Write concern levels (w: 1, majority) in MongoDB - Time & Space Complexity
When we write data to MongoDB, the database confirms the write in different ways.
We want to understand how the time to confirm a write changes with different write concern levels.
Analyze the time complexity of these write operations with different write concerns.
// Write with w:1 (acknowledge from primary only)
db.collection.insertOne({name: "Alice"}, {writeConcern: {w: 1}})
// Write with w: "majority" (acknowledge from majority of nodes)
db.collection.insertOne({name: "Bob"}, {writeConcern: {w: "majority"}})
This code writes a document and waits for confirmation from either the primary node or the majority of nodes.
Look at what happens behind the scenes when confirming writes.
- Primary operation: Waiting for acknowledgments from nodes.
- How many times: For w:1, once from primary; for w: "majority", from multiple nodes.
The time to confirm a write depends on how many nodes must respond.
| Input Size (n) | Approx. Operations |
|---|---|
| 3 nodes | w:1 waits for 1 response; w:majority waits for 2 responses |
| 5 nodes | w:1 waits for 1 response; w:majority waits for 3 responses |
| 7 nodes | w:1 waits for 1 response; w:majority waits for 4 responses |
Pattern observation: w:1 time stays the same; w:majority time grows roughly with half the number of nodes.
Time Complexity: O(w)
This means the time to confirm a write grows with the number of nodes that must acknowledge it.
[X] Wrong: "Waiting for majority is always the same speed as waiting for one node."
[OK] Correct: Majority requires more nodes to respond, so it usually takes longer than just one node.
Understanding how write concern affects response time helps you explain trade-offs between speed and data safety in real systems.
"What if we changed write concern to w: 0 (no acknowledgment)? How would the time complexity change?"