Coordination: clocks, leaders, locks and consensus
Foundations F09. What to say when your design needs "one leader", "a lock" or "run this once": why wall clocks lie, ordering events with Lamport and hybrid clocks (and Spanner's TrueTime), failure detection and leader election without split brain, leases, fencing tokens, distributed locks for efficiency vs correctness, consensus and Raft, and where consensus belongs in a real design. Each idea is told as a story you'll remember, with a lab that shows how timeouts, pauses and fencing decide whether a failover is fast, slow or harmful.
Start here
Many designs quietly need machines to agree: which event came first, who the one leader is, who holds the lock, what the next entry in the log is. Interviewers reach for this whenever you say "a single leader", "a lock" or "a cron job that must run once", and their follow-up is always the same: what happens when that machine pauses, the clock jumps or the network splits?
This page covers eight ideas: why wall clocks lie, ordering events without trusting clocks (Lamport, hybrid clocks, TrueTime), failure detection and leader election (and split brain), leases, fencing tokens, distributed locks (efficiency vs correctness), consensus and Raft, and consensus in practice (cost, cluster size, and what to put in ZooKeeper or etcd). Replication, quorums and conflict handling were on the previous two pages. Two-phase commit across services comes later, with idempotency and sagas.
Ten days of Ganeshotsav at the society pandal
A housing society runs its Ganesh pandal for ten days. Volunteers work in shifts, the donation box fills up, and decisions get made by a committee that rarely sits in one room. Ten days touch every idea on this page:
- The evening aarti is "at 7". Mrs Kulkarni's wall clock says 7, the treasurer's phone says 6:57, and the DJ's watch is five minutes fast. (clocks lie)
- Two donation slips have no time on them. Which came first? Each slip carries a number one higher than any slip the writer has seen. (logical clocks)
- The shift leader stops answering his phone. Dead battery, or stuck at the Lalbaug traffic? (failure detection)
- The committee picks a new shift leader, and an hour later the old one walks in giving orders too. (leader election, split brain)
- The donation-box key is handed over "for this shift only, till 10 pm". (a lease)
- Every handover gets a numbered slip, and the bank only accepts deposits with the newest number. (a fencing token)
- Two volunteers both book the society hall for the same Saturday. Annoying or a disaster? (locks: efficiency vs correctness)
- Big decisions go in the minutes book, and a line only counts once a majority of the committee has signed it. (consensus)
- The committee decides only who's in charge and where the budget goes; volunteers handle the rest without a vote. (consensus in practice)
The pandal is made up for teaching; it is not any real society's system.
Wall clocks lie: skew, drift and jumps
Every machine's clock is slightly wrong and can jump, so never use wall-clock timestamps from different machines to decide which event came first, and never measure a duration with a clock that can go backwards.
Two watches at the muhurat
The wedding muhurat is 10:42. The groom's uncle goes by his old HMT watch; the bride's side goes by the priest's phone. They're two minutes apart, and both sides are sure they're right.
The photographer later tries to work out whether the garland went on before the bride's brother tied the turban. He has two photos, one timestamped by each side's camera. The garland photo says 10:43, the turban photo 10:44. But the cameras were set by different people; he can't actually tell the order.
Then, halfway through the ceremony, the uncle notices his watch is fast and winds it back three minutes. Anyone timing the pheras on that watch gets a negative number.
Two different clocks on every machine:
- Wall clock (time of day): synced by NTP or PTP, so it can be stepped forwards or backwards, can stall or smear during a leap second, and differs from other machines by some skew. Use it for showing times to people and for rough log ordering.
- Monotonic clock: only ever moves forward, but means nothing across machines. Use it for timeouts, durations and lease countdowns.
Why clocks disagree:
- Quartz oscillators drift with temperature and age; NTP corrects them by speeding up, slowing down or stepping.
- Typical sync quality varies hugely: tens of milliseconds over the public internet, tens of microseconds with good in-datacenter time.
- A VM can be paused, or a process stopped by GC, so a whole second can pass "between two lines of code".
The rule: when the order of two events on different machines matters (which write wins, who held the lock first), don't decide it by comparing their wall-clock timestamps. Use a logical clock, a single leader that assigns the order, or a clock with a known error bound.
On 1 January 2017, a leap second made time appear to go backwards on Cloudflare's DNS servers. Their resolver code measured round-trip times by subtracting timestamps from Go's time.Now(), which, the post notes, wasn't monotonic at the time. A negative duration reached rand.Int63n(), which panics on negative input, and about 0.2% of DNS queries at peak failed between 00:00 and 06:45 UTC (Cloudflare, Jan 2017).
How good can sync get? AWS reports a clock error bound typically under 100 µs over the Amazon Time Sync Service's NTP endpoint, and under 40 µs with the PTP hardware clock, while public NTP servers in its sample output showed errors of tens of milliseconds. Its ClockBound library returns an interval, not a single time (AWS Compute Blog, Nov 2023).
- Wall-clock timestamps are free and readable, but skew and jumps make them unsafe for ordering events or deciding which write wins.
- Better time sync (PTP, hardware clocks) shrinks the error to microseconds, but never to zero, and only helps if the code also knows the error bound.
I won't order writes from different servers by their wall-clock timestamps; skew of even a few milliseconds can make the older write win. The leader for each key assigns a sequence number instead, and timeouts use the monotonic clock.
Using "last-writer-wins by timestamp" across servers or regions without mentioning skew. The interviewer will ask what happens when one server's clock is 200 ms ahead.
Ordering without trusting clocks: Lamport, hybrid clocks and TrueTime
To order events across machines, either count instead of reading the time (Lamport and hybrid logical clocks), or know exactly how wrong your clock can be and wait out the doubt (TrueTime).
Numbered chits between two kitchens
A big wedding has two kitchens: the main one and the sweets tent across the lawn. Runners carry chits between them: "send 200 more jalebis", "jalebis sent, need more sugar".
Nobody trusts the times on the chits, so the head cooks use a rule: every chit you write gets a number one higher than the highest number you've written or received. The sweets tent receives chit 41 and replies with chit 42, even if its own last chit was 17.
Now anyone sorting the pile can be sure of one thing: a reply always has a higher number than the chit it answers. Two chits written independently may get numbers in either order, and that's fine: neither caused the other.
- Happened-before (Lamport, 1978): A happened before B if they're on the same machine in that order, or A is a message send and B its receipt, or there's a chain of these. Otherwise they're concurrent.
- Lamport clock: a counter per machine; tick on each event; on receiving a message, jump to max(mine, theirs) + 1. If A happened before B, A's number is smaller. Not the reverse: a smaller number doesn't mean A caused B. (Detecting concurrency needs version vectors, from the previous page.)
- Hybrid logical clock (HLC): a timestamp that stays close to the physical clock but has a logical counter for ties and for messages from a machine whose clock is ahead. Ordering is causally safe and the numbers still look like time.
- TrueTime (Google Spanner): the clock API returns an interval [earliest, latest] guaranteed to contain the true time. To commit, a transaction picks a timestamp and then waits until that time is certainly in the past ("commit wait"), about twice the uncertainty. After that, any later transaction gets a higher timestamp, so timestamp order matches real-time order.
CockroachDB uses a hybrid logical clock. The default maximum clock offset between nodes is 500 ms; a read's "uncertainty interval" runs from its timestamp to that plus the max offset, and a value written inside that window can force the read to restart at a higher timestamp. A node whose clock is more than 80% of the max offset (400 ms) away from at least half of the others shuts itself down rather than risk inconsistent reads (Cockroach Labs, Apr 2025).
Spanner's 2012 paper: TrueTime's uncertainty ε was "a sawtooth function of time, varying from about 1 to 7 ms", 4 ms most of the time, using GPS and atomic clocks as time references. Commit wait makes each write wait out that uncertainty (OSDI 2012).
- Logical clocks need no special hardware and are always causally safe, but their numbers say nothing about real time, so they can't give real-time ordering between unrelated clients.
- TrueTime-style bounded clocks give real-time order (external consistency), but need excellent time sync and add a commit wait to every write; a bad clock becomes a correctness problem, so nodes must step out when they drift.
Within one partition the leader assigns the order with a sequence number, so clocks don't matter. If I need a global order across partitions, I'd use a database with hybrid logical clocks or TrueTime, and I'd know its max clock offset because that bounds its correctness.
Saying "use a vector clock" or "use a Lamport timestamp" to get a global real-time order. Lamport order is consistent with cause and effect, not with the wall clock: an event that happened later in real time on another machine can still get a smaller number.
Failure detection and leader election: dead, or just slow?
A machine can't tell a dead peer from a slow one, so it guesses with heartbeats and a timeout; electing a new leader is safe only if a majority must agree, so two halves of a split network can't each pick one.
The head cook who didn't answer
Two hours before the reception, the head cook stops answering his phone. Is he in hospital? Out buying vegetables with a dead battery? Asleep in the van? From the kitchen, you can't tell. All you know is that he hasn't replied for 30 minutes.
The catering team has a rule: if the head cook is silent for 30 minutes, the five senior cooks vote, and whoever gets three votes takes charge. They pick Ramesh.
At 6 pm the old head cook walks back in with sacks of onions and starts giving orders. Now there are two people telling the kitchen what to do, and the paneer gets salted twice. That's split brain. The fix isn't a better guess about whether he was dead; it's a rule that the old head steps down the moment he learns there's a newer one.
- Heartbeats and timeouts: the leader sends "I'm alive" every h ms; followers suspect it after T ms of silence. A timeout is a guess: in a real network, a crashed node and a slow one look the same.
- Why majorities: a candidate needs votes from a majority (2 of 3, 3 of 5). Any two majorities overlap, so at most one leader can be elected per round, even if the network splits.
- Terms (epochs): each election starts a new, higher term number. Every message carries it; a leader that sees a higher term steps down immediately.
- Split brain: two nodes both acting as leader. Majority voting prevents two leaders *being elected* in one term; it does not stop an old leader that hasn't heard the news yet from acting. That needs leases and fencing (next two sections).
- Tuning: short timeouts mean fast failover but more false alarms; long ones the reverse. etcd's defaults are a 100 ms heartbeat and a 1,000 ms election timeout.
On 21 October 2018, GitHub lost connectivity between its US East Coast network hub and primary East Coast data center for 43 seconds. In that window, its Orchestrator cluster (which uses Raft) failed the MySQL primaries over to the West Coast. Several seconds of East Coast writes had never replicated west, and the West Coast then took writes for nearly 40 minutes that the East didn't have, so failing back wasn't simple. The service was degraded for 24 hours and 11 minutes (GitHub, Oct 2018).
etcd's tuning guide: heartbeat "around round-trip time between members" (0.5 to 1.5× the RTT), and "election timeouts must be at least 10 times the round-trip time", up to 50 s for globally distributed clusters (etcd docs, checked Oct 2026).
- Short timeouts: failover in about a second, but GC pauses, slow disks and network blips trigger needless elections and write stalls.
- Long timeouts: few false alarms, but every real crash leaves the system leaderless for the whole timeout.
The primary is chosen by majority vote in a three-node consensus group, with terms so an old leader steps down when it sees a newer one. Election timeout around a second within a region. And I'll ask what a failover may cost: GitHub's 43-second blip became a cross-region failover and a day of degradation.
Saying "if the leader dies, a replica takes over" without saying who decides, how a slow leader is told apart from a dead one, and what stops the old leader writing after it wakes up.
Leases: a lock with an expiry time
A lease is a right that expires on its own unless renewed, so if the holder dies nobody has to prove it: the others just wait out the lease, and the holder must stop acting before it ends.
The hotel key card
You check into a hotel in Goa. Your key card opens room 214 until 12 noon on Sunday. If you want another night, you go to reception and extend it.
If you vanish on Saturday night, the hotel doesn't need to find you or know whether you're alive. At 12:01 on Sunday, your card stops working and the room can go to the next guest. Nobody had to agree that you were gone.
But notice what the system relies on: your card and the door agree on what "12 noon" means. And if you're asleep in the room at 12:01 with the door open, nothing stops you walking around as if it were still yours.
- The lock service (or the cluster) grants a lease for T seconds. The holder renews it every h seconds, well before it runs out.
- If the holder crashes, renewals stop and the lease expires on its own. Nobody has to decide the holder is dead; they only have to wait T.
- Safety assumes clocks measure durations roughly right: the holder must stop acting before the lease ends on its own clock, minus a margin for drift. Spanner's paper used a worst-case drift of 200 µs per second; that's 2.4 ms over a 12-second lease, small compared with a GC pause.
- What a lease can't do: stop a holder that is paused at the wrong moment. It checks "I still hold it", freezes for 10 seconds, then writes. From its point of view no time passed.
- Lease length is the trade-off: short leases give fast failover but more renew traffic and more false expiries; long leases the opposite.
- Leases also make reads cheap: a leader holding a lease can answer reads locally, knowing no other leader can exist until it expires.
Google's Chubby lock service (2006): each KeepAlive extends a session's lease, "12s" by default; if it lapses, the client waits a further "grace period, 45s by default" before giving up its locks, so a short master outage doesn't drop every lock. Chubby was intended for "coarse-grained" locks, such as electing a primary that then holds the role "for a considerable time, perhaps hours or days" (OSDI 2006).
Kubernetes control-plane components elect a leader through Lease objects. The docs describe the lease duration as "effectively the maximum duration that a leader can be stopped before it is replaced by another candidate" (Kubernetes docs, checked Oct 2026).
CockroachDB's leaseholder for each range serves strongly consistent reads without a consensus round trip, because its writes have already been agreed (CockroachDB docs, checked Oct 2026).
- Leases remove the need to agree that a node is dead, but make correctness depend on bounded clock drift and on the holder checking its lease before acting.
- Short leases recover quickly; long leases survive pauses and slow renewals. Neither is safe against a pause longer than the lease; that's what fencing is for.
The scheduler's leader holds a 10-second lease in etcd and renews every 2 seconds. If it dies, another instance takes over within about 10 seconds. It stops acting a little before the lease ends on its own monotonic clock, and anything it writes carries a fencing token.
Treating a lease (or a Redis key with a TTL) as a guarantee that only one process can act. A process can stall past its lease and then act anyway.
Fencing tokens: making the old holder harmless
Every time the lock or leadership changes hands, hand out a number that only goes up, send it with every write, and have the storage reject any number lower than the highest it has seen.
The godown keeper's slip numbers
A grain godown accepts deliveries only from the supervisor on duty. Each time a new supervisor takes over, the office gives them a slip with the next number: 33, then 34.
Supervisor 33 drives a truck in, parks outside, and falls asleep in the cab. His shift ends. The office hands slip 34 to the next supervisor, who delivers her load. The keeper notes: "highest slip seen: 34."
At midnight, supervisor 33 wakes up, sure he's still on duty, and backs his truck up to the door. The keeper looks at the slip: 33. "I've already seen 34. Go home." No argument about whose watch was right or whether he was really asleep. The number settles it.
- The lock service or consensus group issues a fencing token with each grant: a number that strictly increases (a Raft term, a ZooKeeper zxid, an etcd revision, a database sequence).
- The holder sends the token with every write to the protected resource (storage, database, downstream service).
- The resource remembers the highest token it has accepted and rejects lower ones.
- This makes safety independent of timing: however long the old holder paused, and whatever its clock says, its writes bounce.
- The catch: the resource must take part. A plain file system or a third-party API that can't check tokens needs another guard, such as a conditional write (compare-and-set on a version column) or an idempotency key.
- A random lock value (Redis-style) is not a fencing token: it lets you release only your own lock, but it isn't ordered, so the storage can't tell old from new.
Martin Kleppmann's 2016 analysis gives the canonical case: client 1 gets a lease with token 33, then pauses (his example is a stop-the-world GC, which really hit an HBase deployment) and the lease expires. Client 2 gets token 34 and writes. When client 1 wakes and writes with 33, the storage, having seen 34, rejects it (Kleppmann, Feb 2016).
Chubby offered the same idea in 2006 as a "sequencer": an opaque string describing the lock's state right after acquisition, which servers check before performing a protected operation (OSDI 2006).
The Redis docs' own disclaimer on distributed locks: "You should implement fencing tokens", especially for long-running processes (Redis docs, checked Oct 2026).
- Fencing makes a paused or partitioned old leader harmless without trusting clocks, but every protected resource must store and check the token.
- Where the resource can't check tokens, fall back to conditional writes or idempotency, or accept that the lock is only for efficiency.
Leadership comes with the term number as a fencing token. Every write to the job table includes it, and the update says WHERE fence_token <= :mine, setting it to mine. A paused old leader's writes simply match zero rows.
Answering "what if the lock holder pauses past its lease?" with "make the lease longer" or "renew more often". No lease length covers every pause; only the resource rejecting stale writers does.
Try it: Leases, pauses and fencing
Set how often the leader renews, how long until others take over, and how long the leader freezes without knowing it. Each row shows the arithmetic: how long a real crash leaves you leaderless, whether a slow leader gets replaced by mistake, and whether the old leader's late write does damage.
etcd's defaults: a heartbeat every 100 ms and a 1-second election timeout, three members a few milliseconds apart in one region. The leader has a short 50 ms GC pause now and then.
| What we're sizing | Number | How we got it | So we decide |
|---|---|---|---|
| 1 · The leader really dies | |||
| No leader forA dead leader can't hand over. The others can't tell dead from slow, so they wait out the timeout first. The timeout is the floor on every failover. | about 1.5 s | nobody may take over until the lease runs out: T = 1.0 s plus a random extra wait of 0 to T so candidates don't all stand at once, plus a vote (~2 round trips = 10 ms) → 1.0 s to 2.0 s, typically 1.5 s 12 crashes a year × 1.5 s = 18 s a year without a leader | Sub-second to a few seconds per crash: fine for most primaries. Clients should retry writes through a failover. |
| 2 · The leader is alive but slow | |||
| False failover?A timeout can't tell a dead leader from one that is frozen, overloaded or behind a slow link. Too short and normal hiccups cause elections; too long and real crashes take longer to fix. | no | heartbeats that can go missing in a row: ⌊T ÷ h⌋ − 1 = ⌊1000 ÷ 100⌋ − 1 = 9 timeout ÷ round trip = 1000 ÷ 5 = 200× (etcd: at least 10×) worst case, the freeze starts just before a renewal: lease left = T − h = 900 ms; freeze = 50 ms → it wakes with lease to spare | Good margin for ordinary hiccups. |
| 3 · Two leaders at once | |||
| The old leader's late writeCompare the drift line with the freeze: clock drift costs microseconds to milliseconds, a pause can cost seconds. A lease alone can't protect you from a process that stops without knowing it stopped. Only the resource it writes to can say no. | none | no takeover happened, so there is only one leader and only token 33 in use clock drift: over one lease of 1.0 s, a 0.02% drift is 200 µs; the leader should stop acting that much early | Every write carries the token; the storage keeps the highest it has seen and rejects lower ones. |
| 4 · Verdict for this setup | |||
| What you get | Balanced: quick failover, no false alarmsFollowers tolerate 9 missed heartbeats and the timeout is 200× the round trip, so ordinary delays don't trigger elections. A 50 ms freeze fits inside the 900 ms left on the lease. A real crash costs about 1.5 s of leaderless time. Keep fencing on anyway: the next pause may be longer. | ||
Try: on etcd defaults, raise the freeze to 1,000 ms and watch a false failover appear. On Long GC pause, turn fencing on: same takeover, no harm. On 12 s lease, cut the timeout to 3,000 ms: recovery gets fast, and the 4-second freeze becomes a false failover again. On Across regions, raise the timeout to 1,500 ms and the heartbeat to 150 ms. The heartbeat costs 10 messages a second per follower. Timings are rounded, typical teaching values; failover assumes Raft-style randomised timeouts, and the freeze starts at the worst moment, just before a renewal.
Distributed locks: for efficiency or for correctness?
First ask what happens if two processes hold the lock at once: if it's only wasted work, a simple Redis lock is fine; if it's corrupted data, use a consensus-backed lock with fencing, or better, avoid the lock with a conditional write.
The clubhouse booking
In a flat shared by four friends, there's a sticky note on the fridge: "I'm buying milk today — Arjun". It's a lock. If it fails and two of them buy milk, the cost is an extra packet in the fridge. Nobody needs a notary.
Downstairs, the society clubhouse can host one function per Saturday. Two families each think they've booked it for their daughter's sangeet on the 14th. If that lock fails, 300 guests turn up to the same hall. Here, a sticky note isn't enough. The secretary keeps one register, and a booking counts only when it's written in that register against an empty line.
Same word, "lock", two very different jobs.
Ask: what's the cost if two holders act at once?
- Efficiency lock: avoids duplicate work (two workers rebuilding the same cache entry or sending the same report). Rare double work is acceptable. A single Redis instance with SET key value NX PX 30000 and a compare-and-delete release is enough.
- Correctness lock: two holders would corrupt data, double-charge or double-book. Use a lock backed by consensus (ZooKeeper, etcd, Chubby) so the lock state survives node failures, and add fencing tokens, because a lease can still expire under a paused holder.
- Often better: no lock at all. Push the rule into the database: a unique constraint, a conditional write (UPDATE … WHERE version = 7), a compare-and-set, or one partition owner that serializes all changes to a key. These are atomic where the data lives.
On Redlock (a lock across five independent Redis masters): it improves availability over one instance, but Kleppmann argued its safety depends on timing assumptions (bounded pauses, network delay and clock drift); Redis's author disputed parts of that. The safe interview stance: fine for efficiency, and for correctness add fencing or use a consensus store.
The Redis docs describe the single-instance lock as SET resource_name my_random_value NX PX 30000, with a random value "unique across all clients and all lock requests" so a client can release only its own lock. Redlock needs the lock on a majority of N = 5 masters (at least 3) within the validity time. The docs link both Kleppmann's critique and antirez's reply, and warn that Redis doesn't use a monotonic clock for key expiry, so a wall-clock jump could let two processes hold the lock (Redis docs, checked Oct 2026).
Kleppmann's rule of thumb: for efficiency, the cost of a failed lock is "a minor increase in cost"; for correctness, it can be "a corrupted file, data loss, permanent inconsistency" (Kleppmann, Feb 2016).
- Redis locks: fast and simple, a millisecond to acquire, but not safe for correctness without fencing.
- Consensus-backed locks: survive node failures and give you a token, but cost a quorum write per acquire and add an operational dependency. Avoiding the lock with a conditional write is often both simpler and safer.
For the report job, a Redis lock is fine: if two run, we send one duplicate internally. For seat booking I wouldn't use a lock at all: the seat row has a status and version, and the booking is a conditional update that succeeds for exactly one request.
Reaching for "a distributed lock in Redis" to prevent double booking or double payment. The next question is "what if the holder pauses past the TTL?", and the honest answer is that both requests go through.
Consensus and Raft: one agreed log
Consensus lets a group of machines agree on one value, or one ordered log of values, and keep agreeing when a minority crash; with 2f + 1 members it survives f failures, and Raft does it with a leader, terms and majority-acknowledged log entries.
Five scorers, one scorebook
A district cricket final has five official scorers, each with their own scorebook. The chief scorer calls out each ball: "over 32, ball 4: two runs". A ball counts once three of the five have written it down. Then the chief says "confirmed", and the scoreboard updates.
If the chief scorer collapses from the heat, the other four notice the silence. One of them says "I'll be chief for the second session", and becomes chief only if a majority agree, and only if her book is at least as complete as theirs. Anyone whose book is missing balls copies them from the new chief.
Because every confirmed ball is in at least three books, and any new chief needs three votes, at least one voter always has every confirmed ball. A confirmed ball can never be lost or changed.
- The problem: several nodes must agree on a value (who's leader, the next log entry) even if some crash and messages are delayed. Agreeing on a sequence of values gives a replicated log; apply it in order on every node and you get a replicated state machine (a key-value store, a lock service).
- Majorities: 2f + 1 nodes tolerate f crashes: 3 survive 1, 5 survive 2. Four is no better than three.
- Raft (Ongaro and Ousterhout, 2014), in three parts:
- Leader election: terms; a node votes once per term, only for a candidate whose log is at least as up to date as its own; a majority of votes wins.
- Log replication: the leader appends entries and sends them to followers; an entry is committed once stored on a majority, and only then applied and acknowledged to the client.
- Safety: a newly elected leader always has every committed entry.
- Safety never depends on timing; only progress does. FLP (Fischer, Lynch and Paterson, 1985) proved no deterministic algorithm can guarantee agreement in a fully asynchronous system if even one node may crash. Real systems use timeouts for liveness, so during network trouble a consensus group may stall but must not disagree.
- Paxos (Lamport) solves the same problem; ZooKeeper uses its own protocol, ZAB. All of these assume crash failures, not lying (Byzantine) nodes.
The Raft paper: "A log entry is committed once the leader that created the entry has replicated it on a majority of the servers"; "five is a typical number, which allows the system to tolerate two failures". It recommends randomised election timeouts, e.g. 150 to 300 ms, so candidates rarely split the vote; with a 12 to 24 ms timeout, electing a new leader took 35 ms on average in their tests (USENIX ATC 2014).
ZooKeeper's admin guide: to tolerate F failures, "deploy 2xF+1 machines"; "with four machines ZooKeeper can only handle the failure of a single machine" (ZooKeeper docs, checked Oct 2026).
Kafka 4.0 (March 2025) is "the first major release to operate entirely without Apache ZooKeeper": its metadata now lives in KRaft, a Raft-based controller quorum (Apache Kafka, Mar 2025).
- Consensus gives one agreed order that survives a minority of failures with no data loss, the foundation for linearizable stores and safe leader election.
- Every committed write needs a round trip to a majority plus a durable disk write, all writes go through one leader, and a group that loses its majority stops accepting writes.
The metadata store runs Raft on three nodes across three zones. A write commits when two of three have it on disk, so we survive one zone down with no data loss. If two are down it stops taking writes rather than risk two histories.
Confusing consensus with two-phase commit, or with quorum reads and writes. 2PC is atomic commit across different shards and blocks if the coordinator dies; plain quorums don't give one agreed order. Consensus is replication of one log across copies.
Consensus in practice: cost, cluster size and what to coordinate
Consensus is slow and small by design, so use it for the few decisions that must be agreed (who leads, membership, config, the shard map) and keep the data path out of it, or split the data into many small consensus groups.
The family that polls everything
A large family runs a WhatsApp group. For the wedding venue, they run a poll and wait until most of the elders have voted. That's right: it's a big decision, and everyone must agree on one answer.
Then someone starts a poll for every small thing: what time to leave, which sweets to order, who picks up the cousins from the station. Nothing moves until a majority replies, and half the family is asleep in another time zone.
The family that works well uses the poll only for the big things, including "who's in charge of the sweets". After that, the person in charge just decides, and everyone else follows.
What a consensus write costs:
- One round trip from the leader to a majority, plus a durable disk write (fsync) on each. Same zone: about a millisecond or less; across regions: tens to hundreds of milliseconds (rounded, typical).
- All writes go through one leader, so throughput doesn't grow with members. Adding members adds fault tolerance and makes writes slower.
- Keep groups at 3 or 5 members, and timeouts well above the round trip.
How systems use it:
- Coordination service (ZooKeeper, etcd, Chubby): a small, strongly consistent store for leader election, locks, membership, configuration and service discovery, with watches so clients learn of changes. Not for bulk data.
- Leader per shard: consensus elects a leader (or assigns a lease) per partition; that leader then orders that partition's writes on its own. Kafka's partition leaders, assigned by the controller, work this way.
- Multi-Raft: split the data into many ranges, each its own small Raft group, so the work spreads across leaders (CockroachDB, TiKV, Spanner's Paxos groups).
etcd's limits make the "small" explicit: requests up to 1.5 MiB by default, a default storage quota of 2 GiB and a suggested maximum of 8 GiB (etcd docs, checked Oct 2026). Kubernetes keeps all its cluster state in etcd, which is why etcd's latency and disk speed matter so much to a cluster.
CockroachDB organises "all nodes that contain a replica of a range" into a Raft group; three replicas is the smallest number that can reach quorum. The leaseholder serves strongly consistent reads without running Raft, since its writes have already been agreed (CockroachDB docs, checked Oct 2026).
Chubby's design note, again: it provides "only coarse-grained locking", locks held for hours or days, not per-request locking (OSDI 2006).
- Consensus for control decisions only: a small, reliable core, and a fast data path that follows its decisions.
- Consensus on the data path (one group per shard): every write is strongly ordered and survives failures, but costs a quorum round trip and needs many groups to scale.
I'd keep coordination out of the request path. etcd holds who leads each partition and the partition map; each partition's leader orders its own writes and replicates them. A request never waits on etcd unless leadership is changing.
Proposing ZooKeeper or etcd as the main database, or a five-region consensus group for user writes, without noticing that every write then pays a cross-region majority round trip.
Remember it
One line per idea. Read this the night before.
- Wall clocks skew and jump: don't order events across machines by timestamp; use the monotonic clock for timeouts and leases.
- Lamport and hybrid clocks order events by cause, not by wall time; TrueTime knows its error and waits it out (commit wait).
- A timeout can't tell dead from slow. Elect by majority with increasing terms; an old leader steps down when it sees a newer term.
- A lease expires on its own, so nobody has to prove the holder died; the holder must stop acting before it ends. It can't stop a paused holder.
- Fencing token: a number that only goes up with each grant, checked by the storage. It makes a paused old leader harmless.
- Locks: efficiency (Redis is fine) vs correctness (consensus + fencing). Better still: a conditional write or unique constraint, no lock.
- Consensus (Raft, Paxos): one agreed log; 2f + 1 nodes survive f; commit at a majority; safety never depends on timing, progress does.
- Consensus is slow and small: use it for leaders, membership, config and shard maps; keep the data path out, or use many small groups.
Check yourself
Answer out loud, then open.
A cron job must run exactly once per hour across three app servers. How do you design it?
Elect one runner, and make the job itself safe to repeat.
- Leader election through a lease in etcd or ZooKeeper (or a Kubernetes Lease): one instance holds it and renews it; if it dies, another takes over after the lease expires.
- The job carries the fencing token (or the run's hour) in its writes: INSERT the run row for "2026-10-23 14:00" with a unique key, so a second runner's insert fails.
- Make the job's effects idempotent, because a takeover can happen halfway through a run.
Say it The lease decides who usually runs it; the unique run key decides that it only counts once.
Your lock has a 30-second TTL. The holder hits a 40-second GC pause. Walk through what happens and how to make it safe.
- At 30 s, the lock expires. Another client takes it and starts writing.
- At 40 s, the first client wakes. From its view no time passed; it still thinks it holds the lock and writes too. Two writers, one resource.
- A longer TTL only moves the line: the next pause may be longer, and a long TTL slows every real failover.
The fix is fencing: each grant carries an increasing token (33, then 34). The storage keeps the highest token seen and rejects 33 once it has seen 34. If the storage can't check tokens, use a conditional write on a version column instead.
Why does a consensus cluster usually have 3 or 5 members, not 4 or 7?
- Tolerance comes from majorities: 2f + 1 members survive f failures. 3 survive 1, 5 survive 2.
- 4 needs a majority of 3, so it still survives only 1, with one more node to pay for and one more vote to wait on. Even numbers add cost but no tolerance.
- 7 survives 3, but every write waits for 4 acknowledgements and the leader sends to 6 followers. Most teams don't need to survive three simultaneous failures.
Say it Three in one region across zones for most systems; five when I need to survive a zone down plus one more node.
Two servers write the same key; the server clocks differ by 300 ms. With last-writer-wins by timestamp, what goes wrong, and what are the alternatives?
The server whose clock is ahead wins, even if its write happened earlier in real time. A user can save, see the save, and then have it overwritten by an older edit; nothing errors, data is silently lost.
Alternatives:
- One leader per key that assigns a sequence number, so order comes from the leader, not from clocks.
- Conditional writes with a version number: a write based on an old version fails and retries.
- A database with hybrid logical clocks or TrueTime and a bounded max clock offset, if you need a global order.
- If both edits matter, keep both (version vectors) or use a CRDT.
The network splits a 5-node Raft cluster into groups of 3 and 2. The old leader is in the group of 2. What happens on each side?
- Group of 3: followers stop hearing heartbeats, time out, and one wins an election with 3 votes in a new, higher term. It commits writes, since 3 is a majority of 5.
- Group of 2: the old leader can still receive client requests, but it can't get any entry onto a majority, so nothing it accepts is committed or acknowledged. Clients there time out or get errors.
- When the split heals, the old leader sees the higher term, steps down, and its uncommitted entries are replaced by the new leader's log.
Safety holds throughout: only one side can commit. The minority loses availability, which is CAP's C choice.
When is a Redis lock good enough, and when isn't it?
Good enough when a failed lock only wastes work:
- Two workers warming the same cache entry, sending the same internal report, or recomputing a thumbnail.
- Use SET key random NX PX ttl and release only if the value is still yours.
Not enough when a double holder causes harm you can't undo:
- Charging a card, booking a seat, allocating a unique ID, writing to shared storage.
- Use a consensus-backed lock with fencing tokens, or skip the lock: a unique constraint or conditional update in the database does the job atomically.
Spanner waits before it acknowledges a commit. Why, and what does that buy?
TrueTime returns an interval [earliest, latest] that contains the true time, a few milliseconds wide. Spanner gives a transaction a commit timestamp s and then waits until TT.after(s) is true, so s is certainly in the past everywhere.
What it buys: any transaction that starts after this one commits gets a higher timestamp, on any server in the world. Timestamp order matches real-time order (external consistency), and consistent snapshot reads need no global coordination.
The cost: every write waits out the uncertainty, about twice ε. That's why good clocks (GPS, atomic) matter: they keep ε, and therefore the wait, small.
Where you'll use this in the series
- Consistency, CAP and quorums · why overlapping quorums still need one agreed order
- Replication and sharding · leader failover, and what elects the new leader
- Uber: from tap to pickup · one owner per trip, so state changes have one order
- Idempotency, exactly-once and sagas · staying correct when a fenced-out worker's job is retried
- Queues and event streams · partition leaders and consumer-group coordination
- Distributed job scheduler · leases, fencing and running each job once (coming)
- Unique ID generator · ordering without trusting clocks (coming)
- Message queue (Kafka) · KRaft controllers and partition leadership (coming)
Sources
- Time, clocks, and the ordering of events in a distributed system, Lamport, CACM (Jul 1978)
- Impossibility of distributed consensus with one faulty process, Fischer, Lynch & Paterson, JACM (1985)
- The Chubby lock service for loosely-coupled distributed systems, Burrows, OSDI (Nov 2006)
- Spanner: Google's globally-distributed database, OSDI (Oct 2012)
- In search of an understandable consensus algorithm (Raft), Ongaro & Ousterhout, USENIX ATC (2014)
- How to do distributed locking, Martin Kleppmann (Feb 2016)
- Is Redlock safe?, antirez (Feb 2016)
- How and why the leap second affected Cloudflare DNS, Cloudflare (Jan 2017)
- October 21 post-incident analysis, GitHub (Oct 2018)
- It's about time: microsecond-accurate clocks on Amazon EC2 instances, AWS Compute Blog (Nov 2023)
- Apache Kafka 4.0.0 release announcement (Mar 2025)
- Clock management in CockroachDB, Cockroach Labs (Apr 2025)
- Tuning (heartbeat interval and election timeout), etcd docs (checked Oct 2026)
- System limits, etcd docs (checked Oct 2026)
- ZooKeeper administrator's guide, Apache ZooKeeper (checked Oct 2026)
- kube-scheduler configuration (leader election), Kubernetes docs (checked Oct 2026)
- Distributed locks with Redis, Redis docs (checked Oct 2026)
- Replication layer, CockroachDB docs (checked Oct 2026)
Checked October 2026. Definitions come from the papers listed (Lamport 1978, Fischer, Lynch & Paterson 1985, Chubby 2006, Spanner 2012, Raft 2014) and the official etcd, ZooKeeper, Kubernetes, Redis and CockroachDB docs; company statements are as published on the dates shown (Kleppmann and antirez 2016, Cloudflare 2017, GitHub 2018, AWS 2023, Kafka 2025, Cockroach Labs 2025) and may have changed since. The lab's timings are rounded, typical teaching values; its failover model assumes Raft-style randomised timeouts.
System Design Mastermind · Foundations
Series homeAll of Foundations
18 publishedStart here: the concepts every design uses, each told as a story you'll remember.
How a request travels: DNS, load balancers, gateways and open connections
Name → address (DNS) → open a secure line once and reuse it (TCP, TLS) → nearby copies for static files (CDN) → spread and guard the work (load balancer, gateway) → find colleagues inside (discovery) → keep a line open for live updates.
The interview framework: requirements, numbers and scope before boxes
Agree what users must do (three core requirements) → put numbers on how well (p99 latency, availability, durability, staleness) → say what's out of scope → sketch the simple end-to-end design → go deep only where a number breaks it.
Back-of-envelope estimation: from users to servers in one minute
Users × actions ÷ 86,400 (≈10⁵) = average per second → × peak factor → split reads and writes → storage = count × size × time × copies → bandwidth × 8 bits → in flight = rate × latency → servers = peak ÷ (capacity × 60%) + 2 spares.
APIs and real-time communication: REST, gRPC, retries, webhooks and live updates
Nouns + HTTP verbs (user from the token) → REST outside, gRPC inside → cursor pagination → POST with an Idempotency-Key, retries with backoff and jitter → add, don't change → poll for rare updates, SSE for one-way live, WebSockets for both ways → webhooks are at-least-once → thin connection gateways with resume and push fallback.
Databases: data models, indexes and transactions
Relational by default (each fact once, keys, constraints) → key-value / document / wide-column / graph only for a named access pattern → B-tree for reads, LSM for heavy writes → composite index with equality columns first, then the sort → one transaction per local change, made durable by the write-ahead log → know your isolation level → win races with a conditional write and a unique constraint.
Replication and sharding: copying and splitting your data
Copies scale reads and survive failures (leader + followers); splits scale writes and size (shards). Replicate first; shard only when data size or write rate outgrows one leader → pick the shard key from the main query → hash it into many fixed slots so growth moves ~1/(N+1) → name your hot key and your one cross-shard query.
Caching: hit ratios, invalidation and stampedes
Cache what is read far more than it changes → say the expected hit ratio and size the database for the misses → cache-aside with a TTL; on writes, update the database then delete the key → coalesce misses on hot keys and jitter TTLs → plan for the cache failing or restarting empty, because by then the system depends on it.
Consistency, CAP and quorums: what replicas promise
Say what each operation needs, not what the system is: strong (linearizable) for money, stock, seats and uniqueness; read-your-writes for a user's own data; eventual for counts, feeds and pages → during a partition, strong operations fail on the minority side, the rest keep serving (CAP) → on a normal day, strong costs a round trip to a quorum (PACELC) → with N copies, W + R > N makes reads overlap the latest write, but it isn't linearizability.
Coordination: clocks, leaders, locks and consensus
Don't order events across machines by wall-clock time; let one leader assign the order → elect that leader by majority vote with increasing terms, so a split network can't elect two → give it a lease so a dead leader is replaced without anyone proving it died → and a fencing token the storage checks, so a paused old leader can't do harm → use consensus (Raft) for the few decisions that must be agreed, not for every request.
Queues and event streams
Put a queue between work that can wait and the caller, so a spike becomes lag instead of an outage → use a task queue for jobs and an event log (Kafka) when many consumers need every event, replay or per-key order → key by the entity whose order matters and size partitions for peak consumers → deliver at least once and make consumers idempotent → retry a few times with backoff, then dead-letter → scale on lag → publish through an outbox, never "save, then publish".
Idempotency, exactly-once and sagas
Treat a timeout as unknown, never as failed → make writes idempotent by design (set, don't add; client IDs; conditional writes) → for the rest, an idempotency key per intent, stored with the result in the same transaction as the effect → consumers deduplicate by message ID in the same transaction → exactly-once holds only inside one boundary → across services, use a saga of local steps with compensations, not 2PC → compensable steps first, the pivot (capture payment) next, retryable steps last, on a durable orchestrator.
Scaling and performance
State latency as a percentile at a stated load → size each tier to the utilisation where its p99 is still flat (pooled, least-request balancing lets you run hotter) → budget fan-out calls against the page deadline, hedge stragglers → scale up first, scale out stateless tiers → name the shared resource (database, lock, connections) that caps the speed-up → find the saturated resource and cut work per request → pre-scale known peaks, autoscale on the signal that saturates → under overload, shed the lowest-priority work fast and budget retries.
Reliability and disaster recovery
Turn the target into a downtime budget → cut hard dependencies, because chains multiply → spread copies across zones (cells for blast radius) → timeouts from the deadline, one layer of jittered retries under a budget → circuit breakers with fallbacks and a bulkhead per dependency → fast, non-flapping health checks (readiness checks dependencies, liveness doesn't) → statically stable: spare capacity already running, config cached → PITR plus tested restores, because replicas copy mistakes → the cheapest DR strategy that meets RTO and RPO, drilled.
Observability and safe deployments
Metrics to notice, traces to locate, logs to explain (joined by a trace ID) → watch latency percentiles, traffic, errors and saturation → set an SLO per user journey and treat 1 − SLO as an error budget → page on burn rate over two windows, not on CPU → canary every change on a slice with automated analysis against a baseline → keep every version compatible with its neighbours (expand, migrate, contract) so rollback is always possible → ship dark behind flags, and stage config like code → when it breaks: one commander, mitigate first, blameless postmortem.
Security essentials for system design
Prove who the caller is (slow salted hashes, MFA, passkeys, rate-limited login) → carry identity in short-lived signed tokens with revocable refresh tokens, or in sessions you look up → delegate with OAuth code flow + PKCE, sign in with OpenID Connect → check this user against this object on every request, least privilege for people and services, audit logs → TLS 1.3 at the edge, mTLS inside, no trust from network location → envelope encryption with a KMS, secrets in a vault, tokenise what you needn't keep → treat all input as data (parameterise, encode, CSRF tokens, no user-chosen fetches) → absorb floods and abuse at the edge.
Search, feeds and geo building blocks
Search: analyse text into terms → inverted index of sorted postings → BM25 or hybrid (BM25 + vectors via RRF) retrieval of ~1,000 candidates → learned ranker → shards with replicas, fed from the database by CDC, refreshed every second. Typeahead: precomputed top-k per prefix in memory. Feeds: push IDs into followers' timelines, pull celebrities at read time, hydrate, filter, rank, page with cursors. Geo: index by cell (geohash, S2, H3), search the cell plus neighbours, exact distance on the few candidates.
Data pipelines: batch and stream
Pick batch or stream by how fresh each output must be. Get data in with log-based CDC (snapshot, then the WAL) and schemas that evolve safely; land raw events as Parquet in lakehouse tables partitioned by date. Batch jobs map, shuffle and reduce one partition and overwrite it, so retries and backfills are safe. Stream jobs window by event time, fire on watermarks, decide whether late events wait, correct or drop, and checkpoint state with offsets for exactly-once effect, with transactional or idempotent sinks. Reprocess by replaying retained data (Kappa) rather than keeping two codebases (Lambda).
AI foundations: inference, RAG and agents
Latency is time to first token (prefill reads the prompt, compute-bound) plus output tokens × time per token (decode, memory-bound), so stream answers and limit by tokens. GPU memory is weights plus a KV cache per request; long prompts, not users, fill it. Continuous batching shares each weight read across many requests, cutting cost per token by 10× or more until time per token hits its target. Route easy requests to small models, cache shared prompt prefixes, quantize carefully. RAG retrieves, reranks and cites a few permission-filtered chunks; agents are tool-calling loops with budgets, idempotent tools and approval for irreversible steps. Evaluate every change on an eval set, and design so a model fooled by prompt injection still can't do damage.