What you'll learn: By the end of this lesson you will be able to explain why a read replica can return data older than a write the same user just made, name the session guarantees that break (read-your-writes and monotonic reads), compare four ways to route reads that restore them (primary window, position token, sticky replica, synchronous apply), and choose a policy for ShopStream's account and order screens without sending all traffic back to the primary.
A head office pins a new notice on its board and sends copies to the branch boards by courier. A manager pins a notice, walks to the nearest branch board a minute later, and finds the old notice still up. Nothing was lost: the courier has not arrived yet. The manager's complaint is not "the notice is missing everywhere" but "I just changed this and I cannot see my own change."
That is replication lag, seen from one user. The replication lesson introduced leader-follower copies and lag. Consistency models named the guarantees in general. This lesson is the dedicated treatment of one practical question: when reads go to replicas, how do you keep one user's reads consistent with that user's own writes? The quorum arithmetic for leaderless stores is in quorum reads and writes, so it is not repeated here.
Verified on 2026-12-01 against the PostgreSQL 18 manual, the MongoDB and Amazon DynamoDB documentation and Werner Vogels' article on eventual consistency. The lab on this page is an in-memory model, not a database: it shows the logic of the routing policies and does not measure any product.
The core idea
With asynchronous replication, a write is acknowledged by the primary before the replicas have applied it, so a read sent to a replica in that gap returns older data. The fix is to make each read say what it needs to see, and to send it only where that is already true. Everything below is a way of carrying that need: a time window, a log position, a pinned replica, or a commit that waits.
Three illustrations run through the lesson, each labelled:
- Minimal example: one price changes from 120 to 130 and two replicas catch up at different speeds; the lab prints which read sees what.
- Realistic example: ShopStream's account and order screens behind read replicas.
- Failure example: every replica falls behind at once and a correct policy sends all reads to the primary.
Why a replica is behind
PostgreSQL's manual says streaming replication "is asynchronous by default", with "a small delay between committing a transaction in the primary and the changes becoming visible in the standby". On the standby, "there will be a measurable delay between primary and standby", and the page calls the standby's data "eventually consistent" with the primary. The same page warns that a long-running query "could cause other sessions on the standby server to not see recent changes on the primary, if it delays application of WAL records". So lag is not a constant: it moves with network time, load, and what else the replica is doing.
Figure 1. Writes go to one place, reads can go to several. How to read this: the dashed lines carry the change log to each replica on its own schedule. A read to Replica 2 can see an older state than a read to Replica 1 taken at the same moment.
PostgreSQL gives you ways to see the gap. pg_stat_replication has write_lag, flush_lag and replay_lag, described as the time elapsed between flushing recent WAL locally and receiving notification that the standby has written, flushed or applied it. pg_current_wal_lsn() returns the primary's current write-ahead log write location and pg_last_wal_replay_lsn() returns the last location replayed on a standby. A log position (an LSN in PostgreSQL) is simply a number that only grows, which is what makes the routing policies below possible.
The guarantees that break
Vogels' article defines the two guarantees that matter here. Read-your-writes: after a process updates an item, it "always accesses the updated value and will never see an older value". Monotonic reads: "If a process has seen a particular value for the object, any subsequent accesses will never return any previous values." Session consistency is the practical version: the guarantee holds as long as the session exists. The article adds that if a client reaches the same server every time, "it is relatively easy to guarantee read-your-writes and monotonic reads". A pinned replica is a different node from the one that took the write, which is why the sticky policy below does less than it first seems to.
Figure 2. The gap between "acknowledged" and "applied". How to read this: the first read is not wrong from the replica's point of view, because it has not yet seen the change. It is wrong for this user, who has already been told the write succeeded.
Two symptoms follow, and they need different cures:
- Stale for the writer (read-your-writes broken): the user's own edit is missing.
- Going backwards (monotonic reads broken): the user reads from replica A (current), then from replica B (behind), and the value reverts. This can happen to a user who never wrote anything.
Four ways to route a read
Each policy answers the question "where may this read go?".
| Policy | Rule | Gives | Costs |
|---|---|---|---|
| Any replica | Round robin over replicas | Spreads load | Stale reads and reads that go backwards |
| Primary window | For a short time after a session's write, read the primary | Read-your-writes if the window outlasts the lag | A guessed number; extra primary load |
| Position token | The write returns its log position; a read goes to a replica only if that replica has applied that position, else the primary | Read-your-writes without guessing | The token must travel with the session; fallback load |
| Sticky replica | Pin a session to one replica | Monotonic reads | Not read-your-writes: the pinned replica can still be behind |
A fifth option removes the problem at the write: synchronous apply. PostgreSQL's synchronous_commit = remote_apply makes each commit wait "until replies from the current synchronous standby(s) indicate they have received the commit record of the transaction and applied it, so that it has become visible to queries on the standby(s)". The manual notes that in simple cases this "allows for load balancing with causal consistency". The cost is that every commit waits for that standby, so write latency now includes it. The other levels (on, remote_write, local) do not promise visibility on the standby: on waits for the flush to durable storage, remote_write for the write to the file system, local only for the local flush.
Some databases build the token idea in. MongoDB's causally consistent sessions can provide "read own writes" and "monotonic reads" among four guarantees, but its documentation says that only reads with majority read concern and writes with majority write concern guarantee all four, and that read concern local with write concern { w: 1 } "cannot guarantee causal consistency". DynamoDB offers a per-read choice: reads are eventually consistent by default and may "not reflect the results of a recently completed write", and setting ConsistentRead to true returns "the most up-to-date data"; eventually consistent reads cost half as much as strongly consistent ones.
hurt this user?"} Q1 -->|no| A["Any replica"] Q1 -->|yes| Q2{"Must everyone see
the latest value?"} Q2 -->|yes| B["Primary or synchronous apply"] Q2 -->|no, only the writer| Q3{"Can the request carry
a log position?"} Q3 -->|yes| C["Position token,
fallback to primary"] Q3 -->|no| D["Primary window,
measured against lag"]
Figure 3. A first-pass read policy. How to read this: most reads leave at the first question. The token is the precise answer for the writer; the window is the approximate one when no token can be carried.
Build it: four policies on one timeline
The lab is examples/spring-labs/labs/replication-lag. What it is: an in-memory model. A Primary appends each write to a log with a position (a counter here). Each Replica replays that log in order, but only changes that committed at least its delay ago, on a clock the test moves by hand. A Session remembers the position of its last write. Cluster.read asks a ReadPolicy where to go and reports whether the value was older than the session's own write or older than something it had already read. What it is not: a database or a measurement. The delays (50 ms and 400 ms) are chosen numbers, there is no network, no replay cost and no failover. The HTTP part uses Spring MVC with MockMvc, so no server or Docker is involved.
Run it from examples/spring-labs:
./gradlew :labs:replication-lag:test
The command runs 10 tests, including GoldenRunTest, which compares the report below with examples/spring-labs/golden/replication-lag.txt.
Minimal example: any replica
Alice writes 130 (the price was 120). Replica r1 lags 50 ms, r2 lags 400 ms, and reads rotate between them.
Expected output, captured from a real run (Java 25, Spring Boot 4.1.2, in-memory model, 2026-12-01):
== 1. One session, any replica (r1 lags 50 ms, r2 lags 400 ms) ==
t=0 alice writes price 130 to the primary (log position 2); price was 120 at position 1
t(ms) served price node lsn verdict
10 r1 120 1 STALE (older than own write)
60 r2 120 1 STALE (older than own write)
120 r1 130 2 ok
130 r2 120 1 STALE and BACKWARDS
450 r1 130 2 ok
460 r2 130 2 ok
Alice never sees her own 130 on the first two reads, and the read at 130 ms returns 120 after
the read at 120 ms returned 130: the same session moved backwards in time.
Both symptoms appear in six reads. The read at 130 ms is stale and backwards at once, because r2 is behind r1 and the session had already read r1's newer value.
The four policies side by side
The same writes and the same read times, with a different policy per column. S marks a value older than the session's own write, B a value older than one the session already read. The primary-window policy uses a 500 ms window.
Expected output, captured from a real run (the same run as above):
== 2. Four read policies on the same timeline ==
key: S = older than the session's own write, B = older than a value this session already read
t(ms) any-replica primary-window min-lsn-token sticky-replica
10 r1 120 S primary 130 primary 130 r1 120 S
60 r2 120 S primary 130 r1 130 r1 130
120 r1 130 primary 130 r1 130 r1 130
130 r2 120 S B primary 130 r1 130 r1 130
450 r1 130 primary 130 r1 130 r1 130
460 r2 130 primary 130 r2 130 r1 130
600 r1 130 r1 130 r1 130 r1 130
610 r2 130 r2 130 r2 130 r1 130
policy stale backwards primary r1 r2
any-replica 3 1 0 4 4
primary-window 0 0 6 1 1
min-lsn-token 0 0 1 5 2
sticky-replica 1 0 0 8 0
Read it column by column. Any replica has 3 stale reads and 1 backwards read. The primary window has none, but it sent 6 of 8 reads to the primary, including the ones at 450 and 460 ms that replicas could already have served: a window is a guess, and this one was longer than needed. The position token also has none and used the primary once (at 10 ms, when neither replica had the write), then replicas. The sticky replica never goes backwards, yet its first read is stale: stickiness gave monotonic reads, not read-your-writes.
The token policy is short. choose receives the session's last write position and tries replicas from the round-robin position, taking the first one that has applied it:
List<Replica> replicas = cluster.replicas();
int start = next++;
for (int i = 0; i < replicas.size(); i++) {
Replica candidate = replicas.get((start + i) % replicas.size());
candidate.catchUp(cluster.primary(), nowMillis);
if (candidate.appliedLsn() >= session.lastWriteLsn()) {
return Optional.of(candidate);
}
}
return Optional.empty();
An empty result means "read the primary". That one line is the whole fallback.
The token over HTTP
ProfileController returns the log position in an X-Min-Lsn header on a write. A read that sends the header back is routed with the token policy; a read without it goes to any replica.
Expected output, captured from a real run (the same run):
== 3. The token over HTTP (Spring MVC, MockMvc) ==
t=0 PUT /profiles/ana -> 204, X-Min-Lsn: 3
t=10 GET without the token -> served by r1 node lsn 2, body "Ana, old address"
t=10 GET with the token -> served by primary node lsn 3, body "Ana, new address"
t=450 GET with the token -> served by r2 node lsn 3, body "Ana, new address"
With the token the read waits for nothing: it goes to a replica that has applied position 3
or, if none has yet, to the primary.
The header name here is the lab's own. A real system would carry the position in a cookie, a signed header or a session store, and treat a token from a client as untrusted input.
The failure case: every replica is behind
Both replicas are 5,000 ms behind and Alice reads six times after her write.
Expected output, captured from a real run (the same run):
== 4. Every replica is 5000 ms behind (a lag spike), six reads after a write ==
policy stale backwards primary
any-replica 6 0 0
min-lsn-token 0 0 6
The token policy stays correct and sends every read to the primary: the safety is paid for in primary load.
Correctness and load are the same dial. The token policy trades stale answers for primary traffic, so the primary must be sized for the moment when replicas cannot help.
Trade-offs
| Policy | Strength | Weakness | Wrong when |
|---|---|---|---|
| Any replica | Cheapest, spreads reads | Stale and backwards reads | A user must see their own edit |
| Primary window | Easy, no token | Time guess; wastes primary capacity | Lag can exceed the window |
| Position token | Exact for the writer | Needs a token path and a fallback | Clients cannot carry the token |
| Sticky replica | Monotonic reads | No read-your-writes; uneven load | The pinned replica is the one that lags |
| Synchronous apply | Replicas current when commit returns | Commit waits for the standby | Write latency is the bottleneck |
| Primary only | Always fresh | No read scaling | Read volume exceeds one node |
The other side of this topic
The same problem appears in the browser: a client that shows cached server data after a successful save is making its own read-your-writes decision. See Server State: Caching and Revalidation for how the front end revalidates after a mutation.
In practice: ShopStream account and order screens behind read replicas
This is an educational scenario using ShopStream's shared illustrative numbers.
This is a realistic scenario, not a case history.
The situation
This is the realistic example. ShopStream at stage 2 serves about 2,300 browse requests per second at peak and about 58 checkouts per second (the shared illustrative figures). A load balancer sends reads to two replicas and writes to the primary. Support receives the same complaint daily: "I changed my delivery address and the order page shows the old one", and "my order disappeared from my list after I placed it, then came back".
Starting architecture
Figure 4. The starting point. How to read this: reads and writes are separated by a rule that ignores who is reading. A shopper's own write and the next read can land on different nodes.
Options considered
| Option | Gain | Cost | Wrong when |
|---|---|---|---|
| A. Read account and order screens from the primary | Always fresh | Moves every account read to the primary | Account traffic is large |
| B. Primary window of a few seconds after a write | Small change | A guess; lag spikes exceed it | Lag is unpredictable |
| C. Position token with fallback to the primary | Exact for the writer; browsing stays on replicas | A token path in the API; fallback load | Clients cannot carry the header |
| D. Synchronous apply for the orders database | Replicas current at commit | Every checkout waits for a standby | Checkout latency is already tight |
The decision
Option C for account and order reads, with browsing still on any replica. The write response carries the log position; the web and mobile clients send it on the next reads for a short period; the API routes a read with a token to a replica that has applied it, else to the primary. Checkout confirmation itself reads from the primary. A token from a client is validated, and a missing or invalid token simply means "any replica", never an error.
Figure 5. Routing by token. How to read this: the app server compares the shopper's token with each replica's applied position and sends the read to the first replica that is at least that far along, otherwise to the primary.
Rollout and verification
Ship the token behind a flag for a small share of sessions. Replay a test where a replica is delayed by an injected amount and assert that no account read returns a value older than the session's last write. Track the share of token reads that fell back to the primary and the lag the database reports per replica (in PostgreSQL, pg_stat_replication). Compare the support ticket rate before and after.
The 2 a.m. failure
The page reads: "primary CPU above 90 percent, replica lag rising". A bulk catalogue import (illustrative cause) has put every replica behind, so every token read falls back to the primary.
First checks: replay_lag and the gap between sent_lsn and replay_lsn in pg_stat_replication on the primary; the fallback rate in the app metrics; what else started on the replicas. Mitigation: pause or throttle the import, shed non-essential reads (recommendations, reports) from the primary, and keep token reads correct. Follow-up: a capacity test that sizes the primary for all-reads-on-primary for the account screens, and an alert on replica lag before the fallback rate moves.
Architect's notes
- Ask which reads need which guarantee before choosing a policy for the whole system.
- Measure lag as a distribution, not an average; the tail decides whether a window is safe.
- Size the primary for the fallback. A correct policy hides lag by spending primary capacity.
- Never trust a client token blindly. Treat it as a hint that can only make a read go to the primary more often.
- Test with injected delay. A lag that never happens in staging will happen in production.
Common mistakes
- Assuming replicas are current because lag is usually small.
- Calling sticky sessions a fix for read-your-writes: they stop a session going backwards, not behind.
- Choosing a time window and never revisiting it after the write volume or lag changes.
- Reading a replica after a write inside the same request, for example to re-render the saved item.
- Forgetting that monotonic reads can break for users who only read.
Key takeaways
- Asynchronous replicas acknowledge nothing about when a change becomes visible; reads from them can be behind the user's own write.
- Read-your-writes and monotonic reads are different guarantees with different cures.
- A log position makes the check exact: serve from a replica that has applied it, otherwise from the primary.
- A time window approximates the same fact with a guess.
- Sticky routing gives monotonic reads only.
- Synchronous apply moves the wait to the commit.
- Every policy that protects freshness spends primary capacity when replicas fall behind.
Practice exercises
Exercise 1 (30 min). Run the lab and change the primary window from 500 ms to 100 ms. Which reads become stale and why? Restore the code and run the tests again.
Exercise 2 (1 hour). For ShopStream, list six screens that read replicated data. For each, choose a policy from the table and say what a stale answer would cost the shopper.
Exercise 3 (2 hours). Extend the lab with a policy that advances the clock up to a limit waiting for a replica to catch up before falling back. Report latency and primary reads for the four timelines in this lesson.
Related reading
- Replication: leader-follower copies, lag and failover.
- Consistency models: the guarantees in general.
- Multi-leader and leaderless replication: conflicts when writes are accepted in several places.
- Quorum reads and writes: read and write sets that overlap.
- Server State: Caching and Revalidation: the front-end side of stale data.
Official documentation
- PostgreSQL 18 manual: log-shipping standby servers and hot standby.
- PostgreSQL 18 manual: write-ahead log settings,
synchronous_commitand system administration functions. - PostgreSQL 18 manual: the statistics views,
pg_stat_replication. - Werner Vogels, Eventually Consistent.
- MongoDB manual: causal consistency and read and write concerns.
- Amazon DynamoDB: read consistency.