TwiceToldby Develoker
ConceptsSystem designLabsCheat sheetsAbout

Develoker makes free tools for learning to build software. TwiceTold explains each idea twice, as an everyday analogy and the real thing; CloudArch lets you design cloud systems and put load on them.

About ยท Labs ยท Cheat sheets ยท Learning paths

All concepts ยท distributed systems ยท databases ยท consistency

CAP theorem

When a network split cuts replicas off from each other, a distributed database must choose between staying consistent (refuse some requests) and staying available (answer, possibly with stale data).

9 min4 animations

๐Ÿ“š Builds on๐Ÿ“š Replication and read replicas

๐Ÿ–จ๏ธ Cheat sheet

Two branches

A shop has two branches with a phone line between them. When the price list changes in one, it phones the other, so a shopper gets the same answer wherever they ask. While the line works, everything is easy: both branches are open, and both agree.

Replicas

Distributed databases keep replicas on several machines, for speed and to survive failures. Writes on one replica are copied to the others over the network. The CAP theorem talks about three properties:

  • Consistency: every read sees the latest write, as if there were one copy.
  • Availability: every request to a working node gets a (non-error) answer.
  • Partition tolerance: the system keeps working when the network loses messages between nodes.
Two branches, one price list3 steps
๐Ÿ™‹Shopper A๐ŸชNorth branch๐ŸฌSouth branch๐Ÿ™‹โ€โ™‚๏ธShopper B
Press play and watch it happen!

The line goes down

Then a storm cuts the phone line. Each branch can either close its doors to changes until the line is back, so nobody ever gets a wrong price, or stay open and accept that the two branches may disagree for a while. There's no third option: a branch can't know what it hasn't been told.

Pick one during a partition

Networks do partition, so P isn't optional. CAP says that during a partition a system must give up either C or A:

ChoiceBehaviour during a partitionExamples
CPRefuse or block requests that can't be confirmed with a majorityetcd, ZooKeeper, HBase, Spanner
APKeep answering; replicas diverge and reconcile laterCassandra, DynamoDB, Riak

Without a partition, a system can be both consistent and available.

Line down, choose consistency4 steps
๐Ÿ™‹Shopper A๐ŸชNorth branch๐ŸฌSouth branch๐Ÿ™‹โ€โ™‚๏ธShopper B
Press play and watch it happen!

Staying open

A shop that stays open has to tidy up afterwards. When the line comes back, the branches compare notes and agree on the latest price. For a while, shoppers might have seen different prices, but eventually everyone sees the same one.

Eventual consistency

AP systems promise eventual consistency: if writes stop, all replicas converge. Conflicting writes are resolved by rules such as last-write-wins (by timestamp), version vectors, or data types that merge automatically (CRDTs).

Many systems let you tune this per request. Cassandra's QUORUM reads and writes overlap on at least one replica, giving consistent results while a majority is reachable.

Line down, choose availability3 steps
๐Ÿ™‹Shopper A๐ŸชNorth branch๐ŸฌSouth branch๐Ÿ™‹โ€โ™‚๏ธShopper B
Press play and watch it happen!

When the line comes back

Staying open has a cost. Say the north branch is told the cake is ยฃ6 and, a minute later, the south branch is told ยฃ7. Neither hears the other. When the line returns, the branches find two different prices for one cake. Someone must choose.

A simple rule is "the latest time on the note wins". It is quick, but the other change is thrown away, and the shopper who asked for it is never told. A careful shop keeps both notes and asks a person to decide.

The branch that closed has its own trouble. A shopper who walks in during the storm is sent away, even though the shelves are full. And even in good weather, waiting for a call to the other branch before every answer makes every shopper wait a little longer.

What can go wrong

  • A CP system refuses writes on the minority side. A node that cannot reach a majority cannot confirm a write, so it errors or blocks. You see timeouts and "no leader" or "unavailable" errors on that side only, while the majority side works. Cassandra at QUORUM behaves this way: the coordinator throws UnavailableException when it knows too few replicas are alive, or WriteTimeoutException if they don't answer in time; in etcd the minority side is unavailable and requests to it time out. Fix: retry against the majority side, set client timeouts, and use consensus groups of 3 or 5 so a single failure keeps a majority.
  • An AP system accepts both sides, then conflicts. Both replicas acknowledge writes to the same key. After the partition heals, one must win. With last-write-wins (Cassandra, DynamoDB global tables in the default multi-Region eventual consistency mode), the later timestamp wins and the other acknowledged write is silently lost. If clocks are skewed, the "later" write may be the older one. You see a value that reverts, with no error anywhere. Fix: keep both as siblings (Riak with allow_mult) and merge in the application, detect concurrency with vector clocks, or use CRDTs that merge by design.
  • Stale reads after the partition heals. Healing is not instant: replicas catch up through repair and hinted handoff, so a read from a lagging replica returns old data. You see a client read its own write back as the old value (read-your-writes broken). Fix: write and read at QUORUM (so R + W > N), read from the primary, or pin a user's session to one replica.
  • Latency versus consistency with no partition (PACELC). Waiting for replicas costs time even on a healthy network; see the PACELC note below.
ChoiceYou gainYou pay
CP (refuse on the minority side)Every read sees the latest write; no conflictsErrors and timeouts for clients cut off from the majority
AP (answer on both sides)Always answers, even when partitionedConflicts, lost writes under LWW, stale reads
Quorums with R + W > NRead and write sets overlap, so a read sees the latest acknowledged writeEach request waits for more replicas; fewer failures tolerated
Strong versus eventual readsStrong: latest value. Eventual: faster and cheaperStrong: more latency and less availability. Eventual: stale data

With N replicas, a read of R and a write of W overlap when R + W > N. For N = 3, R = 2 and W = 2 gives overlap and survives one down replica. R = 1 and W = 1 is fast but can miss writes. Note that quorums reduce staleness but do not by themselves make a system linearizable.

Both sides accept, then a conflict4 steps
๐Ÿ™‹Shopper A๐ŸชNorth branch๐ŸฌSouth branch๐Ÿ™‹โ€โ™‚๏ธShopper B
Press play and watch it happen!
๐Ÿ”ง Going deeper

PACELC extends CAP: if there's a Partition, choose A or C; Else, choose between Latency and Consistency. Even with a healthy network, waiting for replicas to confirm costs time.

๐Ÿงฉ Quick quiz

Quick quiz! 4 questions about CAP theorem, told the same way as the story.
  1. The phone line between the two branches is cut. What choice does each branch face?
  2. While the line works, what can the two branches do?
  3. A branch stayed open during the storm. What must it do when the line comes back?
  4. Both branches stayed open. The north was told ยฃ6, the south was told ยฃ7, and the rule is that the latest time wins. What happens when the line returns?
Answer every question to check.Passing marks CAP theorem as done.
Got the hang of CAP theorem? Mark it as done, and your paths show how far youโ€™ve got.

Saved in this browser.

๐Ÿ•ธ๏ธ Distributed systems from zeroStep 3 of 7

โ† Previous on the path๐Ÿ—ณ๏ธ Consensus (Raft)Next on the path โ†’๐Ÿ“• Sharding

๐ŸŽฏ Backend interview prepStep 8 of 9

โ† Previous on the path๐Ÿ“‹ Distributed cachingNext on the path โ†’๐Ÿ“ฌ Apache Kafka