Skip to content

Failover and lost writes

When the primary is lost, no node can accept writes. Failover is the act of promoting a replica to be the new primary. It takes three things: noticing that the primary is gone, choosing a replica, and telling everyone else which node is the primary now.

The PostgreSQL documentation is clear about who does what. Failover is triggered by promoting the standby, with pg_ctl promote or pg_promote(). PostgreSQL itself does not provide the software that identifies a primary failure and notifies the standby: you use external tools for that. And after a failover only one server is left, so a standby must be recreated on the former primary or a new machine, which the pg_rewind utility can speed up on large clusters.

Everything about a failover costs something, and the cost has two parts.

  1. Writes fail while there is no primary. From the crash until the promotion, nothing can accept a write.
  2. Writes can be lost. The new primary only has what it had received. A write that the old primary had acknowledged to its client, and not yet shipped, is gone.

Mental model. The clerk who kept the ledger collapses. The next clerk takes over the ledger that they copied. Every line the collapsed clerk wrote and had not yet passed on was never copied. The customers were told those lines were recorded.

In this lab, an application sends a write every 100 ms. Node 1 crashes at 650 ms, and a replica is promoted 500 ms later, at 1,150 ms. The lags are 250 ms for Node 2 and 500 ms for Node 3, and the replication is asynchronous. Node 2 is promoted. Predict first: which writes will the application have been told succeeded and will not be in the new primary?

The primary crashes at 650 ms and a replica is promoted 500 ms later. Writes in between fail. Writes the promoted replica never received are lost, although clients were told they had succeeded.

250 ms
500 ms
When a write is acknowledged

The primary acknowledges a write at once, then ships it to the replicas.

Promote after the crash
2,350 ms
Node 1ReplicaIn syncepoch 2Node 2PrimaryAccepting writesepoch 2Node 3ReplicaIn syncepoch 2
Node 1ReplicaIn syncepoch 2Node 2PrimaryAccepting writesepoch 2Node 3ReplicaIn syncepoch 2
  • 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.

Node 2 is the primary now. It never received these acknowledged writes, so they are lost: 5 and 6.

What the run came to

Writes acknowledged
10 of 15
Writes refused
5Writes: 7, 8, 9, 10 and 11
Acknowledged writes lost
2Writes: 5 and 6
Writes never acknowledged
0
Time to acknowledge a write
At once
The nodes at this moment
NodeRoleStateWrites applied
Node 1ReplicaIn sync1, 2, 3, 4, 12, 13, 14 and 15
Node 2PrimaryAccepting writes1, 2, 3, 4, 12, 13, 14 and 15
Node 3ReplicaIn sync1, 2, 3, 4, 12, 13, 14 and 15
Event log: every event of the run, in order
Every event of the run in time order. Events after the current moment are dimmed.
Time in the runEvent
100 msWrite 1 (the application) is accepted by Node 1.
100 msWrite 1 (the application) is acknowledged at once.
200 msWrite 2 (the application) is accepted by Node 1.
200 msWrite 2 (the application) is acknowledged at once.
300 msWrite 3 (the application) is accepted by Node 1.
300 msWrite 3 (the application) is acknowledged at once.
350 msNode 2 applies write 1.
400 msWrite 4 (the application) is accepted by Node 1.
400 msWrite 4 (the application) is acknowledged at once.
450 msNode 2 applies write 2.
500 msWrite 5 (the application) is accepted by Node 1.
500 msWrite 5 (the application) is acknowledged at once.
550 msNode 2 applies write 3.
600 msNode 3 applies write 1.
600 msWrite 6 (the application) is accepted by Node 1.
600 msWrite 6 (the application) is acknowledged at once.
650 msNode 2 applies write 4.
650 msNode 1 crashes.
700 msWrite 7 (the application) fails: Node 1 is down.
800 msWrite 8 (the application) fails: Node 1 is down.
900 msWrite 9 (the application) fails: Node 1 is down.
1,000 msWrite 10 (the application) fails: Node 1 is down.
1,100 msWrite 11 (the application) fails: Node 1 is down.
1,150 msNode 2 is promoted to primary (epoch 2). Writes it holds: 4. It never received these acknowledged writes, so they are lost: 5 and 6.
1,200 msWrite 12 (the application) is accepted by Node 2.
1,200 msWrite 12 (the application) is acknowledged at once.
1,300 msWrite 13 (the application) is accepted by Node 2.
1,300 msWrite 13 (the application) is acknowledged at once.
1,400 msWrite 14 (the application) is accepted by Node 2.
1,400 msWrite 14 (the application) is acknowledged at once.
1,500 msWrite 15 (the application) is accepted by Node 2.
1,500 msWrite 15 (the application) is acknowledged at once.
1,650 msNode 3 catches up and applies write 2.
1,650 msNode 3 catches up and applies write 3.
1,650 msNode 3 catches up and applies write 4.
1,700 msNode 3 applies write 12.
1,800 msNode 3 applies write 13.
1,900 msNode 3 applies write 14.
2,000 msNode 3 applies write 15.
2,200 msNode 1 comes back up.
2,200 msNode 1 learns that Node 2 is the primary and becomes its replica.
2,200 msNode 1 discards the writes the primary does not have: 5 and 6. Clients had been told these succeeded: 5 and 6.
2,350 msNode 1 catches up and applies write 12.
2,350 msNode 1 catches up and applies write 13.
2,350 msNode 1 catches up and applies write 14.
2,350 msNode 1 catches up and applies write 15.

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.
  • A write that is still travelling when its sender crashes, or when a partition cuts the link, never arrives.
  • Failover is a step of the script: a chosen replica is promoted at a fixed time. The other replicas follow it and are made to match its history.
  • A node that comes back, or rejoins after a partition, steps down and discards whatever the new primary does not have. The history of the newest epoch is the one that survives.

