Course contents

08. Distributed Systems Lesson 2 of 10

CAP Theorem

Cut the link between two replicas and watch the forced choice: keep answering and diverge, or refuse writes and stay consistent. What CAP really says.

16 minAdvanced8 steps
Loading the interactive simulation…
Loading the knowledge check…

Summary

  • CAP: during a network partition, a replicated system must give up either linearizable consistency or availability.
  • C means linearizability (behaves like a single copy); A means every request to a non-failed node gets a non-error answer.
  • Choosing availability means both sides keep answering and diverge; conflicts must be reconciled after the partition heals.
  • Choosing consistency means nodes that cannot reach a majority refuse requests; with a majority quorum the larger side keeps working.
  • Without a partition, systems can be consistent and available; the everyday trade-off is latency (PACELC).
Deep diveHow it works, trade-offs, failure modes, misconceptions and the interview angle.

What it is

The CAP theorem says that a replicated data store cannot guarantee all three of the following at once:

  • Consistency (C): linearizability. The system behaves as if there were a single copy of the data and every operation took effect at one instant between its start and its end. Once a write has completed, every later read, by any client, sees it or something newer.
  • Availability (A): every request received by a node that has not failed eventually gets a non-error response.
  • Partition tolerance (P): the system keeps operating even if the network loses arbitrarily many messages between nodes.

Eric Brewer stated it as a conjecture in 2000; Seth Gilbert and Nancy Lynch proved a formal version in 2002. Because networks do partition, the useful reading is: when a partition happens, you must choose between C and A.

Why it exists

Replicating data across machines (for availability, durability or proximity to users) means the copies must talk to stay in sync. If they cannot talk, a node receiving a request faces a dilemma. To answer, it must use only what it knows locally, which may miss writes accepted on the other side: inconsistent. To stay consistent, it must wait for or refuse the request: unavailable. CAP turns that intuition into a theorem and kills the idea that clever engineering can avoid the choice.

How it works

The proof in one paragraph. Take two nodes, G1 and G2, holding a value v = v0. Cut every message between them. A client writes v = v1 at G1. If the system is available, G1 must confirm the write. Then a client reads v at G2. If the system is available, G2 must answer, and it can only answer v0, since no message from G1 can reach it. A completed write was not seen by a later read: not linearizable. So no algorithm can be both available and consistent while messages are lost.

What a partition looks like from inside. Nodes cannot tell a partition from a crashed peer or a very slow network; they just stop hearing from each other. Each side typically stays healthy and reachable by its own clients, which is why partitions are dangerous: nothing looks broken locally.

Choosing availability (AP). Each side keeps serving. With single-leader async replication, followers serve stale reads. With multi-leader or leaderless replication, both sides accept writes and the copies diverge. After the partition heals the system must reconcile: last write wins (simple, silently drops a confirmed write), merge functions such as CRDTs (counters, sets, registers that merge deterministically), or storing sibling versions with version vectors for the application to resolve. Amazon’s Dynamo shopping cart is the classic example.

Choosing consistency (CP). A node that cannot confirm a write with the others refuses (or blocks). Consensus protocols such as Raft, Paxos and Zab refine this with majorities: a write commits once a majority of nodes has it, and a leader must be elected by a majority. Two disjoint majorities cannot exist, so the majority side of a partition keeps working and the minority side refuses writes and linearizable reads. With a single-node cluster or two nodes and no majority, “refuse” means everyone.

Per-operation choices. Many systems expose the choice per request: Cassandra and other Dynamo-style stores let you pick read and write consistency levels; MongoDB has read and write concerns; some systems serve linearizable reads through the leader and cheaper, possibly stale reads from followers.

When to use it

Use CAP as a reasoning tool when you design or choose a replicated store: for each operation, ask what must happen if replicas cannot talk. Operations that protect an invariant across replicas (a balance that must not go negative, a unique username, a lock) need C. Operations where a stale or merged answer is acceptable (likes, view counts, presence, a cart you can reconcile) can choose A.

When not to

