The CAP theorem
medium 28 minWhen the network between copies of your data breaks, each copy must either refuse some requests or risk answers that disagree.
See it run
Cut the network between three replicas and watch what a CP and an AP store do, then look at normal days.
Operations
CP: ask a majority
Every write needs 2 of 3 nodes. The side without them refuses.
Step 1 of 6
Normal operation
All nodes are connected and hold v1.
Step 1: Normal operation
def write(node, key, value): peers = reachable(node) if len(peers) < N // 2 + 1: raise Unavailable for p in peers: p.store(key, value) return "ok"- In a partition
- Minority refuses
- Price
- Errors for some
- AP
- answers everywhere
Two sides can never both hold a majority. That is the whole trick.
In the real world
The same the cap theorem doing real jobs. Pick one and step through it.
Two regions sell tickets for one concert. One seat is left when the link drops.
Step 1 of 4
One seat left
Both regions know it.
Step 1: One seat left
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Saying pick two of three
majorYou do not pick whether cables break. CA is not a design for several machines.
Wrongdesign = choose(["CA", "CP", "AP"])Rightif partitioned: refuse() or answer_and_repair()Counting only live nodes
criticalIf each side counts only the nodes it sees, both sides have a majority.
Wrongif acks > len(alive) / 2:Rightif acks >= total_members // 2 + 1:Last write wins on money
criticalOne of two accepted payments vanishes without an error.
Wrongbalance = max(a, b, key=timestamp)Rightbalance = start + sum(all_transfers)One letter for the whole product
minorBrowsing and paying have different needs.
WrongDATABASE_MODE = "CP"Rightread_catalog(level="local")place_order(level="majority")
Interview tips
How to explain it
- Copies that cannot talk must refuse or risk it.
- C is one copy, A is every node answers.
- Choose for each operation.
Memory trick
- C: same data everywhere.
- A: always responds.
- P: survives splits, and it is given.
Choose CP for
- Money and stock.
- Locks and leaders.
- Anything that cannot be undone.
Choose AP for
- Feeds and carts.
- Metrics and logs.
- Anything that merges.