In this lesson, you will learn how to prevent your application from accidentally serving stale data by using versioning and sequence numbers within your read-write workflows.
When working with read-replicas in a weakly consistent system, there is often a time lag between a write on the leader and the replication of that data to followers. If a user performs an update and immediately refreshes their page, a load balancer might route them to a replica that hasn't received the update yet, resulting in a "stale read."
To combat this, we implement Version Checks or Sequence Numbers (often called "log sequence numbers" or LSNs).
How it works
- The Write: When the application writes to the leader, the database returns a unique version identifier or a transaction sequence number associated with that specific commit.
- The Metadata: The application stores this version identifier (often in a session cookie or a cache).
- The Read: When the application queries a replica, it sends this version number along with the request.
- The Validation: The replica compares the requested version with its own current state. If the replica’s LSN is behind the requested version, it has two choices: wait until it catches up, or redirect the request back to the leader to ensure the user sees the most recent data.
Implementation Illustration
Consider an application that updates a user profile:
-- Application receives a version stamp from the write
-- SET @last_seen_version = 105;
-- When reading from a replica, we check consistency:
SELECT data
FROM users
WHERE id = 123
AND version_id >= 105;
If the replica returns empty (because its version_id is only 104), the application knows it is looking at stale data. It can then choose to either inform the user that a sync is in progress or force a fetch from the leader. By attaching these sequence markers to our read operations, we decouple the application's correctness from the inherent replication lag of the underlying cluster.
Key Takeaway: By tracking version numbers or sequence stamps, applications can detect and reject stale data from replicas, ensuring that users only interact with information that meets their required level of consistency.