Module 3 · Database designLesson 32 of 887 minAdvanced

The CAP theorem

When the network splits a distributed database, it must choose between giving correct answers and giving any answer at all.

Try it

Cut the network with "Stay consistent" and watch Node C refuse writes. Heal, switch to "Stay available", cut again, then heal and see whose writes get overwritten.

The CAP theorem is about databases that keep copies on several machines. It names three properties:

  • Consistency (C): every read sees the latest write, as if there were one copy.
  • Availability (A): every request to a working node gets an answer.
  • Partition tolerance (P): the system keeps running even when the network between nodes breaks.

The famous summary is "pick two", but that's misleading. In a real network, partitions will happen; you can't opt out of P. So the real question is:

When the network splits, do you stay consistent or stay available?

CP: refuse rather than be wrong

Nodes that can't reach a majority stop accepting writes (and sometimes reads). Users on that side see errors, but nobody ever sees conflicting data.

Good for: money, inventory, locks, anything where two different truths would be a disaster. Examples: etcd, ZooKeeper, Spanner, most SQL setups with synchronous failover.

AP: answer now, fix later

Every node keeps accepting requests. The sides drift apart, and when the network heals they reconcile: last write wins, merge the changes, or ask the app to decide.

Good for: shopping carts, likes, social feeds, sensor data. Examples: Cassandra, DynamoDB (in its default mode), Riak.

Beyond CAP: PACELC

CAP only talks about partitions, which are rare. PACELC adds: Else, when everything is fine, you still trade Latency against Consistency. Waiting for replicas in other regions makes every write slower, even on a good day. Most real design choices are about that everyday trade-off.

Quick check

A shopping cart service should keep accepting "add to cart" even during network problems, and merge carts later. Which side of CAP is that?