Simplifications

  • Three nodes, one record and fixed lags. A real replication stream has delays that vary, batches, backlogs and many records.
  • The failure detector is a fixed delay. Real ones trade a quicker promotion against false alarms.
  • Nothing is recovered from the old primary’s disk. In practice its extra writes could be recovered by hand, which the model does not show.

Parameter values are illustrative. They are not benchmarks of any real product.

Writes 7 to 11, sent between 700 ms and 1,100 ms, are refused: there is no primary to take them. That is the first cost.

The second cost is the one that matters. Node 2 holds writes 1 to 4 when it is promoted. Writes 5 and 6 had been sent at 500 and 600 ms and acknowledged at once, and they were still on their way to Node 2, which applies a write 250 ms after the primary. They never arrive: a write that is still travelling when its sender crashes is lost. Clients were told they had succeeded. When Node 1 comes back, it learns it is not the primary and discards them.

Now change Promote after the crash to Node 3. Node 3 lags 500 ms, so it holds only write 1: writes 2 to 6 are lost, five acknowledged writes instead of two. Choosing which replica to promote is a decision about data: promoting the most up-to-date replica loses the least.

Now change When a write is acknowledged.

Mode Promote Node 2 Promote Node 3 A write is acknowledged after
Asynchronous writes 5 and 6 lost writes 2 to 6 lost at once
Semi-synchronous none lost writes 2 to 4 lost 250 ms at first, and 500 ms once Node 1 is gone and only Node 3 is left to confirm
Synchronous none lost none lost 500 ms

With synchronous replication no acknowledged write can be lost, because a write is only acknowledged once both replicas have it, and the price is that each write waits 500 ms. With semi-synchronous replication the write is on at least one replica, which makes losing it a matter of which replica you promote. Promote Node 2, the quicker one, and nothing is lost. Promote Node 3 and you lose three writes.

In the lab, the writes that were not acknowledged are not counted as lost. With semi-synchronous replication, writes 5 and 6 were never acknowledged because Node 2 had not confirmed them, so they were not promised, and they are discarded. The client had been told nothing, and can retry.

The PostgreSQL documentation states the same trade-off for the real thing. With asynchronous replication there is a window in which data is lost if the primary crashes before the data is shipped, and synchronous replication means data loss is only possible if both the primary and the standby crash at the same time.

What happens if you want the failover to be faster?

Section titled “What happens if you want the failover to be faster?”

The failure lab below has the same shape on a bigger scale. The shop sends writes to a primary and reads to two replicas. At 180 writes per second, the primary is killed, and a replica is promoted after 30 seconds. The replica is 250 ms away, there and back. Predict the outage in seconds, the writes refused, and the acknowledged writes lost.

Kill the primary (failover)

The shop sends its writes to one primary database and its reads to two replicas. Replication is asynchronous: the primary tells the client a write succeeded as soon as it has it, and sends it on to the replica, which is far away, 250 ms there and back. You kill the primary. Writes fail until a replica is promoted, which takes 30 seconds from the failure here. Watch the writes that fail, then count the writes the primary had acknowledged that the replica never received. Then decide what you would have built differently and run the same failure 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: The primary database stops answering. Writes have nowhere to go until a replica is promoted. Reads carry on.

