Timestamp-Based Consistency Checks
You'll learn how to use timestamps to verify replicas are fresh enough before serving reads.
The Problem We're Solving
In a primary-replica database setup with replication lag, a user might write data to the primary and immediately try to read it from a replica—only to find it missing or stale. We've already seen session-based routing and sticky sessions as solutions. Now let's add another powerful tool: checking timestamps.
How It Works
When the primary writes data, it tags that write with a timestamp (or sequence number). The replica tracks its own "last replicated timestamp"—the most recent write it has successfully applied.
Before serving a read request, your application can:
- Check the timestamp of the write the user just made
- Ask the replica: "Have you caught up to timestamp X yet?"
- If yes, serve the read from that replica
- If no, either wait briefly for it to catch up, or route to the primary (or a more up-to-date replica)
Real-World Analogy
Imagine you mail a letter (write to primary) and immediately call the recipient to discuss it. Before they answer your questions, they check: "Has today's mail arrived yet?" If not, they might wait for the mail truck or ask you to read your copy of the letter instead.
Implementation Pattern
Your app tracks: last_write_timestamp = 1234567890
Replica reports: replica_lag_timestamp = 1234567880
Decision: 1234567880 < 1234567890 → replica is 10 units behind → route elsewhere
Key Takeaway: Timestamp-based consistency checks let you programmatically verify a replica has caught up to a specific write before reading from it, enabling strong consistency guarantees even with asynchronous replication.