Replication

Copy a database to four followers and reads get cheap, but every copy runs late. With half a second of average lag, a reload 0.3 s after you post misses your own comment more than half the time. How you route reads decides what users see.

Pick a read rule, move the lag, and step through users. Then we build each part from zero: leaders and followers, failover, the replication log, the three lag anomalies, several leaders, no leader, and version vectors.

You need a little Python and what a database write is. We build the rest from zero.

Post, then reload twice

0.50 s

Illustrative and seeded: 4 asynchronous followers, each with an exponential lag of the average you set. Reloads at 0.3 s and 0.7 s; 10,000 users. Chapters 4 and 5 derive the same rates by hand.

Chapter 0

Copies of Changing Data

Rename a user in Virginia and watch two other copies hold the old name for a while

A profile service keeps its database on one server in Virginia. If that server dies, every request fails until it is back. A reader in Tokyo waits about 150 ms for each round trip. And one machine answers only so many reads.

Replication means keeping a copy of the same data on several machines connected by a network. Each copy is a replica. Copies help in three ways: the service keeps running when one machine dies, reads go to a nearby copy, and more machines answer more reads.

Copying data that never changes is easy: copy it once. All the difficulty is in changes. A user renames herself in Virginia, and for a moment Frankfurt and Tokyo still hold the old name.

Rename, then read each copy

The rename lands in Virginia at time 0 and travels to the other two copies. Drag the time slider and read each copy.

0.30 s

Illustrative lags: Frankfurt applies the change after 0.15 s, Tokyo after 0.9 s, because Tokyo's copy is busy.

How many reads do copies buy? With made-up numbers: one server answers 50,000 reads a second, but writes use half of it, so 25,000 are left. Each follower replays every write too, which costs it 30%, so it serves 35,000. Three followers give 25,000 + 3 × 35,000 = 130,000 reads a second, 5.2 times one server. Writes do not scale this way, because every copy applies every write.

