Budi buys seat A12 through the Kuala Lumpur server. Siti buys the same seat through the Singapore server. Both get "success", because the network between the two servers is down and neither knows about the other. Once the network is back, the seat can belong to only one of them.
You can prevent this, but it has a price. Take TicketTune with two ticket booths at a stadium. Both hold the same seat list and keep each other updated by walkie-talkie. One day the walkie-talkie dies. Option one: both booths stop selling until it works again. No seat is sold twice, but buyers wait. Option two: each booth keeps selling from its own list. Nobody waits, but the same seat can be sold twice and has to be sorted out later. There is no option three.
That is the CAP theorem: when the network between two database nodes is cut, the system has to choose between consistency (everyone who reads sees the latest data, or gets an error) and availability (every request still gets an answer, even if the data may be old).
C, A and P
- Consistency (C): every read gets the latest write, or an error. All the nodes look like a single copy of the data.
- Availability (A): every request to a node that is up gets a non-error answer, even if it isn't the latest.
- Partition tolerance (P): the system keeps running even when messages between nodes are lost because the network has split (a network partition).
The popular wording: a distributed system can only guarantee 2 of those 3 properties at the same time. The precise meaning is narrower: P is not a choice, because networks do go down (the Why Distributed Systems Are Hard lesson). So there is only one question: when a partition happens, do you give up C or A? While the network is healthy, a system can have both.
When the network goes down: CP or AP
Replicas kul (Kuala Lumpur) and sgp (Singapore) store Archipelago Concert's seat A12 and the concert's number of "likes": 1,200. Example model numbers: a local write takes 2 ms, a round trip from Kuala Lumpur to Singapore (RTT) 20 ms. The network between them goes down, then Budi buys A12 through Kuala Lumpur and Siti through Singapore:
| CP: refuse writes | AP: accept, differ for now | |
|---|---|---|
Budi buys A12 at kul |
503 after 500 ms: sgp unreachable |
OK in 2 ms, sgp doesn't know yet |
Siti buys A12 at sgp |
503 after 500 ms |
OK in 2 ms, kul doesn't know yet |
Rina reads A12 at sgp |
free (correct: nobody has bought it) | Siti (Kuala Lumpur says Budi) |
| While it's down | safe, but can't sell | keeps selling, the two replicas differ |
CP (consistency + partition tolerance) chooses to refuse: a write only counts once both replicas have stored it, and when one is unreachable, the write is refused after a timeout. AP (availability + partition tolerance) chooses to answer: each replica takes its own writes, and replication catches up later. The data that differs is made the same afterwards: eventual consistency.
After the network comes back
With AP, the two replicas send each other their pending writes, and then they must reconcile: make the differing data the same.
- The likes are easy. Each replica counts the additions from its own side (Kuala Lumpur +1, Singapore +1), and when merged, they are added up: 1,202. This structure is called a G-Counter, one of the CRDTs (data structures that can always be merged without conflict). If you stored just one number, "the last one wins" would give 1,201: one like lost.
- Seat A12 can't be merged: one seat, two owners. The last-writer-wins rule gives A12 to Siti because her write came later, and Budi's purchase silently disappears even though he has paid.
So A12 goes to Siti, and Budi has to be refunded. That's why seat sales and payments choose CP: better to refuse for a while than to sell one seat to two people. Likes, feeds and shopping carts can be AP.
// TicketTune: seat A12 and the likes on two replicas (an example model)
const MODE = "AP"; // CP: refuse writes while cut off. AP: accept, reconcile later
const RTT = 20; // ms round trip Kuala Lumpur to Singapore
let cut = false;
let clock = 0; // virtual time, ms
const replicas = {
kul: { seatA12: null, likes: { kul: 700, sgp: 500 } },
sgp: { seatA12: null, likes: { kul: 700, sgp: 500 } },
};
const pending = []; // AP writes that haven't reached the other side yet
const other = (side) => (side === "kul" ? "sgp" : "kul");
const totalLikes = (r) => r.likes.kul + r.likes.sgp;
function apply(r, w) {
if (w.kind === "like") r.likes[w.origin] = Math.max(r.likes[w.origin], w.value);
else if (!r.seatA12 || r.seatA12.t < w.t) r.seatA12 = { name: w.name, t: w.t }; // last-writer-wins
}
function write(side, w, label) {
w.t = clock;
if (MODE === "CP") {
if (cut) return console.log(`${label} at ${side}: 503 after 500 ms, ${other(side)} unreachable`);
apply(replicas[side], w);
apply(replicas[other(side)], w); // wait for the other replica: synchronous
return console.log(`${label} at ${side}: OK in ${2 + RTT} ms`);
}
apply(replicas[side], w); // AP: write locally, answer right away
if (cut) pending.push({ to: other(side), w });
else apply(replicas[other(side)], w); // async replication catches up
console.log(`${label} at ${side}: OK in 2 ms${cut ? `, ${other(side)} doesn't know yet` : ""}`);
}
function buy(side, name) {
clock += 1000;
const owner = replicas[side].seatA12;
if (owner) return console.log(`${name} buys A12 at ${side}: 409, already owned by ${owner.name}`);
write(side, { kind: "seat", name }, `${name} buys A12`);
}
function like(side) {
clock += 1000;
write(side, { kind: "like", origin: side, value: replicas[side].likes[side] + 1 }, "like +1");
}
function network(on) {
clock += 1000;
cut = !on;
if (cut) return console.log("network down");
console.log(`network back: sending ${pending.length} pending writes`);
const a = replicas.kul.seatA12;
const b = replicas.sgp.seatA12;
if (a && b && a.name !== b.name) console.log(`A12 conflict: ${a.name} vs ${b.name}, ${a.t > b.t ? a.name : b.name} wins`);
for (const { to, w } of pending.splice(0)) apply(replicas[to], w);
console.log(`kul and sgp match again: A12 ${replicas.kul.seatA12?.name ?? "free"}, likes ${totalLikes(replicas.kul)}`);
}
network(false);
buy("kul", "Budi");
buy("sgp", "Siti");
like("kul");
like("sgp");
network(true);
The output:
network down
Budi buys A12 at kul: OK in 2 ms, sgp doesn't know yet
Siti buys A12 at sgp: OK in 2 ms, kul doesn't know yet
like +1 at kul: OK in 2 ms, sgp doesn't know yet
like +1 at sgp: OK in 2 ms, kul doesn't know yet
network back: sending 4 pending writes
A12 conflict: Budi vs Siti, Siti wins
kul and sgp match again: A12 Siti, likes 1202
MODEdecides the choice. Change it to"CP", and all four writes during the cut are answered503.pendingholds the AP writes that haven't reached the other replica. They are all sent innetwork(true).likeskeeps a count per origin (kul,sgp), andapplytakes the larger value per origin. That's a G-Counter: additions from the two sides don't overwrite each other.seatA12uses last-writer-wins: the write with the largertwins, and the loser vanishes without an error.
The "pick 2 of 3" myth
The CAP triangle makes people think there are three packages: CP, AP or CA. CA means consistent and always answering, but not partition tolerant. That's only possible when no network can be cut, which means a single server, and that isn't a distributed system. "Partitions don't happen inside one cloud region" is wrong too: switches, cables and configuration still fail. The real choice is only CP or AP, and it only applies during a partition.
PACELC: a price even when the network is healthy
PACELC completes CAP: if there's a Partition, choose A or C; Else (healthy network), choose Latency or Consistency. In the TicketTune model: CP waits for the other replica on every write, so a write takes 2 + 20 = 22 ms. AP answers in 2 ms, but the Singapore replica only receives the write about 10 ms later, and a read there before that gets old data. So consistency is paid for every day, not only when the network goes down. Compare sync and async in the Replication & HA lesson (Database track).
Example systems
- CP: etcd, ZooKeeper, HBase. Used for configuration, locks and leader election, where a wrong answer is more dangerous than no answer (the Consensus Algorithms lesson).
- AP: Cassandra, DynamoDB (with eventually consistent reads, its default), CouchDB. They keep answering during a partition, and the data catches up.
- Many databases are tunable. Cassandra with
QUORUMand MongoDB withmajoritylean towards CP. So what you really pick is the behaviour per operation, not the database brand.
🤔 Between strong and eventual
There are levels in between: read-your-writes (you always see your own writes), monotonic reads (you never see data older than what you've already seen), and causal consistency (a reply never shows up before the message it replies to). Example: after Budi taps "like", he himself must see 1,201 right away, even if others may see 1,200 for a few more milliseconds.
⚠️ Getting CAP wrong
- Treating CA as an option. In a distributed system, partitions will happen. The choice is CP or AP.
- One choice for the whole app. Seats and payments CP, likes and feeds AP, in the same app.
- AP with no reconciliation plan. Last-writer-wins quietly throws writes away. Work out first which data can be merged (counters) and which needs a business rule (refunds).
- Forgetting the latency side. CP pays the round trip between replicas on every write, even when the network is healthy.
TL;DR: CAP: during a network partition, a distributed system must choose between consistency (every read sees the latest write, or an error) and availability (every request is answered, even with old data). The popular wording is "it can only guarantee 2 of the 3 (C, A, P) at once", but P is not optional, so CA is not a real option: the choice is CP or AP. CP refuses writes when the other replica is unreachable (TicketTune: 503 after 500 ms), right for seats, payments, balances and locks (etcd, ZooKeeper, HBase). AP keeps accepting; the data differs for a while and is then reconciled (eventual consistency), right for likes, feeds and carts (Cassandra, DynamoDB): counters can be merged (G-Counter: 1,202), a seat sold twice needs a refund. PACELC: even with a healthy network there's a choice between latency and consistency (CP 22 ms, AP 2 ms with a lagging replica).
⚡ The network splits: choose C or A
Meaning: Consistency: every read gets the latest write, or an error. Availability: every request still gets an answer, even if the data may be old. Partition tolerance is not a choice, because networks do go down. So the only choice is CP or AP.
⚡ CP refuses, AP accepts
Guess first: the network between kul and sgp is down, in AP mode. Budi buys A12 in Kuala Lumpur, Siti buys A12 in Singapore. Once the network is back, whose is A12?
Siti's, because her write came later (last-writer-wins). Budi's purchase silently disappears, so Budi has to be refunded.
Meaning: Seats and payments choose CP: better to refuse for a while (503) than to sell one seat to two people.
⚡ Counters can be merged
Write:
if (w.kind === "like") r.likes[w.origin] = Math.max(r.likes[w.origin], w.value);
Meaning: Each replica keeps a like count per origin, and a merge takes the larger value per origin. That's a G-Counter: likes from the two sides don't overwrite each other, and the total is 1,202.
⚡ AP means eventual consistency
Meaning: AP systems such as Cassandra and DynamoDB keep answering during a partition, but the data may not be the same on every node yet, and is reconciled later. Even a healthy network has a price (PACELC): CP writes in 22 ms, AP in 2 ms with a replica that lags behind.