Course contentsShow
← Databases & SQL
Lesson 1218 of 1,95311. NoSQL and Document ModelsFree lesson

Read Preference and Data Consistency

Configure read behaviors to balance latency against stale data concerns.

In this lesson, you will learn how to adjust read preferences to balance your application’s need for low-latency performance against the risk of reading stale, outdated data.

Understanding the Trade-off

In a distributed database system, data is often replicated across multiple nodes to ensure high availability. When you perform a write operation, it typically hits a "primary" node first, and then propagates to "secondary" nodes. Because this propagation takes time, there is a window where the secondaries hold slightly older versions of your data.

When your application requests data, you must decide which node to query based on your specific requirements:

  • Primary Read Preference: You always query the primary node. This guarantees you see the most recent write, ensuring strong consistency. However, this increases the load on the primary and may result in higher latency if the primary is geographically distant.
  • Secondary Read Preference: You query secondary nodes. This is excellent for scalability and lowering latency, as you can read from nodes physically closer to the user or spread the read workload across many servers. The trade-off is the potential for eventual consistency, where the user might temporarily see "stale" data because the secondary hasn't caught up with the primary yet.

Configuring Read Behavior

When configuring your database connection, you typically choose a policy that dictates where your read queries are routed. For example, if you are building an analytics dashboard where absolute currency isn't as critical as speed, you might use a secondaryPreferred setting:

// Example of routing reads to secondaries to offload the primary
db.collection('user_activity').find({}).readPref('secondaryPreferred');

By choosing secondaryPreferred, the application will prioritize fast reads from secondary replicas, only falling back to the primary if those replicas are unavailable. If your application handles sensitive operations like financial transactions, you would force the read to the primary to ensure the most current balance is always retrieved.

Key Takeaway: Balancing latency and consistency requires choosing between the guaranteed freshness of primary reads and the high performance of offloading reads to secondary replicas.