This lesson follows Chapter 6 of Designing Data-Intensive Applications, 2nd edition, by Martin Kleppmann and Chris Riccomini (O'Reilly, 2026). We explain its ideas in our own words, with our own examples and simulations. Chapter 5 encoded each change as bytes; this chapter ships those changes to other machines. Where the Distributed Systems series already builds a mechanism, we link to it.

Failure. Symptom: someone runs DELETE FROM users by mistake, and every replica is empty a second later. Measure: row counts on each replica and in the last backup. Cause: replication copies a mistake as faithfully as a good write. Fix: keep point-in-time backups as well as replicas.

  1. Leader: one leader, followers, and how a new follower catches up.
  2. Failover: what goes wrong when the leader dies, and the timeout trade.
  3. Log: statements, write-ahead logs and logical rows.
  4. Your writes: why you miss your own post, and three fixes (the hero's read rules).
  5. Backward: reads that go back in time, and answers before questions.
  6. Multi-leader: several leaders, write conflicts and last write wins.
  7. Leaderless: quorums that miss, sloppy quorums and repair.
  8. Concurrency: version vectors tell "after" from "at the same time".
  9. The showcase: one workload under all three designs.
  10. The field guide: numbers, checklist, code and links.
You add three read replicas to a database. Why does write throughput not go up?

Chapter 1

One Leader and Its Followers

Stream one log to every copy, then bring a new follower up without stopping writes

The most common design gives one replica a special job. The leader (also called the primary) takes every write. It records each change in a replication log and streams the log to the other replicas, the followers (secondaries, read replicas). Each follower applies the changes in the same order. Clients read from any replica, but write only to the leader.

When does the leader tell the client "saved"? Synchronous replication waits until a follower confirms it has the change. Asynchronous replication answers as soon as the leader has it. Waiting for every follower is rare, because one slow follower stalls every write. A common middle is one synchronous follower and the rest asynchronous.

Wait for a Follower, or Not measures what each choice costs in latency and in writes lost at failover. PostgreSQL's streaming replication is asynchronous by default.

How do you add a follower while writes keep coming? Copying the files while they change gives a broken copy. Instead:

  1. Take a consistent snapshot of the leader, and note its exact position in the log.
  2. Copy the snapshot to the new follower.
  3. The follower asks for every change since that position, and applies them.
  4. Once it has caught up, it follows the live stream.

Bring up a new follower

The purple area is the backlog: log entries the new follower has not applied. It grows while the snapshot copies, then drains. Move the write rate and the copy time.

500
2.0 h

Illustrative: the follower applies 2,000 log entries a second. Computed from the formula below, which a script checked.

How long is step 3? While the snapshot copies, writes pile up. Call the leader's write rate λ (lambda) and the copy time Tc, so the backlog is B = λ · Tc entries. The follower applies entries at rate μ (mu), but new writes keep arriving. Call the catch-up time t.

Say it aloud

t equals B over mu minus lambda.

t
t the catch-up time, in seconds, from the end of the copy until the follower is current.
B
B the backlog: log entries written while the snapshot copied.
μ
mu how many entries the follower applies each second.
λ
lambda how many new writes the leader takes each second.
In plain words

The follower gains on the leader by mu minus lambda entries each second. Divide the backlog B by that gain to get t. If mu is not above lambda, the follower never catches up.

With numbers

With made-up numbers: λ = 500 writes a second and a 2-hour copy, so B = 500 × 7,200 = 3,600,000. With μ = 2,000, t = 3,600,000 / 1,500 = 2,400 s, which is 40 minutes. At λ = 1,900 the same follower needs 38 hours.

Failure. Symptom: a new replica reports a lag that never shrinks. Measure: its apply rate against the leader's write rate. Cause: μ is not above λ, for example a follower on a slower disk. Fix: a faster follower, or catch up during a quiet hour.

A one-hour snapshot copy, 1,000 writes a second, and a follower that applies 3,000 a second. How long does catch-up take?

Chapter 2

When the Leader Dies

Promote a follower, and choose a timeout that neither waits too long nor fires on a pause

A follower that crashes is easy. It knows the last log position it applied. It reconnects, asks for everything after that, and catches up.

A leader that crashes needs failover: one follower becomes the new leader. It takes three steps:

  1. Decide that the leader is dead, usually because no heartbeat came for a timeout of τ (tau) seconds.
  2. Choose the follower that holds the most of the log.
  3. Send clients and the other followers to it. If the old leader returns, it must become a follower.

Each step can go wrong. With asynchronous replication, the new leader lacks the old leader's last writes, and the system usually throws them away, though clients were told "saved". If two nodes both believe they lead, a split brain, both take writes and the histories split. So systems fence the old leader, cutting it off or powering it down, before the new one takes writes.

Thrown-away writes can also break other systems. In September 2012, GitHub's cluster promoted a MySQL replica that was out of date. Records created in that window no longer matched data kept in Redis. Some events showed on the wrong users' dashboards, and 16 private repositories were visible to outsiders for seven minutes.

The hardest knob is the timeout. Too long, and a real crash means τ seconds with no writes. Too short, and a leader that only paused looks dead.

Choose the failover timeout

Each dot is one pause of a healthy leader, by its length. A dot above the yellow timeout line triggers a needless failover (red). The bar below is the write outage after a real crash. Drag the timeout.

10 s

Illustrative and seeded: 6 pauses an hour for 30 days, exponential lengths averaging 2 s. Election and reconfiguration take 5 s after a real crash.

How many false failovers does a timeout cause? Pauses, such as garbage collection or a stalled disk, come at r per hour. Their length averages m seconds, and long pauses get rare fast. Call the false failovers per day F.

Say it aloud

F equals twenty-four times r times e to the minus tau over m.

F
F needless failovers per day: a healthy leader paused longer than the timeout.
24
twenty-four hours in a day.
r
r pauses per hour: 6 here.
e−τ/m
e to the minus tau over m the chance that one pause outlasts the timeout τ. Pause lengths are exponential with average m, 2 s here.
In plain words

Count the pauses in a day: 24 times r. Multiply by the chance that one pause lasts longer than tau. That chance is e to the minus tau over m.

With numbers

With made-up numbers: r = 6 and m = 2 s. With τ = 10 s, F = 144 × e−5 = 0.97, about one needless failover a day. With τ = 30 s, F = 0.000044, one in 62 years, but each real crash now costs 35 s with no writes.

Failure. Symptom: the cluster fails over every night during the backup job. Measure: the leader's pause lengths against the timeout. Cause: τ is below the long pauses. Fix: raise τ or cure the pauses, and check the candidate's lag before you promote it.

Why must the old leader be fenced before the new leader takes writes?

Chapter 3

What the Leader Sends

Replay one update four ways, and see which follower ends up different

The leader must describe each change so that a follower can repeat it. Take one statement: UPDATE users SET token = UUID(), seen = NOW() WHERE id = 42. There are four ways to send it.

Replay one update

Left: what goes over the wire. Right: the leader's row and the follower's row after replay. Pick a format, then try a follower on a newer major version.

Illustrative values; the rules come from the MySQL 8.4 manual (statement and row formats) and the PostgreSQL manual (log shipping and logical replication).

Rows cost bytes. UPDATE accounts SET fee = 0 WHERE plan = 'free' is 47 bytes as a statement. Say it changes 10,000 rows of about 100 bytes each. A row log that carries each row before and after holds about 10,000 × 200 = 2,000,000 bytes, 2 MB. The row log pays that to replay the same result everywhere.

Today the MySQL 8.4 manual calls binlog_format deprecated and tells new setups to use row-based logging only.

Failure. Symptom: a token that works against the leader fails against a follower. Measure: checksum the same rows on both. Cause: statement-based replication of a UUID() call. Fix: row-based logging.

You want every PostgreSQL change to reach a search index. Which log can the index read?

Chapter 4

Read Your Own Writes

Work out how often a fast reload misses your post, and size the fix

Followers serve reads, and asynchronous followers run behind. If writes stop, they catch up and agree. This weak promise is eventual consistency. "Eventually" has no bound: under load, lag can reach minutes.

Lag causes three anomalies, and each has a guarantee that rules it out. The first: you post a comment, reload, and the comment is not there. Read-after-write consistency (read-your-writes) promises that a user always sees the writes they made. It promises nothing about other users' writes.

How likely is the miss? Call the time from your write to your reload t, and the follower's average lag L. As an illustration, let lag be exponential: short most times, long sometimes. Call the chance that the follower is still behind P.

Say it aloud

P equals e to the minus t over L.

P
P the chance that the follower has not applied your write yet.
e−t/L
e to the minus t over L the chance that an exponential lag with average L is longer than t. t is the time from write to read, in seconds.
In plain words

Divide the reload time t by the average lag L. Raise e to minus that number. The longer you wait compared to L, the smaller P gets.

With numbers

With made-up numbers: t = 0.3 s and L = 0.5 s give P = e−0.6 = 0.55. Over half of fast reloads miss. The hero's 10,000 seeded users missed 54.6% of the time.

Three fixes, each one of the hero's read rules:

Size the leader window

The curve is the chance a follower is still behind, t seconds after a write. Reads inside the window go to the leader (teal). The red point is the first read after the window. Drag the lag and the window.

0.5 s
1.0 s

Illustrative exponential lag. The stale share is also counted over 10,000 seeded reads, and it agrees with e−w/L.

Failure. Symptom: during the nightly batch import, users say their saves do not stick. Measure: follower lag during the import against the leader window. Cause: a fixed window shorter than the lag; at L = 5 s a 1-second window leaks 82% of reads. Fix: track log positions instead of time.

Average lag is 0.5 s. Reads go to the leader for 1 s after a write. How often is the first read after the window stale?

Chapter 5

Reads That Go Backward

Reload twice and lose a comment, then see an answer arrive before its question

You reload and see 10 comments. You reload again and see 9. The first read hit a follower that had the new comment, and the second hit one that did not. Time seemed to run backward.

Monotonic reads forbids this: after a user sees some state, later reads never show an older one. It is weaker than always reading the newest data. The usual fix routes each user to the same replica, chosen by a hash of the user ID. If that replica fails, the user moves to another.

How often does a comment vanish? Call the number of followers n, the two reload times t1 and t2, and the average lag L. Call the chance of a backward read P.

Say it aloud

P equals one minus one over n, times one minus e to the minus t-one over L, times e to the minus t-two over L.

P
P the chance that the second reload shows less than the first.
1 − 1/n
one minus one over n the chance that the second reload goes to a different follower; n = 4 followers here.
1 − e−t1/L
one minus e to the minus t-one over L the chance that the first follower had the comment at the first reload, t-one = 0.3 s.
e−t2/L
e to the minus t-two over L the chance that the second follower is still behind at the second reload, t-two = 0.7 s. L is the average lag.
In plain words

Three things must all happen. The second reload goes to a different follower. The first follower was already fresh at t-one. The second follower is still behind at t-two. Multiply the three chances.

With numbers

With made-up numbers: n = 4, L = 0.5 s. P = 0.75 × 0.45 × 0.25 = 0.083, so one user in 12 sees a comment vanish. A sticky follower makes the first factor 0.

The third anomaly needs two pieces of data that replicate apart, such as two shards. Alice asks "Ready to ship?" on shard A. Bob answers "Yes, shipped" 0.3 s later, on shard B. An observer's copy of shard A runs 0.8 s behind, and of shard B 0.1 s. The answer shows at 0.4 s, the question at 0.8 s: for 400 ms the observer sees an answer to nothing.

Watch reads go backward

The top shows one user (or one observer). The bars count anomalies over many seeded users. Pick a scene, drag the lag, then press Next.

0.5 s

Illustrative and seeded: follower scenes use 4 followers and reloads at 0.3 s and 0.7 s (10,000 users). Two shards: the slider sets shard A's average lag, shard B averages 0.1 s, the answer comes 0.3 s after the question (10,000 observers).

Consistent prefix reads promises that if writes happen in some order, every reader sees them in that order. One fix writes causally related data to the same shard. The other tracks which write depends on which, as Keeping Cause Before Effect does with vector clocks.

Failure. Symptom: users see an order marked "shipped" and then "processing" again. Measure: per-user reads that return an older version than a previous read. Cause: a load balancer that spreads one user's reads over followers with different lag. Fix: sticky routing by user ID.

Which guarantee stops an answer from showing before its question?

Chapter 6

Several Leaders, Conflicting Writes

Let each region accept writes, then see which write last write wins throws away

With one leader, a user in Tokyo sends every write to Virginia, and writes stop during a failover. Multi-leader replication lets several nodes accept writes. Each region gets a leader, and each leader sends its writes to the others asynchronously. Users write nearby, and each region keeps working if the links between regions fail.

The same shape appears outside data centres. An app that works offline is a leader on each device: it accepts writes and syncs later. A shared document editor has one leader per user, merging keystrokes.

The price is the write conflict: two leaders change the same key before either sees the other's change. One leader never has this, because it orders all writes. One Leader, Many, or None works out how often conflicts happen. Here is how systems resolve them:

LWW drops one of two conflicting writes by design. Clocks also drift, so it can drop the later one. Say two leaders change one key g apart in real time, with g anywhere from 0 to D. Leader B's clock runs s ahead. If B wrote first and g is below s, B's timestamp still looks later. Call the chance that the earlier write wins P.

Say it aloud

P equals s over two D.

P
P the chance that last write wins keeps the earlier of two conflicting writes.
s
s the clock skew: how far B's clock runs ahead, in ms.
2
two B writes first in half of the pairs.
D
D the widest gap between two writes that still conflict: the replication delay, 150 ms here.
In plain words

B writes first in half of the pairs. In those, the wrong write wins when the gap g is below the skew s, which happens s out of D of the time. Multiply: s over 2D, while s is at most D.

With numbers

With made-up numbers: s = 50 ms and D = 150 ms give P = 50 / 300 = 0.17. One conflict in six keeps the older value. Our 10,000 seeded pairs gave 15.9%.

Resolve a conflict

Two leaders change one address. The top lane is real time, the bottom lane is each write's timestamp. Drag B's clock skew and press Next pair.

50 ms

Illustrative and seeded: 10,000 conflicting pairs, gaps uniform from 0 to 150 ms, either leader first with equal chance; A's clock is exact.

Leaders also forward each other's writes, in a ring, a star or all to all. All to all survives a failed node, but an update can overtake the insert it depends on at a third leader. The fix is the causal ordering of the last chapter.

Failure. Symptom: a customer's new address turns back into an old one after support fixed a typo. Measure: overwritten writes per key with timestamps within the replication delay. Cause: last write wins between two leaders. Fix: one home leader per customer, or keep both versions.

B's clock runs 30 ms fast; conflicting writes fall up to 150 ms apart. How often does LWW keep the earlier write?

Chapter 7

No Leader at All

Count how often a quorum read misses, then let repair find the stale copies

Dynamo-style systems, such as Cassandra and Riak, have no leader. Any replica takes writes. The client, or a coordinator node, sends each write to all N replicas of a key and waits for W replies. A read asks R replicas and keeps the newest version. Quorums Without a Leader shows why R + W > N makes every read meet the latest write. Here: what happens when it does not.

When R + W is at most N, a read can miss. Call the replicas per key N, the write quorum W and the read quorum R. Call the chance that a random read set avoids every replica that took the write P.

Say it aloud

P equals N minus W choose R, over N choose R.

P
P the chance that a read misses the latest write.
C(N − W, R)
N minus W choose R the number of read sets that use only the N − W replicas without the write. "a choose b" is the number of ways to pick b of a.
C(N, R)
N choose R the number of all read sets of R replicas out of N.
In plain words

Count the read sets that use only replicas without the write. Divide by all read sets. If R is bigger than N minus W, there are none, and P is 0.

With numbers

N = 5, W = 2, R = 2: C(3, 2) / C(5, 2) = 3 / 10, a 30% miss. N = 3, W = 2, R = 2: C(1, 2) = 0, so no read misses.

Tune N, W and R

Purple replicas hold the new write; teal rings mark the replicas one read asked. Change the quorums, turn on a sloppy quorum, and press Read again.

2
2

Illustrative and seeded: 10,000 random write and read sets per setting. Sloppy: only one home replica took the write; stand-in nodes outside the home set took the rest.

If home replicas are down, a sloppy quorum writes to other nodes that are not home for the key. They keep the write with a hint and pass it on when the home replica returns. This is hinted handoff. Writes stay available, but R + W > N no longer promises overlap. With one home copy, a read of R home replicas misses with chance (N − R)/N: one in three for N = 3 and R = 2.

Replicas that missed a write need repair. Read repair: when a read sees a stale replica, it writes the newer value back. Anti-entropy: a background process compares replicas and copies what differs; Cassandra compares Merkle trees, built in Finding What Differs. Read repair fixes only keys that someone reads. Call the reads per key per day r, the days since the write T, and the share of stale keys still stale S.

Say it aloud

S equals e to the minus r T.

S
S the share of stale keys that no read has repaired yet.
e−r·T
e to the minus r T the chance that a key read at random r times a day gets no read in T days.
In plain words

Multiply the read rate r by the days T. Raise e to minus that. That share of stale keys has had no read, so read repair has not touched them.

With numbers

With made-up numbers: a cold key read 0.1 times a day. After 7 days, S = e−0.7 = 0.50; after 30 days, S = 0.05. One stale key in 20 is still stale a month later, unless anti-entropy runs.

Failure. Symptom: after a node was down for a day, old values show on rarely viewed pages for weeks. Measure: stale reads by key popularity. Cause: only read repair runs, and cold keys are seldom read. Fix: run anti-entropy repair on a schedule.

N = 5 and W = 2. What is the smallest R that makes every read meet the write?

Chapter 8

Which Write Came First?

Compare version vectors, keep concurrent writes as siblings, and merge them

Two clients write the same key through different replicas, and neither saw the other's write. Such writes are concurrent. One write happens before another if the second knew about the first: it read it, or built on it. Concurrent means neither happened before the other, whatever the wall clocks say.

Replicas must tell the two cases apart. If B happened after A, B replaces A. If they are concurrent, the system keeps both as siblings until someone merges them. A version vector records, for each replica, how many of that replica's writes a version includes. A client reads a key with its vector, and sends that vector back with its next write. Keeping Cause Before Effect uses the same kind of counts to order messages.

When does one version replace another? Call two versions' vectors A and B, and the entry for replica i A[i].

Say it aloud

A dominates B if and only if A of i is at least B of i, for every replica i.

A, B
A, B the version vectors of two versions of one key.
≥
dominates A includes every write that B includes, so A replaces B.
⇔
if and only if the two sides are true together or false together.
A[i]
A of i how many writes from replica i version A includes.
B[i]
B of i the same count in version B. A missing entry counts as 0.
for every i
for every i check each replica, not only one.
In plain words

Compare A and B entry by entry. If every entry of A is at least B's, A replaces B. If every entry of B is at least A's, B replaces A. If each is bigger somewhere, they are concurrent: keep both.

With numbers

A = {A: 3, B: 2} and B = {A: 2, B: 4}. A is bigger at replica A, B is bigger at replica B. Neither dominates, so they are siblings. A merge written as {A: 4, B: 4} dominates both.

Fill one cart from two places

Two replicas hold one cart. Each version shows its items (purple) and its vector. Step through the writes; then switch to last write wins and replay.

Illustrative five-step trace, checked with a short Python version vector class. Last write wins uses timestamps in which the eggs write is 20 ms later.

Merging siblings is the application's job. For a cart, take the union. But a removed item comes back if one sibling still holds it. So the merge needs a marker for each removal, a tombstone. The OR-Set in Registers and Sets does this with a unique tag on each add.

Failure. Symptom: items a user removed come back into the cart. Measure: merges in which a removed item survives. Cause: a union merge with no tombstones. Fix: tombstones, or an OR-Set.

One version has {A: 2, B: 1} and another has {A: 1, B: 1}. What does the replica do?

Chapter 9

Three Ways to Replicate

Run one global workload under one leader, several leaders and no leader, then cut Asia off

Now compare the three designs on the same work. Users in the US, Europe and Asia send 3,000 operations over 60 s: 30% are writes, spread over 20 keys. After each save, the writer reloads 200 ms later. Every design keeps one replica in each region.

Replicate across three regions

Top: three regions and their links; blue dots are writes travelling. Bottom: four measures over the whole run. Pick a design, cut Asia off, and play.

Illustrative and seeded. One-way delays: US to Europe 40 ms, US to Asia 75 ms, Europe to Asia 110 ms. Asynchronous apply adds 250 ms on average; leaderless replicas write on receipt. A conflict is a write that the next write to its key did not see.

One leader in the US: a write costs a round trip to the US, 74 ms on average. Nothing conflicts. But 30% of reloads miss their own write, because European and Asian users read a local follower. Cut Asia off and the leader refuses Asia's writes: 32% of all writes.

Multi-leader: writes take 1 ms and own reloads always hit the local leader. But last write wins drops 11.8% of writes unseen. With Asia cut off for the minute, every region keeps writing, and last write wins drops 44.6% when the link heals.

Leaderless with W = R = 2: a write waits for the second-nearest replica, 102 ms on average. Quorum reads see their own writes. Only 2.0% of writes conflict, and they become siblings, not losses. Cut Asia off and its writes fail, because Asia reaches only one replica.

No design wins every column. Choose per kind of data: one leader for orders and balances, a home region for profiles, siblings or merging types for carts and counters.

Failure. Symptom: a multi-region rollout passes every latency test, then a regional outage loses a week of edits to last write wins. Measure: writes overwritten by a write that did not see them, per key and region. Cause: testing only the healthy network. Fix: test with a region cut off, and measure lost writes, not only latency.

Chapter 10

The Field Guide

Keep the numbers, the rules and the code for the next database you replicate

One leader orders every write and streams a log, but followers lag, failover can drop acknowledged writes, and a statement log can make copies disagree. Lag gives three anomalies, each with its own guarantee: read-your-writes, monotonic reads and consistent prefix reads. Several leaders accept writes nearby and must resolve conflicts. No leader trades a quorum's latency for availability, and needs repair and version vectors to keep concurrent writes.

Terms and numbers

IdeaRuleThis lesson's number
Catch-up timet = B / (μ − λ)3.6 million entries at a gain of 1,500 a second: 40 min
False failoversF = 24 · r · e−τ/mτ = 10 s: 0.97 a day; τ = 30 s: one in 62 years
Missed own writeP = e−t/Lt 0.3 s, L 0.5 s: 55%
Read goes backwardP = (1 − 1/n)(1 − e−t1/L) e−t2/L4 followers: 8.3%; sticky: 0
LWW keeps the earlier writeP = s / (2D)50 ms skew, 150 ms window: 17%
Quorum missP = C(N − W, R) / C(N, R)N 5, W 2, R 2: 30%
Unrepaired stale keysS = e−r·T0.1 reads a day, 30 days: 5%
Version orderA ≥ B ⇔ A[i] ≥ B[i] for every i{A: 3, B: 2} vs {A: 2, B: 4}: siblings

Checklist

  1. Keep backups as well as replicas; replication copies mistakes.
  2. Make sure a new follower can apply faster than the leader writes before you start the copy.
  3. Set the failover timeout from measured pause lengths, fence the old leader, and check the candidate's lag.
  4. Use row-based or logical logs; never replicate nondeterministic statements.
  5. Give each user read-your-writes with log positions, and monotonic reads with sticky routing.
  6. Keep causally related writes on one shard, or track their order.
  7. With several leaders, give each record a home or keep siblings; use last write wins only where losing a write is fine.
  8. With no leader, pick R + W > N, run anti-entropy, and merge siblings with tombstones.

The core as code

pythonfrom math import comb, exp

def compare(a, b):
    """Order two version vectors: 'after', 'before', 'equal' or 'concurrent'."""
    keys = set(a) | set(b)
    ge = all(a.get(k, 0) >= b.get(k, 0) for k in keys)
    le = all(a.get(k, 0) <= b.get(k, 0) for k in keys)
    return 'equal' if ge and le else 'after' if ge else 'before' if le else 'concurrent'

def merge(a, b):
    return {k: max(a.get(k, 0), b.get(k, 0)) for k in set(a) | set(b)}

def quorum_miss(n, w, r):
    return comb(n - w, r) / comb(n, r)    # comb(k, r) is 0 when r > k

def stale_own_read(t, mean_lag):
    return exp(-t / mean_lag)              # exponential lag, illustrative

print(compare({'A': 3, 'B': 2}, {'A': 2, 'B': 4}))   # concurrent
print(merge({'A': 1}, {'B': 1}))                       # {'A': 1, 'B': 1}
print(quorum_miss(5, 2, 2), quorum_miss(3, 2, 2))         # 0.3 0.0
print(round(stale_own_read(0.3, 0.5), 3))                # 0.549

Keep going

The takeaway. Every replica runs late. Decide what each reader may see while it does, and choose one leader, several or none from what your data can afford to lose.

Now press Present or Teach and explain four things from memory. Why can an asynchronous failover lose acknowledged writes? Which guarantee stops each of the three lag anomalies? Why does last write wins lose data even with perfect clocks? How does a version vector tell "after" from "concurrent"? Then go back to the hero and find the read rule that fixes both of its numbers.

Database Replication · following Designing Data-Intensive Applications, 2nd edition, Chapter 6
Previous: Encoding and Evolution · Next: Sharding · Back to Gleams