Introducing Dragonfly Cloud! Learn More

Question: Is MongoDB replication synchronous?


MongoDB employs an asynchronous replication model for data redundancy and high availability. This means that when a write operation occurs on the primary node of a replica set, MongoDB does not wait for the data to be copied to the secondary nodes before acknowledging the write operation as successful. Instead, the primary node writes the operation to its operation log (oplog), and then the secondary nodes asynchronously pull this operation from the oplog and apply it to their data sets.

This asynchronous replication allows for high throughput and low latency on write operations since the primary does not need to wait for all secondaries to confirm the write. However, it can lead to a brief period where the data is not yet replicated to the secondary nodes, leading to potential data loss if the primary fails before the secondaries have caught up.

For situations where stronger consistency is required, MongoDB offers write concern options that allow developers to specify that a write operation must be acknowledged by a certain number of replicas before considering the operation successful. For instance, setting a write concern of { w: "majority", j: true } ensures that the write operation is replicated to the majority of nodes in the replica set and written to the journal (for durability) before the operation is acknowledged as successful.

Example of a write concern in a MongoDB insert operation:

db.collection.insertOne( { item: "example", qty: 100 }, { writeConcern: { w: "majority", j: true } } );

In summary, while MongoDB's replication is inherently asynchronous for efficiency and performance, it provides mechanisms such as write concerns to achieve stronger consistency when needed.

Was this content helpful?

White Paper

Free System Design on AWS E-Book

Download this early release of O'Reilly's latest cloud infrastructure e-book: System Design on AWS.

Free System Design on AWS E-Book

Start building today 

Dragonfly is fully compatible with the Redis ecosystem and requires no code changes to implement.