Tuning consistency vs performance in MongoDB - Performance Comparison
When tuning MongoDB, we often balance how fast operations run with how reliable the data is. This affects how long queries and writes take.
We want to understand how changing consistency settings impacts the time it takes to complete database operations.
Analyze the time complexity of a write operation with different write concern settings.
// Insert a document with different write concerns
const writeResult = db.collection.insertOne(
{ name: "Alice", age: 30 },
{ writeConcern: { w: 1, j: true } } // waits for journal commit
);
This code inserts one document and waits for the write to be confirmed by the primary and journaled to disk.
Look at what repeats or takes time during the write:
- Primary operation: Waiting for the write to be acknowledged and journaled.
- How many times: Once per write, but the waiting time depends on disk speed and replication.
As the number of writes increases, the total waiting time grows roughly linearly because each write waits for confirmation.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 waits for confirmation |
| 100 | 100 waits for confirmation |
| 1000 | 1000 waits for confirmation |
Pattern observation: More writes mean more waiting time, growing in a straight line with the number of writes.
Time Complexity: O(n)
This means the total time grows directly with the number of write operations because each waits for confirmation.
[X] Wrong: "Increasing write concern does not affect write speed much."
[OK] Correct: Higher write concern means waiting for more confirmations, which adds waiting time and slows down writes.
Understanding how consistency settings affect operation time helps you explain trade-offs clearly. This skill shows you can balance speed and reliability in real projects.
"What if we change write concern from waiting for one node to waiting for all nodes? How would the time complexity change?"