CAP theorem: when the network splits, answer or be right
Keep copies of your data on more than one machine and, one day, the network between them will break. A copy that can't reach the others then has two moves: answer from what it holds, or refuse until it can check. One seat left, three copies, two buyers.
What you'll take away
- Explain the choice a cut-off copy makes: answer from what it holds, or refuse
- Know why 'pick two of three' misleads, and why each operation makes its own choice
- Use R + W > N to tell when a read is sure to meet the newest write
- Weigh PACELC's choice with no split: wait for more copies, right more often but slower
The 1-minute version
Tap a point and the picture below plays that step.
Try all three with the network whole, then split: which one oversells, which one refuses, and which one oversells with nothing broken?
Three copies, and the network splits: C is on its own. A customer asks C whether a seat is left. What can C do?
The picture: one seat left, kept as three copies. Data centres A and B stand on the left, C across the long street; Ploy's phone is by A, Ton's by C. A blue slab on a roof is the seat still free, an empty gold square means sold, and each label says what that copy holds (v is its version; "old" when a newer one exists). A ring going out is a read, the light coming back carries the answer (blue: 1 left, gold: 0), and a gold block is a write. When the network splits, the street to C breaks between two red barriers and nothing crosses. Model milliseconds, not a measurement.
Compare them all: CAP: answer, or be right
Ploy buys at A, then Ton at C, each way: with the network whole, with C cut off, and after it heals. The boxes are the tickets sold (there's one seat, so a red one is oversold); after them, Ton's answer.
Use it when Things that can be a little old: like counts, feeds, shopping carts, caches. Systems that must answer fast, and answer even when the network splits
Skip it when Anything there's only one of: a seat, the last item in stock, a balance. Both sides can decide on old data at once
From the same model as quorum.ts below, which really runs. Press any tile to see it large above, with when it fits.
Three ways to read and write three copies
| Read · write | Network whole | C cut off | Suits |
|---|---|---|---|
| ONE · ONE | fastest; a read can be old until the write arrives | every side answers; one seat sold twice | likes, feeds, carts, caches |
| QUORUM · QUORUM | each request waits for a second copy | the side with 2 of 3 works; C refuses | bookings, stock, balances, unique names |
| ONE · ALL | reads fast; each write waits for the slowest copy | everyone reads, nobody can write | read often, write rarely: config, prices |
Not “two of three”
Gilbert and Lynch, who proved the theorem, state it for a network that can lose messages: no service can both answer every request and act as one up-to-date copy (Perspectives on the CAP Theorem). Partitions aren't optional, so the choice is only C or A, and only while the network is split. Brewer wrote in 2012 that the two-of-three framing was misleading, that partitions are rare, and that a system can make the choice many times, operation by operation (CAP Twelve Years Later).
R + W > N
With N copies, a read that waits for R of them and a write that waits for W overlap in at least one copy when R + W > N, so the read meets the newest write. Cassandra sends every write to all replicas and lets each query set how many answers to wait for: ONE, QUORUM (a majority), ALL (Cassandra: Dynamo). DynamoDB reads are eventually consistent by default; ConsistentRead asks for the latest data and costs twice as much, and global secondary indexes and streams are eventual only (DynamoDB: read consistency). Abadi notes that even R + W > N does not by itself give the full consistency the theorem means.
PACELC: a choice with no split too
If there is a Partition, choose Availability or Consistency; Else, choose Latency or Consistency. Waiting for more copies takes time on a healthy network too (in the model, a write then a read: 1 ms at ONE and old, 61 ms at QUORUM and new). In 2012 Abadi put Dynamo, Cassandra and Riak's defaults at PA/EL, VoltDB/H-Store, Megastore and BigTable/HBase at PC/EC, and MongoDB at PA/EC (Consistency Tradeoffs in Modern Distributed Database System Design).
Redis, really run
Redis replicates asynchronously by default. A replica that has lost its primary still answers, with possibly old data, unless replica-serve-stale-data no, which answers MASTERDOWN instead. min-replicas-to-write with min-replicas-max-lag make the primary refuse writes (NOREPLICAS) when too few replicas have pinged lately. Redis calls this a best-effort safety measure, and says WAIT does not make it a CP system either (Redis replication).
In real code
// Three copies of one value (seats left on a flight: 1) on three nodes, A, B and C, talking over real TCP links that
// hold every chunk for a set delay. Any node can take a request and coordinate it: it asks the copies and waits for
// R answers to a read, W to a write (ONE = 1, QUORUM = 2 of 3, ALL = 3), and a read returns the newest version it
// got. Cutting a link makes it swallow everything, as a partition does: no error, just silence.
import { createServer as httpServer } from "node:http";
import { createConnection, createServer, type AddressInfo, type Socket } from "node:net";
import { setTimeout as sleep } from "node:timers/promises";
const NODES = ["A", "B", "C"] as const;
type Node = (typeof NODES)[number];
type Copy = { seats: number; version: number };
const LEVEL = { ONE: 1, QUORUM: 2, ALL: 3 } as const;
type Level = keyof typeof LEVEL;
// one-way delay of each link, set here (a model of three sites, not a measurement of any real one)
const DELAY: Record<string, number> = { AB: 15, AC: 40, BC: 30 };
const TIMEOUT = 250; // a request with no answer by then counts as none: a cut link and a slow one look the same
// ---- the copies: a tiny HTTP server per node ----
const copies = new Map<Node, Copy>();
const replicaPort = new Map<Node, number>();
const servers: { close(): void }[] = [];
for (const node of NODES) {
const server = httpServer((req, res) => {
let body = "";
req.on("data", (c: Buffer) => (body += c));
req.on("end", () => {
if (req.method === "POST") {
const next = JSON.parse(body) as Copy;
if (next.version > copies.get(node)!.version) copies.set(node, next); // a newer version replaces an older one
}
res.end(JSON.stringify(copies.get(node)));
});
});
await new Promise<void>((ok) => server.listen(0, "127.0.0.1", ok));
replicaPort.set(node, (server.address() as AddressInfo).port);
servers.push(server);
}
// ---- the links: a TCP proxy per pair of nodes, each way delayed, cut on demand ----
const cut = new Set<string>();
const linkPort = new Map<string, number>();
const sockets = new Set<Socket>();
for (const from of NODES) for (const to of NODES) {
if (from === to) continue;
const key = [from, to].sort().join("");
const proxy = createServer((client) => {
const server = createConnection(replicaPort.get(to)!, "127.0.0.1");
for (const s of [client, server]) { sockets.add(s); s.on("error", () => s.destroy()); s.on("close", () => sockets.delete(s)); }
const relay = (a: Socket, b: Socket) => a.on("data", (chunk: Buffer) => {
if (!cut.has(key)) setTimeout(() => cut.has(key) || b.write(chunk), DELAY[key]);
});
relay(client, server);
relay(server, client);
});
await new Promise<void>((ok) => proxy.listen(0, "127.0.0.1", ok));
linkPort.set(from + to, (proxy.address() as AddressInfo).port);
servers.push(proxy);
}
async function ask(from: Node, to: Node, write?: Copy): Promise<Copy | null> {
const port = from === to ? replicaPort.get(to) : linkPort.get(from + to);
try {
const res = await fetch(`http://127.0.0.1:${port}/seats`, { method: write ? "POST" : "GET", body: write && JSON.stringify(write), signal: AbortSignal.timeout(TIMEOUT) });
return (await res.json()) as Copy;
} catch {
return null;
}
}
// ---- who each node can hear: a ping to the others every 50 ms (a small failure detector) ----
const heard = new Map<string, number>();
const pings = setInterval(() => {
for (const from of NODES) for (const to of NODES) if (from !== to) void ask(from, to).then((c) => c && heard.set(from + to, Date.now()));
}, 50);
const reachable = (at: Node) => NODES.filter((to) => to === at || Date.now() - (heard.get(at + to) ?? 0) < 200);
type Answer = { ok: true; copy: Copy; ms: number } | { ok: false; why: string };
/** Asks every copy it can reach and settles at the need-th answer. Too few reachable: refused before anything is sent. */
async function quorum(at: Node, level: Level, write?: Copy): Promise<Answer> {
const need = LEVEL[level];
const near = reachable(at);
if (near.length < need) return { ok: false, why: `reaches ${near.length} of the ${need} copies it needs` };
const start = performance.now();
const answers: Copy[] = [];
return new Promise((done) => {
let pending = near.length;
for (const to of near) void ask(at, to, write).then((copy) => {
if (copy) answers.push(copy);
if (answers.length === need) {
const newest = answers.reduce((a, b) => (b.version > a.version ? b : a));
done({ ok: true, copy: newest, ms: Math.round(performance.now() - start) });
} else if (--pending === 0 && answers.length < need) done({ ok: false, why: `only ${answers.length} answered in time` });
});
});
}
async function buy(at: Node, read: Level, write: Level): Promise<"ticket" | "sold out" | "refused"> {
const seen = await quorum(at, read);
if (!seen.ok) return "refused";
if (seen.copy.seats < 1) return "sold out";
const wrote = await quorum(at, write, { seats: seen.copy.seats - 1, version: seen.copy.version + 1 });
return wrote.ok ? "ticket" : "refused";
}
async function reset(partition: boolean) {
await sleep(300); // whatever is still on the wire lands first
cut.clear();
for (const node of NODES) copies.set(node, { seats: 1, version: 1 });
if (partition) { cut.add("AC"); cut.add("BC"); } // C is cut off from A and B; A and B still talk
await sleep(300); // long enough for every node to notice who it can hear
}
// 1. No partition. A takes a write, and a read at C follows at once.
const fresh: string[] = [];
for (const level of ["ONE", "QUORUM"] as const) {
await reset(false);
await quorum("A", level, { seats: 0, version: 2 });
const read = await quorum("C", level);
if (read.ok) fresh.push(`${level} ${read.copy.seats === 0 ? "new" : "OLD"} value in ${read.ms} ms`);
}
await reset(false);
const times: string[] = [];
for (const level of ["ONE", "QUORUM", "ALL"] as const) {
const read = await quorum("A", level);
if (read.ok) times.push(`${level} ${read.ms} ms`);
}
// 2. Ploy buys the last seat at A; then Ton, at C, tries to buy it too: with the network whole, then with C cut off.
const PICKS = [["ONE", "ONE"], ["QUORUM", "QUORUM"], ["ONE", "ALL"]] as const;
async function sell(partition: boolean): Promise<string> {
const sold: string[] = [];
for (const [read, write] of PICKS) {
await reset(partition);
const ploy = await buy("A", read, write);
const ton = await buy("C", read, write);
const tickets = [ploy, ton].filter((r) => r === "ticket").length;
sold.push(`R=${read} W=${write}: ${tickets} ticket${tickets === 1 ? "" : "s"} (A ${ploy}, C ${ton})`);
}
return sold.join(" · ");
}
const whole = await sell(false);
const split = await sell(true);
const why = await quorum("C", "QUORUM"); // still cut off
const refusedWhy = why.ok ? "answered" : why.why;
// 3. The link comes back. Nothing here copies a missed write over later (real systems do: read repair, resync), so
// each copy shows what it was sent.
const healed: string[] = [];
for (const level of ["ONE", "QUORUM"] as const) {
await reset(true);
const tickets = [await buy("A", level, level), await buy("C", level, level)].filter((r) => r === "ticket").length;
cut.clear();
await sleep(300);
const read = await quorum("C", "QUORUM");
if (!read.ok || read.copy.seats !== 0) throw new Error("the healed read missed the sale");
const each = NODES.map((n) => `${n} ${copies.get(n)!.seats}`).join(", ");
healed.push(`${level}: copies ${each}, ${tickets} ticket${tickets === 1 ? "" : "s"} out, a QUORUM read at C says ${read.copy.seats}`);
}
clearInterval(pings);
for (const s of sockets) s.destroy();
for (const s of servers) s.close();
console.log(`no partition, a write at A then a read at C: ${fresh.join(", ")} · reads at A: ${times.join(", ")}`);
console.log(`no partition, Ploy buys at A, then Ton at C: ${whole}`);
console.log(`C cut off: ${split} · C at QUORUM ${refusedWhy}`);
console.log(`healed: ${healed.join(" · ")}`);
node quorum.ts (Node 23.6+ · on Node 22 add --experimental-strip-types)It printed:no partition, a write at A then a read at C: ONE OLD value in 1 ms, QUORUM new value in 63 ms · reads at A: ONE 1 ms, QUORUM 32 ms, ALL 81 ms no partition, Ploy buys at A, then Ton at C: R=ONE W=ONE: 2 tickets (A ticket, C ticket) · R=QUORUM W=QUORUM: 1 ticket (A ticket, C sold out) · R=ONE W=ALL: 1 ticket (A ticket, C sold out) C cut off: R=ONE W=ONE: 2 tickets (A ticket, C ticket) · R=QUORUM W=QUORUM: 1 ticket (A ticket, C refused) · R=ONE W=ALL: 0 tickets (A refused, C refused) · C at QUORUM reaches 1 of the 2 copies it needs healed: ONE: copies A 0, B 0, C 0, 2 tickets out, a QUORUM read at C says 0 · QUORUM: copies A 0, B 0, C 1, 1 ticket out, a QUORUM read at C says 0
Three nodes on real TCP links that hold each chunk for a set delay (a model of three sites, not a measurement of any). Any node coordinates a read or a write at ONE, QUORUM or ALL. The last seat is sold with the network whole, with C cut off, and after it heals. Node's standard library only; really run, and below is what it printed.
Common questions
What is the CAP theorem?
If the network can lose messages between copies, a system can't both answer every request and always return the latest write. While the network is split, each copy has to choose: answer anyway (A), or always be right and sometimes refuse (C).
Is it really "pick two of three"?
No. Brewer, who stated it, wrote in 2012 that the two-of-three framing was always misleading. A split isn't something you opt out of; with no split a system can have both C and A. The choice comes only during a split, and can differ from one operation to the next.
Can a system be CA?
CAP is about copies on a network. One machine can't be cut off from itself, so CAP has nothing to say there; when it goes down, nothing answers. Once copies live on different machines, the network will split one day, and you have to say what happens then.
Is Cassandra, or DynamoDB, CP or AP?
You choose per request. Cassandra takes a consistency level per query, such as ONE or QUORUM; DynamoDB reads are eventually consistent by default, and a read can ask for strong consistency with ConsistentRead. One label for the whole system misses that.
What is eventual consistency?
Copies may disagree for a while, but with no new writes they end up the same. The catch: catching up doesn't undo what was already decided on old data. The two tickets are still out, so something has to fix it, a refund or an apology.
What is PACELC?
Daniel Abadi's extension of CAP: if there's a Partition, choose Availability or Consistency; Else, choose Latency or Consistency, since waiting for several copies takes time even on a healthy network. He puts Dynamo and Cassandra's defaults at PA/EL.
How does a quorum keep reads from being stale?
If the copies a read waits for (R) plus the copies a write waits for (W) are more than the number of copies (N), every read set shares at least one copy with every write set, so the read meets the new value. The price: longer waits, and a side short of copies must refuse.
What does Redis do when the network splits?
Redis replicates asynchronously by default, and a replica that lost its primary still answers, with possibly old data. replica-serve-stale-data no makes it refuse; min-replicas-to-write makes the primary refuse writes. Redis's own docs call that best effort, not CP.
Next lesson
Circuit breakers, retries and timeoutsLevel: Deep
A copy that can't reach the others must choose; so must a caller whose service won't answer: wait, retry or fall back.