Replica servers0.3 ms0.5 ms0.5 ms250 msClientsHealthy<1%APIBusy75%PrimaryHealthy9%ReplicasHealthy36%ReplicationHealthy45%
Replica servers0.3 ms0.5 ms0.5 ms250 msClientsHealthy<1%APIBusy75%PrimaryHealthy9%ReplicasHealthy36%ReplicationHealthy45%

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.

0 ms
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: A replica is promoted to primary after 30 s.

Writes have been failing for
—
The seconds in which more than half of the writes were refused.
Writes refused so far
—
Writes the primary could not take. The client was told that each one failed.
Acknowledged writes the replica never received
—
Writes the primary had told clients succeeded that had not reached the replica when it died: the writes still on their way. A primary that waits for the replica has not acknowledged them yet.
Time a write takes at the database
—
From the API to the primary, and to the replica too when the primary waits for it.

Cause and effect

Each step leads to the next. A step that is changing right now is marked.

Metrics
ComponentStateUtilisationOffered (req/s)Served (req/s)Rejected (req/s)p50p95p99
ClientsHealthy<1%90090000 ms0 ms0 ms
APIBusy75%900900014 ms60 ms93 ms
PrimaryHealthy9%18018002.8 ms12 ms18 ms
ReplicasHealthy36%72072005.5 ms24 ms37 ms
ReplicationHealthy45%18018003.2 ms14 ms21 ms
Traffic
900 req/s
Successful
900 req/s
Error rate
0%
Mean latency
28 ms

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.
  • A replica is promoted 30 seconds after the failure. The figure is illustrative: it stands for noticing that the primary is gone, then promoting a replica. A fix can shorten it.

Simplifications

  • Nothing detects the failure and no one decides: the promotion comes at a fixed time. How long a real failover takes depends on how the failure is detected and who promotes.
  • The promoted replica takes over at once with everything it received, and the old primary never returns. A real failover must also stop the old primary from accepting writes if it comes back, which the PostgreSQL documentation calls STONITH. This lab does not simulate that, or the two-primaries situation it prevents.
  • Every acknowledged write that the promoted replica did not have counts as lost. Some may still be on the failed primary’s disk, if it can be read.
  • Promoting a replica takes it out of the replicas, so the reads that remain run on one. Nothing replaces it during the run.
  • 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, writes fail for 30 seconds and 5,400 writes are refused, which is 180 per second for 30 seconds. About 23 acknowledged writes are lost: a write takes 125 ms to reach the replica, so at 180 per second about 23 writes are on their way at any moment, and those are gone. Reads are unaffected, because the replicas answer them, so one request in five fails, which is the writes.

Each fix has a price, and the lab shows it.

Fix What it protects What it costs
Detect and promote after 10 seconds instead of 30 Writes fail for 10 seconds, so 1,800 are refused instead of 5,400 Still about 23 writes lost. A primary that is only slow can be declared dead, and then two nodes may both believe they are primary
A replica close to the primary (2 ms there and back) About 1 write lost instead of about 23 A replica next to the primary shares whatever takes the primary down, such as a data centre
Wait for the replica before acknowledging No write lost A write takes about 259 ms instead of 4.5 ms, and writes wait if the replica cannot be reached

The first fix shortens the outage and does not change what is lost. The second reduces the loss and does not shorten the outage. The third removes the loss at the price of every write. None of them is free, and they address different problems. The PostgreSQL documentation says that the old primary has to be told it is no longer the primary, which it calls STONITH, because otherwise both systems may think they are primary, and that causes data loss. That is the next lesson.

  • Failover promotes a replica. While there is no primary, writes fail: five writes in the first lab, 5,400 in the failure lab.
  • The promoted replica only has what it received. Acknowledged writes still on their way are lost: two when Node 2 is promoted and five when Node 3 is, in the first lab, and about 23 in the failure lab.
  • Promoting the most up-to-date replica loses the least, and synchronous replication loses none, at the price of a wait on every write.
  • Faster detection shortens the outage, a nearer replica shrinks the loss, synchronous replication removes it. Each has a price.

Next: Split brain.

Your progress

Built by GhaziAlibi.

© ShardCraft. All rights reserved.