In this lesson, you will learn how to configure read preferences in your Node.js driver to account for the time it takes for data to propagate across your database cluster.
Understanding Replication Lag
When you scale your application using a replica set, your primary node handles all writes, which are then asynchronously copied to secondary nodes. Because this copy process isn't instantaneous, a "lag" occurs. If your Node.js application reads from a secondary node immediately after a write, you might fetch stale data—an issue known as an inconsistency.
Configuring Read Preferences
To balance performance and consistency, the MongoDB Node.js driver allows you to set readPreference. You can instruct your client to prioritize speed or accuracy depending on the needs of the specific operation.
For example, if you are building an analytics dashboard where absolute real-time accuracy is less critical than speed, you might allow reading from secondaries. However, if you are updating a user’s balance, you must ensure you are reading the most recent data.
Here is how you configure a connection to prioritize consistency:
const { MongoClient } = require('mongodb');
// 'primary' ensures you always read the most recent data
const client = new MongoClient(uri, {
readPreference: 'primary'
});
async function run() {
await client.connect();
const db = client.db('shop');
// This operation is guaranteed to see the latest write
const user = await db.collection('orders').findOne({ userId: 123 });
}
Choosing the Right Strategy
primary: The safest option. Reads always go to the primary node. This eliminates inconsistency issues caused by replication lag but increases the load on your primary node.secondaryPreferred: The performant option. It attempts to read from a secondary node to reduce the primary's workload. Use this only for data where being a few milliseconds behind the primary is acceptable, such as user profiles or blog post content.primaryPreferred: A balanced approach that defaults to the primary but falls back to secondaries if the primary is unavailable.
Key Takeaway: By configuring read preferences in your Node.js driver, you explicitly choose between the trade-off of high availability and the absolute consistency of your data.