Write concern basics in MongoDB - Time & Space Complexity
When we write data to MongoDB, the write concern controls how the system confirms the write.
We want to understand how the time to confirm a write changes as we adjust write concern settings.
Analyze the time complexity of this write operation with write concern.
db.collection.insertOne(
{ name: "Alice", age: 30 },
{ writeConcern: { w: 2, wtimeout: 5000 } }
)
This code inserts one document and waits for confirmation from 2 servers before returning.
Look at what repeats or waits during this write.
- Primary operation: Waiting for acknowledgments from multiple servers.
- How many times: The client waits for responses from w servers (here, 2).
As the number of servers to confirm increases, the waiting time can grow.
| Write Concern w | Approx. Wait Time |
|---|---|
| 1 (primary only) | Shortest wait |
| 2 | Longer wait, waiting for 2 servers |
| 3 or more | Even longer, waiting for more servers |
Pattern observation: More servers to confirm means longer wait time, roughly growing linearly with w.
Time Complexity: O(w)
This means the time to confirm a write grows roughly in proportion to the number of servers we wait for.
[X] Wrong: "Waiting for more servers doesn't affect write speed much because writes happen instantly."
[OK] Correct: Each additional server adds network and processing time to confirm the write, so waiting for more servers increases total time.
Understanding how write concern affects response time helps you explain trade-offs between speed and data safety in real projects.
"What if we change write concern from waiting for 2 servers to waiting for all servers in the cluster? How would the time complexity change?"