CAP is a poor tool for comparing databases in normal operation. It says nothing about latency, throughput, weaker but useful consistency models (causal, read-your-writes), how often partitions happen, or what happens when a node is merely slow. Labelling a whole product “CP” or “AP” usually hides configuration choices that change the answer.

Trade-offs

Choice during a partition You keep You give up Typical mechanism
Availability (AP) Every reachable node answers Linearizability; must reconcile later Async or multi-leader replication, sloppy quorums, CRDTs
Consistency (CP) Linearizable reads and writes Availability on the minority side (or everywhere with no majority) Consensus, majority quorums, synchronous replication

Alternatives

CAP is a constraint, not a design, so the alternatives are refinements:

  • PACELC adds the normal-operation trade-off between latency and consistency.
  • Weaker consistency models (causal consistency, session guarantees) can stay available during partitions while giving stronger promises than “eventually”.
  • Harvest and yield (Fox and Brewer) frames degraded answers: answer with partial data instead of refusing.
  • Avoid the partition’s blast radius: keep strongly consistent state within one region and replicate asynchronously across regions.

Failure modes

  • Split brain. Both sides of a partition believe they are in charge and accept conflicting writes in a system that was supposed to be CP. Usually caused by failover based on timeouts without a majority or fencing.
  • Silent data loss on reconciliation. Last-write-wins discards one of two confirmed writes without an error.
  • Unavailable minority surprises. A region that ends up on the minority side of a consensus group stops accepting writes; if most users are there, the “consistent” choice can look like a full outage.
  • Stale reads mistaken for consistency. Reading from followers in a “CP” database can return stale data unless reads go through the leader or a quorum.

In production

Decide the partition behaviour per feature and write it down. Keep consensus groups at an odd size (3 or 5) and place members so one zone or region loss leaves a majority. For cross-region data, the common pattern is a strongly consistent home region per record plus asynchronous copies elsewhere. Test partitions deliberately (fault injection that drops traffic between zones) and monitor for divergence, not only for errors. If you choose AP, design the merge before the first conflict happens.

Common misconceptions

  • “Pick any two of three.” P is not optional for a distributed system; the choice is C or A during a partition.
  • “CP systems are unavailable.” Only the side without a majority, and only during a partition.
  • “AP means no consistency at all.” AP systems usually converge (eventual consistency) and can offer session guarantees.
  • “CAP consistency is ACID consistency.” Different concepts that share a word.
  • “Our database is CP, so follower reads are safe.” Consistency often depends on how you read, not only on the product.

Interview angle

State CAP precisely: during a partition, choose linearizability or availability. Then apply it per feature (“payments: CP, refuse on the minority side; feed and likes: AP, reconcile later”) and mention majority quorums (a 3- or 5-node consensus group tolerates 1 or 2 failures). Bonus points for noting that CAP ignores latency and naming PACELC, and for knowing that “CA” only describes a single-node system.

Model assumptions

The simulated steps use a simplified model, not a benchmark. Region 1 sends 50 requests per second to Node A (20% writes, over 20 keys with a Zipf 1 distribution); Region 2 sends 50 reads per second to Node B. Each node has 16 connections, 5 ms reads and 10 ms writes. A ships every write to B over a 40 ms link. Clients give up after 1 s. The partition is modelled as replication being blocked: that link delays every change by ten minutes, which is how a partition looks to replication. No link is cut and no node fails, so both regions' users still reach their local node; while partitioned, the lag shown on Node B is the last measured value, not the growing gap. “Synchronous” means A confirms a write once B has applied it (10 ms) and B's acknowledgement has travelled back over the 40 ms link; A keeps a connection busy while it waits and gives up after 1 s. A stale read is a read on B that misses a write A already confirmed. In the three-node majority step Node C (2 ms from A) joins and A confirms a write once one of its two copies has it (A plus one copy is a majority of 3); B's refusal as the minority is modelled by taking B out of service (a node failure, not a partition), so Region 2's requests are refused and A gets no acknowledgement from it; this is a configured 1-of-2 acknowledgement rule, not a consensus protocol. The engine has a single writer, so the linearizability and conflicting-writes steps are scripted illustrations; the WAN link is scenery. Numbers show behaviour and orders of magnitude only.

