AlgoViz

The CAP theorem

medium 28 min

When the network between copies of your data breaks, each copy must either refuse some requests or risk answers that disagree.

Video lesson · Chapter 1 of 5

The isolated desk cannot verify the price

0:00 / 3:40

CAP in 75 seconds

1:15Reel coming soon

Theory

Read or listen first. About 2 min.

What it is

A distributed data store keeps copies of the same data on several machines. The CAP theorem is about the moment when those machines cannot talk to each other. At that moment a machine that receives a request has only two options: answer from what it knows, or refuse until it can check.

The three letters are consistency (every read sees the latest completed write, as if there were one copy), availability (every request to a working node gets a real answer) and partition tolerance (the system goes on although messages between nodes are lost). During a partition you cannot keep both of the first two.

Why it exists

The theorem saves a team from chasing the impossible. If a product owner asks for data that is never stale, always answers and runs in two cities, you can show that one of the wishes must give way when the link fails, and ask which.

It is often told as "pick two of three". That misleads. Cables, switches and overloaded machines break whether you pick them or not, so partition tolerance is not optional for data on several machines. The real question is what each operation does while the network is split.

A short history

  1. 1999

    Armando Fox and Eric Brewer publish the CAP principle in a paper about scalable internet services.

  2. 2000

    Brewer presents it as a conjecture in a keynote at the PODC conference.

  3. 2002

    Seth Gilbert and Nancy Lynch of MIT publish a formal proof, with consistency defined as linearizability.

  4. 2010

    Daniel Abadi describes PACELC: else, when there is no partition, the trade-off is latency against consistency. The paper follows in 2012.

  5. 2012

    Brewer writes "CAP Twelve Years Later" and says that the two-of-three wording was always misleading.

Words to know

Replica
One of several copies of the same data.
Network partition
Some nodes cannot exchange messages with others, although all of them run.
Linearizability
The system behaves like one copy on which every operation happens at one instant.
Quorum
The number of nodes that must answer. A majority of N is the whole part of N / 2, plus 1.
CP
During a partition, refuse rather than risk a wrong answer.
AP
During a partition, answer rather than refuse.
Conflict
Two sides accepted different writes to the same item.
PACELC
If Partition then A or C, Else Latency or Consistency.

How it works

Step through the idea, or press Play.

Step 1 of 3

Keep several copies. So that one machine can fail

Understand it

Start here

Two islands and one guest book

Picture two small islands that share one guest book. Each island keeps a copy, and a raft pulled along a cable carries every new name to the other side. The keepers promise that both copies always say the same.

When the cable breaks
3names3names

Joining lists of names is easy. If both islands had sold the same last boat ticket, no merge could please both guests.

Another small version: three friends write one story in three notebooks. You would like the same story in all of them (consistency), everybody able to write at any time (availability), and all that even when one friend cannot reach the others (partition tolerance). While that friend is out of reach, one of the first two wishes has to wait.

C

Consistency means one copy

In CAP, consistency is linearizability: once a write has finished, every later read, from any client and any node, returns that value or a newer one. It is not the C of ACID, which is about rules inside one database.

Consistent

  • Client A: write x = 1, answer OK
  • Client B: read x, gets 1
  • Client C: read x, gets 1

Not consistent

  • Client A: write x = 1, answer OK
  • Client B: read x, gets 1
  • Client C: read x, gets 0, which is stale

How a majority write works

Replicate, wait for a majority, then acknowledge. The slowest replica does not hold the client up.

Majority

q=⌊N2⌋+1N=3:;q=2N=5:;q=3failures survived=N−qq = \left\lfloor \tfrac{N}{2} \right\rfloor + 1 \qquad N=3:; q=2 \qquad N=5:; q=3 \qquad \text{failures survived} = N - q
Any two majorities share at least one node, so two sides of a partition can never both have one. Four nodes survive one failure, just like three.

A

Availability means every working node answers

A request that reaches a node that has not failed must get a real answer. It need not contain the latest write, but "try later" does not count. This is a yes or no property of the algorithm, not a percentage.

Available during the split

  • Request 1: answered
  • Request 2: answered, perhaps stale
  • Request 3: answered, perhaps stale

Not available during the split

  • Request 1: answered by the majority side
  • Request 2: times out on the minority side
  • Request 3: gets an error on the minority side

The other availability: percentages of a year

TargetDowntime in a year of 365 days
99%3.65 days
99.9%8.76 hours
99.99%52.6 minutes
99.999%5.26 minutes
A CP system can reach 99.99% if partitions are short and the majority side keeps serving. An AP system can miss it for plain old bugs. More in resilience.

P

Partitions are not optional

One network split

Side A holds node 1 and node 2, which replicate to each other. Side B holds node 3 alone. The link between the sides is down. Clients on side A reach node 1 and clients on side B reach node 3.
All three nodes are healthy. Side A has a majority of 2 out of 3. Side B cannot tell whether the others crashed or only cannot be heard.
  • Networks fail

    Switches break, cables are cut, a wrong rule blocks a port.

  • Pauses look the same

    A node stopped for 20 seconds by garbage collection is silent, like a node behind a broken link.

  • Clouds have bad days

    Zones and regions lose contact now and then. Your design should say what happens.

  • You cannot choose CA

    With one machine there is nothing to split. With two, the split can happen whether you like it or not.

