Replication lag and stale reads
A replica returns the past
Section titled “A replica returns the past”The PostgreSQL documentation on standby servers says it plainly: the data on a standby takes some time to arrive from the primary, so running the same query almost at the same moment on both can return different results, and the data on the standby is eventually consistent with the primary. It adds that a long-running query on a standby can delay the application of changes, so that sessions there do not see recent changes.
“Different results” is not one problem. Three different things go wrong, and a different fix removes each.
- A stale read returns data that has been changed since: a newer acknowledged write exists.
- A read that misses the reader’s own write: you saved something, reloaded the page and it is not there.
- A read that goes back in time: you read a value, read again and get an older one, because the second read reached a replica that is further behind.
Mental model. Several mirrors reflect the same room, each a little late and none of them equally late. Ask a different mirror each time and the room seems to jump backwards. Ask the mirror that is on the primary’s wall and you see the room as it is.
Five ways to route reads
Section titled “Five ways to route reads”In this lab Alice writes three times and reads each write back 50 ms later. Bob only reads, four times. The replicas lag by 100 ms and 400 ms. The control Where reads go chooses the rule, and the figures count how many of the seven reads were stale, how many missed Alice’s own write and how many went back in time.
Alice writes three times and reads each write back 50 ms later. Bob only reads. Choose where the reads go and see who gets stale, missing or out-of-order answers.
- A write on its way to a replica
- A write sent to bring a node level
- A write that never arrives
- A link cut by a network partition
- A write the node has just accepted
- A write acknowledged to its client
- A write the node refused
- A read, with the number of the write it returned
Each square is a write, filled once the node has applied it.
Every replica has applied every write.
What the run came to
- Reads
- 7
- Stale reads
- 5 of 7
- Reads that missed the reader’s own write
- 3 of 7
- Reads that went back in time
- 2 of 7
- Reads answered by the primary
- 0 of 7
- Time to acknowledge a write
- At once
| Node | Role | State | Writes applied |
|---|---|---|---|
| Node 1 | Primary | Accepting writes | 1, 2 and 3 |
| Node 2 | Replica | In sync | 1, 2 and 3 |
| Node 3 | Replica | In sync | 1, 2 and 3 |
Event log: every event of the run, in order
| Time in the run | Event |
|---|---|
| 100 ms | Write 1 (Alice) is accepted by Node 1. |
| 100 ms | Write 1 (Alice) is acknowledged at once. |
| 150 ms | Read (Alice): Node 2 has no write to answer with. The answer is stale (newer acknowledged writes: 1). It misses the reader’s own last write. |
| 200 ms | Node 2 applies write 1. |
| 500 ms | Node 3 applies write 1. |
| 600 ms | Write 2 (Alice) is accepted by Node 1. |
| 600 ms | Write 2 (Alice) is acknowledged at once. |
| 650 ms | Read (Alice): Node 3 answers with write 1. The answer is stale (newer acknowledged writes: 1). It misses the reader’s own last write. |
| 700 ms | Node 2 applies write 2. |
| 750 ms | Read (Bob): Node 2 answers with write 2. |
| 800 ms | Read (Bob): Node 3 answers with write 1. The answer is stale (newer acknowledged writes: 1). It is older than data the reader has already seen. |
| 1,000 ms | Node 3 applies write 2. |
| 1,100 ms | Write 3 (Alice) is accepted by Node 1. |
| 1,100 ms | Write 3 (Alice) is acknowledged at once. |
| 1,150 ms | Read (Alice): Node 2 answers with write 2. The answer is stale (newer acknowledged writes: 1). It misses the reader’s own last write. |
| 1,200 ms | Node 2 applies write 3. |
| 1,250 ms | Read (Bob): Node 2 answers with write 3. |
| 1,300 ms | Read (Bob): Node 3 answers with write 2. The answer is stale (newer acknowledged writes: 1). It is older than data the reader has already seen. |
| 1,500 ms | Node 3 applies write 3. |
Illustrative values, not benchmarks of any real product.
Model notes
Assumptions
- There is one record. Each write gets the next number, in the order clients send them, and a node’s version is the number of the last write it has applied.
- A replica applies a write a fixed time after the primary accepts it: the lag you set. Confirmations travel back at no cost, so an acknowledgement waits only for replicas.
- A primary acknowledges a write once the number of replicas the mode names have applied it. If it cannot reach enough of them it keeps waiting, because it cannot tell slow from gone.
Simplifications
- Three nodes, one record and fixed lags. A real replication stream has delays that vary, batches, backlogs and many records.
- A read returns the last write a node has applied. There are no transactions, and the load that reads put on a node is not counted.
Parameter values are illustrative. They are not benchmarks of any real product.
Here are the outcomes, as the lab shows them. Run each one and check.
| Where reads go | Stale | Missed own write | Went back in time | Answered by the primary |
|---|---|---|---|---|
| Primary only | 0 | 0 | 0 | 7 |
| Any replica, in turn | 5 | 3 | 2 | 0 |
| Sticky replica | 7 | 3 | 0 | 0 |
| Read-your-writes | 2 | 0 | 2 | 3 |
| Monotonic reads | 3 | 3 | 0 | 0 |
Read the table by symptom.
- Reading only from the primary removes all three, and puts every read on one node, which is what the replicas were for.
- Sending a client’s reads to the same replica each time (sticky) stops reads going back in time, because one replica only moves forward. It does nothing for a replica that is behind: all seven reads are stale.
- Read-your-writes sends a read to a replica that has applied the client’s last acknowledged write, or to the primary if none has. Alice never misses her own write, and in the lab the price is that her three reads go to the primary. Bob’s reads are not covered, and two of them still go back in time.
- Monotonic reads send a read to a replica at least as new as the newest data the client has already read. Nothing goes back in time, and Alice can still miss her own write, because she has not read it yet.
Neither guarantee is the other. Which one you need depends on what your users would notice.
Now sort some symptoms.
Challenge
Which guarantee fixes this symptom?
Reads that go to replicas can go wrong in different ways, and each routing rule removes some of them and not the others. Put each symptom under the rule that fixes it, or under the option that neither rule covers.
Sorting needs JavaScript.
Categories
- Read-your-writes
- The client always sees its own acknowledged writes.
- Monotonic reads
- A client never reads older data than it has already read.
- Neither
- Another reader, or data that is simply behind, is not covered by either rule.
Check your answers at least once before looking at the answers.
Can synchronous replication fix it?
Section titled “Can synchronous replication fix it?”Waiting for replicas does remove the stale reads, with a cost. Set When a write is acknowledged to synchronous with reads going to any replica: no read is stale, and none misses Alice’s own write, because a write is not acknowledged until every replica has it. The cost is that a write now waits 400 ms, the lag of the slower replica. Two reads still go backwards, because some reads land on a replica that has not yet applied a write the other already shows, and that write is still waiting for its acknowledgement.
What happens if lag keeps growing?
Section titled “What happens if lag keeps growing?”In the lab the lag is a fixed delay. In a real system, lag is what is left over after the primary and the replica have each done their work, and it can grow. The failure lab below builds that case: the shop from before, with a primary taking the writes and two replicas answering the reads. Normally it writes 180 times a second. A bulk import then multiplies the writes by four, to 720 per second, for 20 seconds. The primary can take that. Each replica can only apply 400 writes per second.
Before you press the button, predict: will anything fail? What will a user see?
Replication lag
The shop sends its writes to one primary and its reads to two replicas. The primary sends every write on to the replicas, and each replica applies them at up to 400 writes a second. The shop normally writes 180 a second, well within that. A bulk import then quadruples the writes to 720 a second, for 20 seconds. The primary can take them. Can the replicas keep up? Watch how far behind they fall, and what the reads they answer return meanwhile. Then decide what you would change and run it again.
The failure lab needs JavaScript. The healthy system is shown below.
1. Break it
The healthy system is shown first. When you press the button the failure strikes, and the run follows the 60 seconds after it.
What the failure does: Four times as many writes arrive as before. The primary can take them. Every replica has to apply every one.
Each dot stands for many requests. The numbers show the real rate.
A dashed arrow is a call the sender does not wait for: the primary sends each write on and carries on.
No bottleneck: every component has headroom.
What happens to the data
Figures from the model at the moment shown. They change as the run plays.
Then, with no one pressing a button: The burst of writes ends after 20 s.
- Replica lag: how old the data a replica returns is
- —
- How long a write takes to reach a replica and be applied. A read answered by the replica returns the database as it was that long ago.
- Writes waiting to be applied
- —
- Writes the replica has received and not yet applied.
- Reads that could be stale, so far
- —
- Reads answered by a replica that was more than 1 s behind, or that was cut off from a primary that went on acknowledging writes. Each could return data that has changed since.
- Writes refused so far
- —
- Writes the primary could not take. The client was told that each one failed.
Cause and effect
Each step leads to the next. A step that is changing right now is marked.
- Traffic900 req/sNormal steady
- API utilisation75%Normal steady
- API queuenone waitingNormal steady
- Latency (p99)101 msNormal steady
- Timeouts and rejections0%Normal steady
- Errors0%Normal steady
| Component | State | Utilisation | Offered (req/s) | Served (req/s) | Rejected (req/s) | p50 | p95 | p99 |
|---|---|---|---|---|---|---|---|---|
| Clients | Healthy | <1% | 900 | 900 | 0 | 0 ms | 0 ms | 0 ms |
| API | Busy | 75% | 900 | 900 | 0 | 14 ms | 60 ms | 93 ms |
| Primary | Healthy | 9% | 180 | 180 | 0 | 2.8 ms | 12 ms | 18 ms |
| Replicas | Healthy | 36% | 720 | 720 | 0 | 5.5 ms | 24 ms | 37 ms |
| Replication | Healthy | 45% | 180 | 180 | 0 | 3.2 ms | 14 ms | 21 ms |
- Traffic
- 900 req/s
- Successful
- 900 req/s
- Error rate
- 0%
- Mean latency
- 28 ms
Sources
Illustrative values, not benchmarks of any real product.
Model notes
Assumptions
- Requests arrive at random, as a Poisson process, at a constant average rate.
- Each node is one queue, served first-come first-served by several identical slots (instances × concurrency).
- Service times are random with the stated mean; by default they are exponentially distributed.
- Each node is analysed separately, with the traffic it receives treated as Poisson.
- The system starts healthy at 900 requests a second. One request in five writes, 180 writes a second, and four in five read, 720 reads a second. Three API instances can serve 1,200 requests a second, the primary 2,000 writes a second, and the two replicas together 2,000 reads a second.
- Replication is asynchronous: the primary acknowledges a write as soon as it has it, and sends it to the replicas without waiting for them. Each replica applies the stream at up to 400 writes a second. The diagram shows one replica's apply stage, since the replicas are alike and fall behind together.
- The link to the replicas takes 250 ms there and back, so a write reaches a replica 125 ms after the primary acknowledged it, and is applied a few milliseconds after that, longer if the replica has a backlog.
- A failure strikes at one instant. Nothing repairs it except the steps the lab lists, which happen at fixed times: no restart, no operator, no autoscaling.
- The burst lasts 20 seconds, and then the writes return to what they were.
Simplifications
- The burst adds writes and nothing else: reads stay at 720 a second, where a real spike would often add reads too.
- A replica may hold up to 10,000 writes it has not applied. The run never gets there, so nothing is cut off.
- A read counts as one that could be stale when the replica that answers it is more than a second behind. Whether a given read is wrong depends on whether it asks for something that changed in that time, which the model does not know.
- The replicas fall behind together, by the same amount. Real replicas can differ, so two reads a moment apart can reach replicas that are not equally behind, and the second can return older data than the first.
- Sending a write to a replica and applying it are one stage with one rate here. Real databases report them separately (PostgreSQL has write, flush and replay lag): what a primary loses when it dies is what never reached a replica, while what a read returns depends on what has been applied.
- A replica applies the stream and answers reads in two separate components, so reads stay fast while it lags. A real replica does both with the same machine.
- Nothing is retried: a write that fails is refused to the client, and the client does not send it again.
- Every replica is the same and falls behind by the same amount. A real replica can be slower than its siblings.
- Above capacity there is no steady state. The model switches to a fluid approximation: the node serves at capacity, its queue grows until it reaches its limit, and further requests are rejected.
- Percentiles assume an exponential tail. A service-time variability other than exponential changes the mean wait but not the shape of the tail.
- A node frees its slot as soon as it has done its own work, before waiting on the services it calls. Real thread-per-request servers hold the slot, so a slow dependency exhausts them faster than this model shows.
- A request calls its dependencies one after another. Parallel fan-out is not modelled.
- When a caller times out and gives up, the callee still finishes the work, so abandoned requests keep consuming capacity.
- Retries add load. Their backoff and jitter decide when that load arrives, which only the per-request simulation shows.
- A caller’s timeout counts the mean time its dependencies take, not their full distribution.
- Latency percentiles for a whole request are estimated, over every request, including those that are rejected and fail quickly. The mean is exact, and the percentiles come from a gamma distribution that has that mean and the variance of the time spent in each component.
Parameter values are illustrative. They are not benchmarks of any real product.
In the run, nothing fails and nothing slows down. The writers get their acknowledgements, the replicas answer reads as fast as ever. The only symptom is old data. The replicas receive 720 writes per second and apply 400, so 320 per second pile up: 6,400 writes are waiting when the burst ends after 20 seconds. The last of them is applied about 16 seconds late, so for a moment a read from a replica returns the database as it was 16 seconds ago. The lab counts 33,480 reads that the replicas answered while more than a second behind, and each could have missed a recent write.
The recovery is slower than the burst. After it, writes are back to 180 per second, so the replicas work off the backlog at the 400 they can apply minus the 180 that keep arriving, which is 220 per second. 6,400 writes at 220 per second take about 29 seconds, longer than the 20-second burst itself.
Try the three fixes, and look at what each costs.
| Fix | What it does to lag | What it costs |
|---|---|---|
| Apply with two workers | Each replica applies 800 per second, above the 720 arriving, so it keeps up | Writes that depend on each other must be applied in order, so a real replica gets less than double; the model gives the full 800 |
| Cap the writes at 350 per second | The replicas keep up, and reads stay fresh | The writes above 350 per second are refused: about 7,200 in this run |
| Add two more replicas | Nothing: each replica applies every write, so each is 16 seconds behind | Two more replicas to pay for, and two more for the primary to send every write to |
The third row is the one to remember. More replicas answer more reads. They do not apply writes any faster, because every replica must apply every write. If the cause of lag is the write rate, only a faster apply, fewer writes, or a different design helps.
- A replica returns what it has applied so far. Three symptoms follow: a stale read, a read that misses the reader’s own write, and a read that goes back in time.
- Read-your-writes fixes the second, monotonic reads fix the third, and neither fixes the other. In the lab, reading from the primary fixes all three at the cost of putting every read on one node.
- Synchronous replication removes stale reads at the price of waiting for the slowest replica, and reads can still go backwards over writes that are not yet acknowledged.
- When writes arrive faster than a replica can apply them, lag grows by the difference: 320 per second in the lab, 6,400 writes after 20 seconds, about 16 seconds of lag.
- More replicas do not reduce that lag. Catching up takes longer than the burst did.
Next: Failover and lost writes.
Your progress
Built by GhaziAlibi.
© ShardCraft. All rights reserved.