Sub topic 10
Replicating state: synchronous versus asynchronous
Redundant servers are easy to add when they hold no data. Once they hold state, such as database rows, queue messages, or files, every copy has to be kept up to date. This chapter covers how replication works, what each mode costs, and how the mode you pick sets how much data a failover can lose.
This chapter assumes you know what a primary and a replica are, have seen a write-ahead log or similar append-only log, and understand timeouts and health checks. Later chapters cover RTO and RPO targets, quorum, and split brain in detail. Here we only use them where they explain the replication trade-off.
What replication does
Replication means sending each change made on one node (the primary) to one or more other nodes (the replicas). Most systems ship an ordered log of changes, and replicas apply them in the same order. A replica that has applied every change is up to date. A replica that is behind has replication lag.
The key design question is simple. When does the primary tell the client "your write succeeded"?
- Synchronous replication: the primary waits until at least one replica confirms it has the change. Only then does it acknowledge the client.
- Asynchronous replication: the primary commits locally, acknowledges the client, and sends the change to replicas afterward.
Synchronous replication
With synchronous replication, an acknowledged write exists on at least two nodes. If the primary dies right after the acknowledgment, the replica has the data. Nothing the client was told was saved is lost.
This has two costs.
- Latency. Every write pays a network round trip to the replica, plus the replica's time to store the change. Within one zone this is often around a millisecond. Across regions it can be tens to over a hundred milliseconds, and every write pays it.
- Availability coupling. If the replica is down or unreachable, the primary cannot confirm writes. A strict design stops accepting writes. That can turn a replica failure into an outage, which defeats the purpose of redundancy.
Two steps lessen the availability problem. Systems usually keep several replicas and require only some of them to confirm. They may also fall back to asynchronous mode after a timeout. Falling back restores availability but gives up the guarantee, so treat it as a deliberate choice, not a default.
Asynchronous replication
With asynchronous replication, the primary's write speed does not depend on the replicas. A slow or dead replica does not block writes. This is why async is the usual choice across regions.
The cost is a window of exposure. Changes that were acknowledged but not yet shipped exist only on the primary. If the primary fails and you promote a replica, those changes are gone. The size of the window equals the replication lag at the moment of failure.
Lag is not constant. It grows during write bursts, long-running transactions on the replica, network congestion, and bulk jobs. A system that averages 50 ms of lag can show 30 seconds during a batch import. Plan for the worst lag you observe, not the average.
Semi-synchronous and quorum modes
Many databases offer middle options.
- Semi-synchronous: the primary waits for one replica to confirm it received and durably stored the change, but not that it applied the change. This cuts latency and still protects against losing the primary.
- Quorum commit: the primary waits for any N of M replicas. One slow replica does not stall writes, and a copy exists on several nodes.
- Consensus replication: systems built on a protocol such as Raft commit a write only when a majority of nodes have stored it. This is quorum commit with built-in leader election. The quorum chapter covers it.
PostgreSQL shows these options in its settings. The following example requires confirmation from any one of two named standbys, then checks the lag.
ALTER SYSTEM SET synchronous_standby_names = 'ANY 1 (replica_a, replica_b)';
ALTER SYSTEM SET synchronous_commit = 'on';
SELECT pg_reload_conf();
SELECT application_name, state, sync_state, replay_lag
FROM pg_stat_replication;With synchronous_commit = 'on', a commit waits until the standby has flushed the change to disk. remote_apply waits until the change is visible to queries on the standby. remote_write waits for less. local and off do not wait for any standby.
Seeing the data-loss difference
The simulation below writes ten records. In the async run, the replica has received only the first seven when the primary crashes. It lists the acknowledged records that the replica does not have.
class Node:
def __init__(self):
self.log = []
def run(mode, writes=10, shipped_before_crash=7):
primary, replica = Node(), Node()
acknowledged = []
for i in range(writes):
record = f"w{i}"
primary.log.append(record)
if mode == "sync":
# Primary waits for the replica before acknowledging.
replica.log.append(record)
elif i < shipped_before_crash:
# Async: shipping happens in the background and has kept up so far.
replica.log.append(record)
acknowledged.append(record)
# Primary crashes. The replica is promoted.
return [r for r in acknowledged if r not in replica.log]
print("sync lost:", run("sync")) # sync lost: []
print("async lost:", run("async")) # async lost: ['w7', 'w8', 'w9']The clients received acknowledgments for w7 to w9, yet the promoted replica does not have them. This acknowledged-but-lost data is what recovery point objective (RPO) measures. Synchronous replication gives an RPO of zero. Asynchronous replication gives an RPO equal to the lag at the time of failure.
How replication mode affects RPO and RTO
Replication choice sets the recovery point. It also influences recovery time.
| Property | Synchronous | Asynchronous |
|---|---|---|
| Data lost on primary failure | None for acknowledged writes | Up to the current lag |
| Write latency | Adds a replica round trip | Unchanged |
| Effect of replica outage | Writes may stall | None on writes |
| Suitable distance | Same zone or nearby zones | Cross-region |
| Promotion decision | Safe, replica is current | Must check how far behind it is |
For recovery time, a synchronous replica is current, so promotion can be fast and automatic. With an asynchronous replica, the failover process must decide whether to promote it and accept the loss, or to wait and try to recover the primary's log. That decision can be automated, but the rule must be written down in advance. For example: "promote automatically if lag is under 5 seconds, otherwise page a human."
Common errors
- Treating async as nearly synchronous. The loss is small only while lag is small. Alert on lag and on its maximum, not only its average.
- Reading from replicas without accounting for lag. A user writes a record and the next read goes to a replica that has not received it. The record seems to vanish. Route reads that must see a user's own writes to the primary, or to a replica known to be caught up.
- Replicating inside one fault domain. A replica on the same host or disk shares failures with the primary. Place replicas in a different zone or region, as the fault domains chapter explained.
- Assuming replication is a backup. Replication copies mistakes too. A bad
DELETEor corrupted row reaches every replica within moments. Keep separate point-in-time backups. - Never testing a stalled replica. Teams configure sync replication, then find that a replica restart blocks all writes. Test this case on purpose.
- Promoting a replica that has not applied its received log. A replica may have received changes but not yet applied them. Check that it has finished applying before accepting traffic.
Choosing a mode
Start from the data, not the technology.
- Decide how much acknowledged data the business can lose. That is your RPO.
- If the answer is "none," use synchronous or quorum replication to a nearby location, and accept the latency cost.
- If a few seconds of loss is acceptable, or the distance is large, use asynchronous replication and monitor lag.
- Many systems combine both. They replicate synchronously to a nearby zone for zero loss on common failures, and asynchronously to a distant region for protection against regional disasters.
Exercise
A service replicates asynchronously to a standby in another region. Replication lag is normally 200 ms, but reached 20 seconds during last week's batch job. The primary's data center fails during a batch job. What is the worst-case data loss, and what is one change that would cut it to zero?
Show answer
Worst-case loss is about 20 seconds of acknowledged writes, because those are the changes not yet shipped to the standby. Switching to synchronous or quorum replication to at least one additional replica, for example one in a nearby zone, makes every acknowledged write exist on two nodes, so failover of the primary loses nothing. The cost is added write latency, and writes may stall if that replica is unavailable.
Exercise
A primary has two synchronous replicas configured so that all of them must confirm every write. One replica's host is rebooted for patching. What happens to writes, and how would you change the configuration?
Show answer
Writes stall until the rebooted replica returns, because the primary cannot get all confirmations. A change is to require any one of the two replicas, as in the ANY 1 (replica_a, replica_b) setting. Writes continue with one confirmed copy while the other replica is down, and each acknowledged write still exists on two nodes.