What does this node do?

The same system can take different branches for different requests.

Proof

Why both is impossible

  1. 1

    Two nodes, one value

    Both hold x = 0. The link between them is cut.

  2. 2

    A write arrives on the left

    To be available, the left node must accept x = 1 without telling the right.

  3. 3

    A read arrives on the right

    To be available, the right node must answer. It has heard nothing, so it says 0.

  4. 4

    Contradiction

    The write finished before the read began, so a consistent read must say 1. With both promises kept, the answer is both 0 and 1.

Notice what the proof uses: the right node sees exactly the same messages whether or not the left one accepted a write, namely none. No cleverness can help it.

CP

Refuse on the minority side

A CP system keeps working where a majority is and stops where it is not. With three nodes and node 3 cut off, writes through nodes 1 and 2 succeed with 2 of 3 votes. Clients that can only reach node 3 get errors until the link is back, and then node 3 catches up.

Which refusals are worth it?

UseWhy wrong is worse than nothing
Moving money between accountsSpending the same balance twice
Stock and seatsSelling the last one twice
Locks and coordinationTwo holders at once
Leader electionTwo leaders, called split brain

AP

Answer everywhere, repair later

An AP system accepts reads and writes on every side. The price comes at healing time: both sides may have changed the same item, and something must decide. Common rules are last write wins (simple, but loses one write), keeping both versions for the application to merge, and data types built to merge (CRDTs).

Which disagreements can you live with?

UseWhy an answer matters moreRepair
Social feedA post a few seconds late is fineLater sync
Shopping cartA refused click loses a saleJoin both carts
Metrics and logsGaps are worse than duplicatesDeduplicate by id
Content deliveryAn old picture beats an error pageExpiry time

Both sides accept

Normal days

PACELC: the other half

Partitions are rare. On every other day the choice is latency or consistency: a fresh answer needs a round trip to other replicas, a local answer does not. Abadi's PACELC puts both halves in one line: if Partitioned, A or C; Else, L or C.

PACELC in one picture

What a fresh answer costs

Tlocal≈1 msTmajority≈1+RTTsecond nearest=1+70=71 msT_{\text{local}} \approx 1\text{ ms} \qquad T_{\text{majority}} \approx 1 + \mathrm{RTT}_{\text{second nearest}} = 1 + 70 = 71\text{ ms}
Assumption: three replicas in three regions, with round trips of 70 and 140 ms from here. A majority of 3 needs one other replica, the nearest. A single region with round trips of 1 ms makes the price almost invisible.

PACELC labels, for a given configuration

LabelIn a partitionOtherwiseTypical shape
PC/ECRefuseWait for agreementConsensus stores such as etcd
PA/ELAnswerAnswer at onceDynamo style with small quorums
PA/ECAnswerWait for agreementLeader plus failover that may lose the last writes
PC/ELRefuseAnswer at onceA fixed leader per item with local reads

Real systems

Labels depend on settings

What the documents say

SystemLeansUnder which settings
etcdCPLinearizable by default; serializable reads are local and may be stale
ZooKeeperCPLinearizable writes; reads come from the connected server unless you sync first
HBaseCPIts documents promise strongly consistent reads and writes
MongoDBCP for majority operationsDefault write concern is majority; linearizable reads must be asked for
CassandraAP, tunableThe level is chosen for each query: ONE to ALL
DynamoDBMixedEventually consistent reads by default, strong reads on request in one region
CouchDBAPAccepts writes on any node and replicates; conflicts are kept
Riak KVAPKeeps answering; offers mergeable data types
DNSAPCached answers may be old until they expire
Redis with WAITNot CPIts own page says WAIT does not make Redis strongly consistent
Strictly, many of these are neither C nor A in the theorem's sense. Say what a chosen operation does, not what a brand is.

One shop, two choices

A shop. The product pages read from any replica and go on during a partition. The checkout service talks to the majority side of an order store and stops if it has no majority.
Browsing keeps answering with data that may be old. Paying needs a majority and refuses without one.

Do it well

Working rules

Do

  • Choose from the business need
  • Use majorities and consensus where wrong is expensive
  • Design the merge before choosing AP
  • Watch the replication lag
  • Cut the network in tests

Do not

  • Assume the network is reliable
  • Ignore what users expect to see
  • Mix both behaviours without saying which is where
  • Forget the healing step
  • Treat CAP as one switch for the whole product

Summary

The whole topic in one minute.

CAP is a statement about a broken network: a replica that cannot reach the others must either refuse or answer without knowing whether the answer is up to date. Consistency here means linearizability, and availability means that every working node answers every request.

Choose for each operation, not once for the whole company. Refuse where a wrong answer costs more than no answer, such as a lock or the last seat. Accept and merge later where an answer matters more, such as a shopping cart. In normal times, ask the other half of the question: how much latency is the fresh answer worth?

  • CAP speaks about the time when replicas cannot talk.
  • C is linearizability, A is an answer from every working node.
  • P is not a choice, so decide between refusing and answering.
  • A majority exists on at most one side of a split.
  • AP needs a merge rule; CP needs a plan for the refused users.
  • Without a partition the trade is latency against consistency.

Sources