System Design · 03. Data & Storage · 10 min · Intermediate

CAP & Consistency

When the network splits, a database must choose between answering and being right.

In short

Networks split, so every replicated system answers one question in advance: when the copies cannot talk, do we refuse (CP) or answer with what we have (AP)?

In normal times the same trade-off shows up as time: 92 ms for strong writes against 2 ms for eventual ones. Pick it per feature: strong for balances and locks, eventual for feeds and counters.

Key ideas

  • Every replicated database has the same job: keep the copies equal, even when machines and networks fail. (step 1)
  • When the link is fine, you can have both. CAP only forces a choice during a partition. (step 3)
  • You do not need strong consistency for everyone. You need it for what each user, or each action, depends on. (step 8)
  • Dynamo-style stores usually pick availability and latency; Spanner-style stores pick consistency in both cases. (step 9)

Good to know

  • Use CP when a wrong answer is worse than no answer: money, locks, leader election. etcd, ZooKeeper and Spanner behave this way. (step 4)
  • Use AP when being up matters more than being exact: shopping carts, likes, feeds. DNS, Cassandra and DynamoDB lean this way (both databases can be tuned). (step 5)
  • Most large systems read from nearby copies and accept a small delay. The gap is usually milliseconds, not hours. (step 7)

Watch out

  • Partitions are not rare events you can design away. Any network between machines can split, so you must decide what to do when it does. (step 2)
  • The farther apart the replicas, the slower every write. Light in fibre cannot be sped up. (step 6)
Alice (EU)Replica EUbalance 150Replica USbalance 150Bob (US)

Key numbers

Stale reads
your choice
Write time
2 ms to 92 ms

Terms

Network partition
A failure where machines are running but some cannot reach each other over the network.
CAP theorem
During a partition a system can keep either consistency or availability, not both.
Consistency (CAP)
Every read returns the latest write or an error.
Availability (CAP)
Every request to a working node gets an answer.
CP system
A system that returns errors on the side without a majority, so it never returns old data.
AP system
A system that keeps answering on both sides of a partition and merges the copies later.
Strong consistency
After a write completes, every later read anywhere sees it, as if there were one copy.
Eventual consistency
Copies may differ for a short time but become equal when no new writes arrive.
Read-your-writes
After you save a change, your own reads always show it.
Monotonic reads
A user never sees newer data followed by older data.
PACELC
If partitioned choose availability or consistency; else choose latency or consistency.