How does MongoDB handle data consistency?

Instruction: Discuss MongoDB's approach to ensuring data consistency across its distributed database system.

Context: The question targets the candidate's knowledge of MongoDB's consistency models, including the trade-offs between consistency, availability, and partition tolerance (CAP theorem).

Updated

Official answer

MongoDB consistency depends on the operation, replica-set state and selected concerns. Calling it simply an "eventually consistent AP database" hides important guarantees and failure behavior. Replica-set writes go to the primary; secondaries replicate asynchronously. A partition can prevent elections or the acknowledgments an operation requires, so applications must handle temporary unavailability.

Distinguish three controls:

  • Read preference selects eligible replica-set members. The default is primary; secondary reads can lag. Selecting the primary alone does not establish linearizability, including during a partition when a former primary has not recognized its demotion.
  • Write concern specifies the required write acknowledgment. w: "majority" waits for the required majority acknowledgment; durability also depends on the deployment's journaling configuration. A write-concern timeout does not undo a write that already occurred, so an error can leave an uncertain outcome.
  • Read concern determines which data may be returned. local can expose data that later rolls back. Outside transactions, majority reads majority-committed data, but does not promise the newest value in the system.

For causally ordered operations, use a causally consistent session with majority read concern and majority write concern to obtain the documented causal guarantees, including reading your own writes. Execute operations sequentially within the session; do not use that session concurrently from multiple threads. This preserves causal order; it is not a global serial order for unrelated operations.

As a separate option outside causally consistent sessions, MongoDB documents linearizable reads on the primary together with majority writes for real-time ordering of reads and writes to a single document. Use a stable unique selector such as _id and a bounded maxTimeMS; this stronger guarantee can require additional coordination and can fail when the required members are unavailable. Do not generalize it into serializable multi-document reads.

For a multi-document invariant, consider a transaction and its supported read/write concerns separately. Under a network partition, CAP concerns the conflict between linearizable consistency and availability for every request; it is not a permanent "choose any two" label for all operations. Choose the needed guarantee, test failure and retry behavior, and measure latency. Daily active users are not evidence of a database consistency guarantee.

Sources

MongoDB: read isolation, consistency and recency; read concern; write concern.

Related Questions