Lesson 01 of 6 · Copies and partitions
Replication and consistency
Every copy of your data is a promise about what a reader will see and what a crash will lose. Compare replication topologies, synchronous, asynchronous and quorum commit, the consistency models in precise terms, what W + R > N does and doesn't give you, PACELC, and failover with fencing. The lab builds a PostgreSQL primary and replica, produces a stale read and fixes it, shows a synchronous commit blocking, and loses 51 rows in a failover.
Forces
You replicate for four different reasons, and each pulls the design a different way:
- Durability wants an acknowledged write on more than one machine before you answer the client.
- Availability wants a copy that can take over when the leader dies.
- Read scale wants many replicas, which may lag.
- Latency wants a copy near the user, which means across a WAN where every synchronous hop costs tens of milliseconds.
You cannot maximise all four. Say which one is primary before choosing a topology, and choose the guarantee per entity, not per database: the same product usually has data that must never be stale next to data that can be minutes old.
First principles
Topologies
| Topology | Write path | Conflicts | Strongest model it can offer | Typical systems |
|---|---|---|---|---|
| Single leader | All writes to one node, streamed to followers | None (one ordering) | Linearizable, if reads go to the leader or wait for a log position | PostgreSQL, MySQL, etcd (via Raft) |
| Multi-leader | Any leader accepts writes; leaders exchange changes | Yes: needs a resolution rule (last-write-wins, CRDTs, application merge) | Causal at best across leaders | Multi-region active-active SQL extensions, CouchDB |
| Leaderless | Client or coordinator writes to W of N replicas | Yes: concurrent writes, read repair, anti-entropy | Eventual by default; tunable per request | Cassandra, Riak, Dynamo-style stores |
Synchronous, asynchronous and quorum commit
Asynchronous replication acknowledges after the leader's local commit. Write latency is local, but the recovery point objective (RPO) equals the replication lag at the moment of failure: RPO > 0 by design.
Synchronous replication waits for a follower to confirm. RPO for that follower becomes 0, write latency becomes the round trip to the slowest synchronous follower, and that follower's outage blocks writes.
Quorum commit waits for any k of n followers, for example PostgreSQL's synchronous_standby_names = 'ANY 1 (a, b)'. It keeps RPO 0 against a single failure without making one follower a single point of failure.
Rule of thumb you can defend: synchronous (or quorum) inside a region, where round trips are sub-millisecond to a few milliseconds; asynchronous across regions, unless the business accepts the WAN round trip on every commit. At 70 ms round trip, a single serial writer is capped at about 14 commits per second.
Consistency models, precisely
"Strong" and "eventual" are not enough vocabulary for a design review. Strongest first:
| Model | Guarantee | Needed for |
|---|---|---|
| Linearizable | Every operation appears to take effect at one instant between its start and end. After a write is acknowledged, every later read anywhere sees it. | Locks, leader election, uniqueness, "check then act", security decisions |
| Sequential | All nodes see operations in the same order, consistent with each client's order, but not necessarily real time | Replicated state machines without real-time requirements |
| Causal | If B was influenced by A, everyone sees A before B; concurrent operations may appear in different orders | Comments and replies, collaborative edits; the strongest model that stays available during a partition |
| Session guarantees | Read-your-writes, monotonic reads, monotonic writes, writes-follow-reads, per client | Most "the user saw their change disappear" bugs |
| Eventual | If writes stop, replicas converge | Analytics, counters, search indexes |
The model a product requirement needs is usually lower than "strong" and higher than "eventual". "A user must see their own profile change immediately" is read-your-writes, not linearizability, and is far cheaper.
Quorums: what W + R > N does and doesn't give you
With N replicas, writes to W and reads from R, the condition W + R > N guarantees that every read set overlaps every write set in at least one replica, which holds the latest acknowledged value. It does not by itself make the system linearizable:
- Sloppy quorums and hinted handoff accept writes on nodes outside the key's home set during failures, so the overlap no longer holds.
- Concurrent writes resolved by last-write-wins depend on clocks; clock skew silently drops acknowledged writes.
- A write in flight can be seen by one reader and not by a later one, unless reads do synchronous read repair.
- A failed write that reached fewer than W replicas is not rolled back on the ones it reached.
PACELC: the trade-off you pay every day
CAP describes behaviour only during a partition. PACELC (Abadi, 2012) adds the normal case: if there is a Partition, choose Availability or Consistency; Else, choose Latency or Consistency. The "else" branch is the one you pay for on every request:
- DynamoDB reads are eventually consistent by default; a strongly consistent read costs twice the read capacity and is served only by the region that owns the item.
- Spanner provides external consistency (linearizable transactions) by waiting out clock uncertainty with TrueTime before acknowledging a commit: it pays latency on the else branch to keep consistency.
Failover: where replication designs actually fail
Promoting a follower is easy. Making sure the old leader can't keep accepting writes is the hard part. A leader paused by a long garbage-collection pause, a VM freeze or a network partition doesn't know it was replaced. Three mechanisms, weakest first:
- Leases. The leader may act only while its lease is valid. This depends on bounded clock drift and on checking the lease before every action.
- Fencing tokens. Each new leader term gets a higher number, and the storage layer rejects writes carrying an older one. This works even when the old leader doesn't know it was demoted.
- STONITH ("shoot the other node in the head"). Power off or isolate the old leader before promoting the new one.
And one decision no mechanism makes for you: whether to promote a follower that is behind. Promotion trades the lagging writes for availability. That is a business decision to make in advance and write in the runbook, not a timeout in a script.
Design space
| Choice | Gain | Cost |
|---|---|---|
| Read from the leader only | Linearizable reads | Leader is the read bottleneck; cross-region reads are slow |
| Read from replicas, no checks | Read scale and locality | Stale reads, read-your-writes violations |
| Read from replicas after waiting for the client's last write position (LSN or token) | Read-your-writes at replica scale | Clients carry a token; reads may wait |
| Sticky reads to the leader for N seconds after a write | Simple read-your-writes | Guessing N; leader load after write bursts |
| Synchronous or quorum commit in-region | RPO 0 for one failure | Write latency; availability tied to followers |
| Asynchronous cross-region | Local write latency | RPO equals lag; promotion loses data |
| Multi-leader across regions | Local writes everywhere | Conflict resolution; no linearizability |
Failure modes
Published incident: GitHub, 21 October 2018
Maintenance work broke connectivity between GitHub's US East Coast network hub and its primary East Coast data centre for 43 seconds. During that window the topology management system promoted MySQL primaries in the West Coast data centre. When connectivity returned, the East Coast had a few seconds of writes that had not reached the West Coast, and the West Coast had already taken new writes. GitHub chose data integrity over fast recovery and ran degraded for about 24 hours while it restored and reconciled. Lessons: automatic cross-region promotion turned a 43-second blip into a day; the decision to promote a lagging replica across regions must account for the data that will be stranded; and latency between regions changes application behaviour once the primary moves.
Other common failures:
- Read-your-writes bugs after introducing read replicas: the user saves a change, the next page load reads a replica and shows the old value.
- Split brain when failover has no fencing: two primaries accept writes.
- Synchronous replication without a plan for follower loss: the primary stops accepting commits when its only synchronous follower disappears.
- Monitoring lag in bytes but not in time, or not alerting on it at all.
Lab: stale reads, blocked commits and lost writes
PostgreSQL 16 in Docker: a primary, a streaming replica cloned with pg_basebackup -R, and a script that walks through four behaviours. To make the stale read deterministic, the replica's WAL replay is paused instead of waiting for network lag. Save as repl-lab.sh and run bash repl-lab.sh (needs Docker; it creates two containers and a network called repl-lab).
#!/usr/bin/env bash
# Replication lab: PostgreSQL 16 primary + streaming replica in Docker.
# Run: bash repl-lab.sh Clean up: docker rm -f pg-primary pg-replica; docker network rm repl-lab
set -euo pipefail
IMG=postgres:16-alpine
P() { docker exec -i pg-primary psql -X -q -U postgres "$@"; }
R() { docker exec -i pg-replica psql -X -q -U postgres "$@"; }
say() { printf '\n### %s\n' "$*"; }
docker rm -f pg-primary pg-replica >/dev/null 2>&1 || true
docker network rm repl-lab >/dev/null 2>&1 || true
docker network create repl-lab >/dev/null
say "1. Start the primary and allow a replication user"
docker run -d --name pg-primary --network repl-lab -e POSTGRES_PASSWORD=labonly $IMG >/dev/null
until docker exec pg-primary pg_isready -U postgres -q; do sleep 1; done; sleep 2
P -c "CREATE ROLE repl WITH REPLICATION LOGIN PASSWORD 'labonly';"
docker exec pg-primary sh -c 'echo "host replication repl all scram-sha-256" >> /var/lib/postgresql/data/pg_hba.conf'
P -c "SELECT pg_reload_conf();" >/dev/null
P -c "CREATE TABLE profile (user_id int PRIMARY KEY, display_name text);
INSERT INTO profile VALUES (42, 'A. Rao');"
say "2. Clone it with pg_basebackup -R and start the replica"
docker run -d --name pg-replica --network repl-lab --user postgres -e PGPASSWORD=labonly $IMG \
sh -c 'pg_basebackup -h pg-primary -U repl -D /tmp/data -R -X stream && chmod 700 /tmp/data && exec postgres -D /tmp/data' >/dev/null
until docker exec pg-replica pg_isready -U postgres -q 2>/dev/null; do sleep 1; done
until [ "$(P -At -c "SELECT count(*) FROM pg_stat_replication WHERE state = 'streaming';")" = 1 ]; do sleep 0.5; done
P -c "SELECT application_name, state, sync_state FROM pg_stat_replication;"
R -c "SELECT pg_is_in_recovery() AS replica, display_name FROM profile WHERE user_id = 42;"
say "3. Freeze replay on the replica, then write on the primary"
R -c "SELECT pg_wal_replay_pause();" >/dev/null
R -c "SELECT pg_get_wal_replay_pause_state();"
P -c "UPDATE profile SET display_name = 'Asha' WHERE user_id = 42;"
LSN=$(P -At -c "SELECT pg_current_wal_lsn();")
echo "primary LSN after the write: $LSN"
say "4. The user reads their own write from the replica"
R -c "SELECT display_name FROM profile WHERE user_id = 42;"
R -c "SELECT pg_last_wal_receive_lsn() AS received, pg_last_wal_replay_lsn() AS replayed,
pg_last_wal_replay_lsn() >= '$LSN'::pg_lsn AS safe_to_read;"
say "5. Resume replay; read again once the replica has reached the write's LSN"
R -c "SELECT pg_wal_replay_resume();" >/dev/null
until [ "$(R -At -c "SELECT pg_last_wal_replay_lsn() >= '$LSN'::pg_lsn;")" = t ]; do sleep 0.2; done
R -c "SELECT pg_last_wal_replay_lsn() >= '$LSN'::pg_lsn AS safe_to_read, display_name FROM profile WHERE user_id = 42;"
say "6. Synchronous commit: the write now waits for the replica"
P -c "ALTER SYSTEM SET synchronous_standby_names = '*';" -c "SELECT pg_reload_conf();" >/dev/null
sleep 1
P -c "SELECT application_name, sync_state FROM pg_stat_replication;"
P -c "\\timing on" -c "INSERT INTO profile VALUES (43, 'sync write, replica up');"
docker network disconnect repl-lab pg-replica
echo "(replica disconnected from the network)"
# statement_timeout does NOT bound this wait: the commit waits after the statement has finished.
P -c "INSERT INTO profile VALUES (44, 'sync write, replica gone');" > insert44.log 2>&1 &
sleep 3
P -At -c "SELECT 'waiting backend: ' || wait_event_type || '/' || wait_event FROM pg_stat_activity WHERE wait_event = 'SyncRep';"
P -At -c "SELECT pg_cancel_backend(pid) FROM pg_stat_activity WHERE wait_event = 'SyncRep';" >/dev/null
wait || true
cat insert44.log; rm -f insert44.log
P -At -c "SELECT 'row 44 on primary: ' || count(*) FROM profile WHERE user_id = 44;"
say "7. Back to async, then lose the primary while the replica is behind"
P -c "ALTER SYSTEM SET synchronous_standby_names = '';" -c "SELECT pg_reload_conf();" >/dev/null
P -c "INSERT INTO profile SELECT g, 'written while replica was cut off' FROM generate_series(100, 149) g;"
P -At -c "SELECT 'rows on primary: ' || count(*) FROM profile;"
docker rm -f pg-primary >/dev/null
echo "(primary destroyed)"
docker network connect repl-lab pg-replica
R -c "SELECT pg_promote();" >/dev/null
sleep 2
R -At -c "SELECT 'promoted, in recovery: ' || pg_is_in_recovery();"
R -At -c "SELECT 'rows on new primary: ' || count(*) FROM profile;"
R -c "SELECT user_id, display_name FROM profile ORDER BY user_id;"
Output from a real run (Docker 29.6, postgres:16-alpine, macOS):
### 1. Start the primary and allow a replication user
### 2. Clone it with pg_basebackup -R and start the replica
application_name | state | sync_state
------------------+-----------+------------
walreceiver | streaming | async
(1 row)
replica | display_name
---------+--------------
t | A. Rao
(1 row)
### 3. Freeze replay on the replica, then write on the primary
pg_get_wal_replay_pause_state
-------------------------------
paused
(1 row)
primary LSN after the write: 0/3000108
### 4. The user reads their own write from the replica
display_name
--------------
A. Rao
(1 row)
received | replayed | safe_to_read
-----------+-----------+--------------
0/3000108 | 0/3000000 | f
(1 row)
### 5. Resume replay; read again once the replica has reached the write's LSN
safe_to_read | display_name
--------------+--------------
t | Asha
(1 row)
### 6. Synchronous commit: the write now waits for the replica
application_name | sync_state
------------------+------------
walreceiver | sync
(1 row)
Time: 3.173 ms
(replica disconnected from the network)
waiting backend: IPC/SyncRep
WARNING: canceling wait for synchronous replication due to user request
DETAIL: The transaction has already committed locally, but might not have been replicated to the standby.
row 44 on primary: 1
### 7. Back to async, then lose the primary while the replica is behind
rows on primary: 53
(primary destroyed)
promoted, in recovery: false
rows on new primary: 2
user_id | display_name
---------+------------------------
42 | Asha
43 | sync write, replica up
(2 rows)
What each step shows:
- Steps 3-4, the stale read. The replica has received the WAL up to
0/3000108but replayed only to0/3000000, so it returns the old name. This is the read-your-writes violation users report as "my change disappeared". - Step 5, the fix. The application records the primary's LSN after the write (or returns it to the client as a token) and reads from a replica only when
pg_last_wal_replay_lsn()has reached it. Read-your-writes at replica scale, without sending every read to the primary. - Step 6, synchronous commit. With the replica connected, the insert commits in about 3 ms. With it disconnected, the commit waits in
IPC/SyncRepindefinitely. Note what the warning says when the wait is cancelled: the transaction has already committed locally. Row 44 exists on the primary. Cancelling the wait does not undo the write; the client got an error for a write that happened. Also notestatement_timeoutdoes not bound this wait, because the wait happens at commit, after the statement has finished. A design that relies on a timeout here needs a different mechanism (quorum commit with more than one candidate, or a monitored fallback to asynchronous). - Step 7, failover with lag. The replica was cut off while 51 more rows were written (row 44 plus 50 bulk rows). The primary was destroyed and the replica promoted. The new primary has 2 rows of the 53: 51 acknowledged writes are gone. That is RPO > 0 made visible, and it is exactly the decision the GitHub incident turned on.
Exercises:
- Change step 6 to quorum commit with two replicas (
ANY 1 (r1, r2)), cut one off, and show that commits continue. - Measure lag in time: add load with
pgbenchon the primary and readwrite_lag,flush_lagandreplay_lagfrompg_stat_replication. - Write the runbook rule for step 7: under what measured lag would you promote automatically, when would you wait for a human, and who decides?
Architect's lens: choose per entity
Apply the ten questions to an identity and entitlements product. Each entity needs a different promise:
| Entity | Guarantee | Design |
|---|---|---|
| Entitlement revocation | Security-critical: a revoked grant must not authorise after the revoke is acknowledged | Linearizable reads on the decision path, or a bounded staleness you can defend (short-lived decisions plus a pushed revocation list) |
| User profile edits | Read-your-writes | LSN token from the write; replica reads wait for it |
| Audit log | Durability first; order per tenant | Quorum commit in-region, append-only, causal order per tenant |
| Usage analytics | Eventual | Asynchronous replica or a stream into a warehouse, off the request path |
Design review
Brief. A global entitlement service: 40,000 tenants, 3 regions, 12,000 writes per second at peak, 300,000 authorisation checks per second. A revocation must take effect everywhere within 2 seconds. 15% of tenants require their data to stay in their region.
Produce: the topology per entity; the consistency model for each read path with the reasoning; RPO and RTO per region; the failover design and how it is fenced; the decision rule for promoting a lagging replica; and a one-page ADR.
| Level | What the answer shows |
|---|---|
| Senior | A working topology with synchronous versus asynchronous justified |
| Staff | Consistency chosen per entity; the revocation path separated from profile reads; read-your-writes with tokens; fencing designed |
| Principal | Residency changes placement (home region per tenant, no cross-region copy for those tenants); the promotion rule decided with the business; cost and operating model stated; what would be measured in the first month |
Self-check
N = 3, W = 2, R = 2. Can a read return a value older than an acknowledged write?
Yes: if a sloppy quorum accepted the write outside the home replicas, or if last-write-wins discarded it because of clock skew. The overlap guarantee only holds with strict quorums and a correct conflict rule.
In the lab, cancelling the synchronous wait returned an error, yet row 44 existed. Why, and what does the client need?
The commit had already happened locally; only the wait for the replica was cancelled. The client cannot tell whether the write happened, so writes must be idempotent (a request ID it can retry safely) and the client must be able to check the outcome.
Your asynchronous replica is 2 s behind and the primary's disk dies. What did you lose, and who decides whether to promote?
Up to 2 s of acknowledged writes. Promoting trades them for availability. The business decides in advance, and the runbook says under which measured lag promotion is automatic.
Why is causal consistency attractive for multi-region designs?
It is the strongest model that can remain available during a partition, and it prevents the anomalies users notice, such as a reply appearing before the message it answers.
References
- Kleppmann, Designing Data-Intensive Applications, chapter 5 (Replication) and chapter 9 (Consistency and Consensus)
- DeCandia et al., "Dynamo: Amazon's Highly Available Key-value Store", SOSP 2007
- Corbett et al., "Spanner: Google's Globally-Distributed Database", OSDI 2012
- Abadi, "Consistency Tradeoffs in Modern Distributed Database System Design", IEEE Computer, 2012
- Kleppmann, "How to do distributed locking", 2016 (fencing tokens)
- GitHub Engineering, "October 21 post-incident analysis", 2018
- PostgreSQL 16 documentation: chapter 27, "High Availability, Load Balancing, and Replication"
- Jepsen analyses, jepsen.io, for how real databases behave under partition
Related on this site
- Isolating tenant data in Multi-tenant SaaS
- Primary/secondary & failover in Cluster Design
- Stateful patterns in Kubernetes Storage
This site is a public version of my personal engineering knowledge hub. It intentionally excludes confidential company information and internal operational details.