How to read this demonstration.

  • Actual engine simulation: asynchronous and synchronous replication between two nodes, client timeouts, stale reads on Node B, and (in the majority step) a third node with a 1-of-2 acknowledgement rule.
  • Scripted animation: the linearizability example and the both-sides-accept-writes example (traffic paused; the engine has a single writer).
  • Hybrid demonstration: the majority step: simulated nodes and metrics, with a node failure standing in for the minority side's refusal.
  • Simplified model: the partition is replication blocked by a ten-minute delay; the replica lag tile shows the last measured value, not the growing gap.
  • Time compression: slow motion (about 0.1 times real time); the ten-minute delay is longer than any step, so replication stays blocked for the whole step.
  • Not supported by the simulation: real network partitions (a cut link, two sides that cannot reach each other), a node failure presented as a partition, leader election, terms, Raft, Paxos or any consensus protocol, multi-leader conflict resolution.
The lesson as textEvery step of the simulation, written out.
  1. 1. One database, two copies, two regions

    Node A in Region 1 takes every write (and Region 1’s reads). It copies each write to Node B in Region 2, 40 ms away (the purple packets), and Region 2’s users read from B.

    Replication is *asynchronous*: A confirms a write straight away and ships it afterwards. So for a few tens of milliseconds B is behind, and a small share of Region 2’s reads miss the very latest write. Hold on to that: it is the normal, no-failure trade-off, and the subject of the PACELC lesson. This lesson is about what happens when the link breaks.

    Scene: Region 1 users read and write on Node A; A replicates each write to Node B in Region 2, whose users read from B. Everything succeeds; a small share of B’s reads are a few milliseconds behind.

    Key idea: Two copies of the data in two places, connected by a network that can fail.

  2. 2. C in CAP means linearizable

    Traffic is paused for a scripted illustration.

    The *C* in CAP is a precise promise called linearizability: the system behaves as if there were a single copy of the data. Once a write has been confirmed to anyone, every later read, from anyone, anywhere, returns that value or a newer one.

    One way to keep that promise: A writes x = 2, sends it to B, waits for B’s acknowledgement, and only then tells the user “saved”. A Region 2 user who reads afterwards gets 2 from B. The *A* in CAP is just as strict: every request to a working node gets a non-error answer.

    Scene: Scripted: a Region 1 user writes x = 2 to Node A; A replicates it to B and waits for B’s acknowledgement before confirming. A Region 2 user then reads x from B and gets 2.

    Key idea: C = linearizability (behaves like one copy). A = every request to a non-failed node gets a non-error response.

  3. 3. Replication between the regions stops

    Traffic is back, A is asynchronous again, and one second in replication between the regions stops getting through, as it would in a *network partition*. Both nodes are fine and both regions’ users can still reach their local node. How this is simulated: the engine does not cut the network. Replication from A to B is delayed by ten minutes, so no change reaches B during the step; that is what a partition does to replication, and nothing else about a partition is modelled.

    Nothing visibly breaks: no errors, latency unchanged. But B stops receiving writes, so the stale reads tile climbs: more and more Region 2 reads return data that A has long since overwritten and confirmed.

    Nobody decided anything, yet this system has already made the CAP choice: it stayed available and gave up consistency.

    Scene: One second in, replication from A to B stops getting through. Both regions keep getting answers without errors, but Node B serves increasingly stale data: the stale-read count rises.

    Key idea: A partition is not a crash: both sides are up, they just cannot talk. Async replication silently keeps serving, and diverging.

  4. 4. Availability: both sides answer, and diverge

    Traffic is paused for a scripted illustration of a fully available design, where *both* nodes accept writes (multi-leader or leaderless replication; the simulated A–B pair has a single writer).

    During the partition a Region 1 user sets x = 2 on A and a Region 2 user sets x = 3 on B. Both get “saved”. Each node tries to tell the other and the messages are lost. The two copies now disagree, and both users were told their write succeeded.

    When the partition heals, the conflict must be resolved: *last write wins* (one confirmed write silently disappears), a merge (counters, sets and other *CRDTs* merge automatically), or keeping both versions for the application to reconcile. Availability is not free; you pay at reconciliation time.

    Scene: Scripted: during the partition a Region 1 user writes x = 2 on A and a Region 2 user writes x = 3 on B. Both are confirmed; each node’s update to the other is lost at the broken link, so the copies disagree.

    Key idea: Choosing availability during a partition means accepting divergent copies and a plan to reconcile them afterwards.

  5. 5. Consistency: refuse what you cannot copy

    Back to the simulation, replication still blocked. Now A runs synchronous replication: it confirms a write only after B has it. B never receives the write, so no write can be confirmed. Clients wait and every write fails after the 1 s timeout (a real system would usually reject faster, but the effect is the same).

    In exchange, stale reads drop to zero: B never misses a write that was confirmed, because nothing is confirmed without B. Reads keep working on both sides.

    That is the whole theorem: during a partition, a node that cannot reach the others must either answer anyway (available, possibly inconsistent) or refuse (consistent, unavailable). There is no third option.

    Scene: With synchronous replication during the partition, every write waits for Node B and fails after the 1 second timeout. Reads keep succeeding and there are no stale reads.

    Key idea: CAP: when a partition happens you choose between consistency and availability. You cannot keep both.

  6. 6. With three nodes, the majority keeps going

    Refusing *everything* is the worst case of choosing C. Real consistent systems (Raft, Paxos, ZooKeeper, etcd, Spanner) run an odd number of nodes and commit once a majority has a write.

    Add Node C in Region 1, a few milliseconds from A. A still replicates synchronously to both copies, but now confirms a write as soon as one of them has it: A plus one copy is 2 of 3, a majority. C answers within a few milliseconds, so every Region 1 write is committed, even though B is cut off and never acknowledges. B, alone on its side, cannot reach a majority, so a real system would make it refuse requests it cannot answer safely. How this is simulated: the engine runs no consensus protocol (no election, no terms, no Raft). A confirms after one of its two copies acknowledged (a configured 1-of-2 rule), and B’s refusal is shown by taking B out of service, which is a node failure standing in for the minority side, not a network partition.

    So “choose C” really means: the minority side becomes unavailable; the majority side keeps working. Two majorities cannot exist at once, which is what rules out split brain.

    Scene: Simulated: a third node C joins in Region 1. Node A replicates every write to B and C and commits once C acknowledges, two of three; every Region 1 request succeeds. Node B, cut off alone, refuses every Region 2 request.

    Key idea: Consistent systems use majorities: the side of a partition with a majority stays available, the minority refuses.

  7. 7. The partition heals

    Back to two nodes, still synchronous and still partitioned, with B serving its region again. One second in, replication is unblocked (the simulated delay is removed, standing in for the link coming back). B acknowledges new writes after the trip across and back, and writes succeed again; the errors stop on their own.

    Partitions are usually short (seconds to minutes) and rare, which is why the CAP choice is about *behaviour during a fault*, not about the system’s everyday character. Most of the time, with no partition, a system can be both consistent and available; the everyday trade-off is a different one: latency.

    Scene: One second in, the blocked replication is restored. Synchronous writes succeed again and errors stop; there are still no stale reads.

    Key idea: CAP only describes behaviour during a partition. Without one, consistency and availability coexist.

  8. 8. What CAP does and does not say

    CAP (Brewer’s conjecture, proved by Gilbert and Lynch in 2002) says: if the network partitions, a replicated system must give up either linearizable consistency or availability. Partitions are not optional in real networks, so “CA” is not a real choice for a distributed system.

    What it does *not* say: that you pick two of three in general; that a “CP database” is unavailable in normal operation; or anything about latency, weaker consistency models, or how long a partition lasts. Many systems let you choose per operation. Note also the cost visible in the simulation: synchronous writes waited a full trip to Region 2 even when nothing was broken. That is PACELC, next.

    Scene: Both regions are healthy and connected; Node A replicates synchronously to Node B. Writes succeed, with a latency that includes the trip to Region 2.

    Key idea: CAP is a statement about partitions only: consistency or availability, decided per system or per operation.