Objective
Machines crash, disks fill, networks drop or delay packets, and a process can pause for seconds in garbage collection. A system that holds positions, orders or research data must keep working, or at least keep its data correct, through all of these. By the end of this lesson you should be able to explain replication and quorums with numbers, state CAP precisely enough not to misuse it, say what consensus guarantees, design a retry policy that does not make an outage worse, and choose a checkpoint interval.
Replication
Keep copies of the data on several machines (replicas) so a failure loses neither the data nor the service.
- Leader-follower (primary-replica): one leader accepts writes and streams them to followers. Reads can go to followers, but a follower may lag.
- Synchronous replication acknowledges a write only after followers have it: no data loss on leader failure, but write latency includes the slowest required follower.
- Asynchronous replication acknowledges after the leader writes: fast, but writes acknowledged in the last moments before a leader crash can be lost when a lagging follower is promoted.
- Leaderless (quorum) systems write to and read from several replicas directly.
Quorums
With replicas, a write waits for acknowledgements and a read queries replicas. If
every read set overlaps every write set in at least one replica, so a read sees the latest acknowledged write (given versions to tell which response is newest). With , overlap is guaranteed and one replica can be down for both reads and writes. is fast but can read stale data. , tolerates two failures.
Availability with independent failures
If each node is up with probability independently, a service needing a majority of 3 is up with probability
For this is : downtime falls from 1% to about 0.03%. With 5 nodes needing 3 it is . But a design that needs all three nodes is up only , worse than one node: replication improves availability only if the system can proceed without some replicas. Real failures are also correlated (same rack, same bad deploy, same region), so these numbers are upper bounds.
CAP in plain terms
A network partition splits the replicas into groups that cannot talk to each other. During a partition, a replica receiving a request has two choices:
- Consistency (C): refuse or block until it can coordinate, so no client ever sees stale or conflicting data. The minority side becomes unavailable.
- Availability (A): answer from local data, so every live replica keeps serving, accepting that different sides may diverge and must be reconciled later.
CAP says you cannot have both during a partition. It does not say you must give up one of three properties at all times; when the network is healthy, a system can be both consistent and available. The more useful everyday trade-off (sometimes called PACELC) is latency versus consistency: even without a partition, coordinating with other replicas on every operation costs round trips.
Applied to a trading firm:
- Positions, risk limits, order state: choose consistency. Two risk servers that each believe they have the full limit available would together allow twice the risk. Refusing to trade during a partition is the safe failure.
- Market-data caches, dashboards, research reads: choose availability. A slightly stale chart is better than none.
"Consistency" here means linearisability: the system behaves as if there were one copy and every operation happened at one instant. Weaker models (read-your-writes, monotonic reads, eventual consistency) are cheaper and often enough, but you should be able to say which one each part of the system needs.
Consensus, intuitively
Consensus is how a group of nodes agrees on one value, or one ordered log of commands, despite some of them failing. Raft and Paxos are the standard algorithms; ZooKeeper, etcd and the metadata layer of Kafka use them. The intuition:
- A leader proposes log entries; an entry is committed once a majority has stored it.
- Any two majorities overlap, so a new leader elected by a majority necessarily includes a node that has every committed entry. Committed entries are never lost.
- Leaders hold numbered terms; a node rejects messages from an older term, which stops a deposed leader that wakes up from a pause from overwriting newer decisions.
- With nodes, the cluster tolerates crashed nodes. Three nodes tolerate one failure, five tolerate two. Four nodes still tolerate only one (a majority of 4 is 3), so even sizes add cost without adding tolerance.
You rarely implement consensus; you use a coordination service for the few things that must be agreed exactly: who the leader is, a lock, a configuration version, a sequence number. A related trick is the fencing token: every lock grant carries an increasing number, and the storage system rejects writes carrying a smaller number than one it has already seen, so a paused former lock holder cannot corrupt data.
Retries with backoff and jitter
Transient failures (a timeout, a dropped connection, a 503) are usually fixed by retrying. Bad retries turn a brief overload into an outage:
- Retry only operations that are idempotent (or made so with an idempotency key; see Data Ingestion). Retrying "send order" without a client order id can send two orders.
- Retry only transient errors. A validation error will fail again.
- Exponential backoff: wait before retry (), capped at a maximum, with a maximum number of attempts or total time.
- Jitter: randomise each wait, for example uniformly in ("full jitter"). Without it, every client that failed together retries together, in synchronised waves that hit the recovering server at once (a thundering herd).
- Retry budgets and circuit breakers: cap retries as a fraction of traffic, and stop calling a dependency that is clearly down, failing fast instead.
- Retry at one layer. If each of three layers makes up to 4 attempts, a failing bottom service receives up to requests for one user request, exactly when it is least able to handle them.
Checkpointing
A long computation (a backfill, a large simulation, a stream processor's state) should periodically save its progress so a failure restarts from the last checkpoint rather than from the beginning. Stream processors checkpoint state together with input offsets, atomically, which is what makes their exactly-once guarantees possible. Batch pipelines get the same effect for free if each partition is an idempotent unit of work: completed partitions are the checkpoint.
Checkpointing too often wastes time writing checkpoints; too rarely wastes time redoing work. With checkpoint cost and mean time between failures , the overhead per unit of work is approximately
the checkpoint time per interval plus, on average, half an interval of lost work per failure. Minimising over gives Young's approximation
Worked example
a checkpoint interval
A backfill runs on a cluster whose jobs fail on average every 6 hours. Writing a checkpoint takes 30 seconds. What interval minimises overhead, how large is the overhead, and what happens at 5 minutes or 1 hour instead?
Show solutionHide solution
Step 1: units. s, s.
Step 2: optimum.
Step 3: overhead at the optimum. Both terms are equal there: and , so the total is about .
Step 4: alternatives.
| Interval | Overhead | ||
|---|---|---|---|
| 5 min (300 s) | 0.100 | 0.007 | 10.7% |
| 19 min (1138 s) | 0.026 | 0.026 | 5.3% |
| 1 hour (3600 s) | 0.008 | 0.083 | 9.2% |
A simulation with exponential failure times and restarts from the last checkpoint gives 10.9%, 5.4% and 9.9% for the three intervals, close to the first-order formula. The optimum is flat: anything from about 10 to 40 minutes is within a couple of points. The formula's real value is the scaling, : quadrupling the failure rate halves the best interval.
Worked example
design the retry policy for a reference-data call
A pricing service calls a reference-data service that occasionally returns 503 during deploys lasting up to a few seconds. Thousands of pricing workers call it. Propose a retry policy with base 100 ms, doubling, a 5 s cap and at most 6 retries, and say how long a single caller can wait in the worst case and on average.
Show solutionHide solution
Step 1: the schedule. The caps on the waits are ms for : 100, 200, 400, 800, 1600 and 3200 ms. None reaches the 5 s cap.
Step 2: worst-case waiting. Without jitter, the total is ms, about 6.3 s, which spans a deploy of a few seconds.
Step 3: jitter. With full jitter each wait is uniform on , so the expected total wait is half, about 3.15 s, and the worst case is still 6.3 s. More importantly, thousands of workers that all failed at the same instant now spread their retries across each interval instead of arriving together at 100 ms, 300 ms, 700 ms and so on.
Step 4: the rest of the policy. Retry only on 503 and timeouts (the call is a read, so it is idempotent); never on 4xx. Retry only in the pricing worker, not also in the client library and the load balancer. Add a circuit breaker: if most calls failed over the last few seconds, fail fast and serve the last cached reference data, marked as stale, which is an availability-over-consistency choice that is acceptable for reference data and would not be for positions.
Knowledge check
A replicated store has N = 5 replicas. Which read and write quorum sizes guarantee that every read sees the latest acknowledged write, while tolerating two unavailable replicas for both reads and writes?
Knowledge check
Two data centres each run a risk server that checks orders against a shared gross limit. The link between them fails. Which behaviour is the safe CAP choice, and why?
Knowledge check
Why do consensus clusters typically have 3 or 5 nodes rather than 4?
Knowledge check
An API gateway, an application server and a database client library each retry a failed call up to 3 times (4 attempts each). The database is overloaded and failing every request. How many database requests can one user request cause?
Key takeaways
- Replication helps availability only if the system can proceed without some replicas. Synchronous replication avoids data loss at the cost of latency; asynchronous can lose recent writes on failover.
- Quorums with overlap, so reads see the latest acknowledged write. A majority of 3 at gives about 99.97% availability; requiring all 3 gives about 97%.
- CAP: during a partition, choose between refusing (consistency) and answering from local data (availability). Choose per data type: consistency for positions and limits, availability for caches and dashboards.
- Consensus commits an entry once a majority stores it; overlapping majorities preserve committed entries. nodes tolerate failures.
- Retries: idempotent operations only, transient errors only, exponential backoff with jitter, one layer, budgets and circuit breakers.
- Checkpoint at about ; the optimum is flat, and idempotent partitions make completed work a free checkpoint.
Finished reading?
Answer the 4 knowledge checks to complete this lesson (0 done).