Write concern and data durability in MongoDB - Time & Space Complexity
When we use write concern in MongoDB, it controls how many servers confirm a write before we consider it done.
We want to understand how this affects the time it takes to complete a write as data grows.
Analyze the time complexity of this MongoDB write with write concern.
db.collection.insertOne(
{ name: "Alice", age: 30 },
{ writeConcern: { w: 3, wtimeout: 5000 } }
)
This code writes one document and waits for confirmation from 3 servers or times out after 5 seconds.
Look at what repeats when confirming the write.
- Primary operation: Waiting for acknowledgments from multiple servers.
- How many times: Equal to the number of servers specified by
w(here, 3 times).
As the number of servers to confirm increases, the time to complete the write grows roughly in a straight line.
| Number of Servers (w) | Approx. Confirmation Steps |
|---|---|
| 1 | 1 confirmation |
| 3 | 3 confirmations |
| 10 | 10 confirmations |
Pattern observation: More servers to confirm means more waiting steps, growing linearly.
Time Complexity: O(w)
This means the time to finish a write grows linearly with the number of servers that must confirm it.
[X] Wrong: "Waiting for more servers to confirm doesn't affect write time much."
[OK] Correct: Each additional server adds waiting time, so more confirmations mean longer write completion.
Understanding how write concern affects time helps you explain trade-offs between speed and safety in real systems.
"What if we change write concern from waiting for multiple servers to just one? How would the time complexity change?"