mongodb runtime_error ai_generated true

MongoServerError: not master and slaveOk=false

ID: mongodb/replica-set-election-hiccup

Also available as: JSON · Markdown · 中文
85%Fix Rate
85%Confidence
1Evidence
2023-06-15First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
mongodb-3.6 active
mongodb-4.0 active
mongodb-4.2 active
mongodb-4.4 active
mongodb-5.0 active
mongodb-6.0 active
mongodb-7.0 active

Root Cause

A secondary replica set member received a write operation or a read without slaveOk enabled during an election.

generic

中文

在选举期间,从节点收到了写操作或未启用 slaveOk 的读操作。

Official Documentation

https://www.mongodb.com/docs/manual/reference/method/rs.slaveOk/

Workarounds

  1. 85% success Implement automatic retry with exponential backoff for write operations, and use readPreference=secondaryPreferred for reads. Example in Node.js: await collection.insertOne(doc, { w: 'majority', wtimeout: 5000 }).catch(e => { if (e.codeName === 'NotMaster') { /* retry after 1s */ } })
    Implement automatic retry with exponential backoff for write operations, and use readPreference=secondaryPreferred for reads. Example in Node.js: await collection.insertOne(doc, { w: 'majority', wtimeout: 5000 }).catch(e => { if (e.codeName === 'NotMaster') { /* retry after 1s */ } })
  2. 90% success Use MongoDB driver's built-in retryWrites and retryReads options (enabled by default in 4.2+). Configure connection string: mongodb://host1,host2,host3/?retryWrites=true&retryReads=true
    Use MongoDB driver's built-in retryWrites and retryReads options (enabled by default in 4.2+). Configure connection string: mongodb://host1,host2,host3/?retryWrites=true&retryReads=true
  3. 75% success Ensure at least 3 voting members in the replica set to avoid elections causing extended unavailability.
    Ensure at least 3 voting members in the replica set to avoid elections causing extended unavailability.

中文步骤

  1. Implement automatic retry with exponential backoff for write operations, and use readPreference=secondaryPreferred for reads. Example in Node.js: await collection.insertOne(doc, { w: 'majority', wtimeout: 5000 }).catch(e => { if (e.codeName === 'NotMaster') { /* retry after 1s */ } })
  2. Use MongoDB driver's built-in retryWrites and retryReads options (enabled by default in 4.2+). Configure connection string: mongodb://host1,host2,host3/?retryWrites=true&retryReads=true
  3. Ensure at least 3 voting members in the replica set to avoid elections causing extended unavailability.

Dead Ends

Common approaches that don't work:

  1. 70% fail

    This bypasses read preference and may cause stale reads; it does not fix write failures during elections.

  2. 90% fail

    Restarting does not resolve the transient election state; it may cause longer downtime.

  3. 60% fail

    Without proper retry logic with backoff, this can overwhelm the server during elections.