We adjust settings to find a good balance between how accurate data is and how fast the database works.
0
0
Tuning consistency vs performance in MongoDB
Introduction
When you want your app to show the newest data immediately.
When you need your database to respond very fast, even if data might be a bit old.
When you want to make sure data is saved safely before moving on.
When your app can handle small delays in data updates to improve speed.
When you want to avoid losing data during unexpected failures.
Syntax
MongoDB
db.collection.find().readConcern('level') db.collection.insertOne(document, { writeConcern: { w: number, j: boolean } })
readConcern controls how fresh the data you read is.
writeConcern controls how sure you want to be that your data is saved.
Examples
Reads data from the node without waiting for replication. Fast but may be less consistent.
MongoDB
db.orders.find().readConcern('local')Reads data that has been confirmed by most nodes. More consistent but can be slower.
MongoDB
db.orders.find().readConcern('majority')Writes data and waits for acknowledgment from the primary only. Faster but less safe.
MongoDB
db.orders.insertOne({item: 'book'}, { writeConcern: { w: 1, j: false } })Writes data and waits for confirmation from most nodes and disk journal. Safer but slower.
MongoDB
db.orders.insertOne({item: 'book'}, { writeConcern: { w: 'majority', j: true } })Sample Program
This inserts a pen item quickly, waiting only for the primary node to confirm. Then it reads data without waiting for replication, so it is fast but less strict on consistency.
MongoDB
db.inventory.insertOne({ item: 'pen', qty: 50 }, { writeConcern: { w: 1, j: false } })
db.inventory.find().readConcern('local')OutputSuccess
Important Notes
Choosing stronger consistency usually means slower performance.
Weaker consistency can improve speed but risks showing outdated data.
Adjust these settings based on what your app needs most: speed or accuracy.
Summary
Tuning consistency vs performance means choosing how fresh and safe your data should be.
Use readConcern to control data freshness when reading.
Use writeConcern to control data safety when writing.