Database CAP Theorem and PACELC
What you will learn
- The three words in CAP: consistency, availability, partition tolerance
- What the theorem actually says, and the common "pick two of three" mistake
- How a CP and an AP choice behave during a partition
- What PACELC adds for the times when nothing is broken
All code in this lesson is a simulation that imitates an idea. It is not a real database. You can run the block on its own.
1. The three words
The CAP theorem talks about a data system whose copies live on several machines (lessons 14.1 and 14.2). Its three words have precise meanings:
| Word | Meaning here |
|---|---|
| Consistency | every read returns the latest completed write, as if there were one copy (the strong model of lesson 14.4; it is not the "valid state" meaning of ACID) |
| Availability | every request to a machine that is working gets an answer, not an error or a timeout |
| Partition tolerance | the system keeps working when the network between machines fails or delays messages, so that some machines cannot reach others |
A network partition is exactly that failure: the machines are running, but a group of them cannot talk to another group.
2. What the theorem says
CAP is often summarised as "pick two out of three". That summary is misleading. The more careful statement is:
If a network partition happens, a system must choose between consistency and availability. It cannot give both during the partition.
Why? Suppose machines A and B hold copies and the link between them is cut. A client writes to A. If the system stays available, B keeps answering reads from its old copy, so a reader of B sees stale data: consistency is lost. If the system stays consistent, it must refuse to answer (or refuse the write) until A and B can talk again: availability is lost.
Partitions on real networks cannot be ruled out, so "partition tolerance" is not really an option you can drop. The real choice appears only while a partition lasts. When the network is healthy, a system can offer both consistency and availability.
3. A CP and an AP choice, in a simulation
The simulation has two nodes holding one value. Two write rules are compared. A CP rule keeps consistency and refuses a write it cannot confirm with the other node. An AP rule keeps availability and accepts the write on whichever node the client reached:
class Node:
def __init__(self, name):
self.name = name
self.value = "v1"
a, b = Node("A"), Node("B")
partitioned = False # True means A and B cannot talk to each other
def write_cp(node, other, value):
"""Consistency first: refuse the write if the other node cannot confirm it."""
if partitioned:
return "REFUSED (cannot reach the other node)"
node.value = other.value = value
return "ok"
def write_ap(node, other, value):
"""Availability first: accept the write on this node even if the other cannot be reached."""
node.value = value
if not partitioned:
other.value = value
return "ok"
print("No partition:")
print(" CP write on A:", write_cp(a, b, "v2"), "| A =", a.value, "B =", b.value)
print(" AP write on A:", write_ap(a, b, "v3"), "| A =", a.value, "B =", b.value)
partitioned = True
print("\nPartition (A and B cannot talk):")
print(" CP write on A:", write_cp(a, b, "v4"), "| A =", a.value, "B =", b.value)
print(" AP write on A:", write_ap(a, b, "v5"), "| A =", a.value, "B =", b.value)
print(" a client reading from B now sees:", b.value, "(stale, but B still answers)")
print(" AP write on B:", write_ap(b, a, "v6"), "| A =", a.value, "B =", b.value)
print(" -> the two nodes now disagree and must be reconciled after the partition heals")
No partition:
CP write on A: ok | A = v2 B = v2
AP write on A: ok | A = v3 B = v3
Partition (A and B cannot talk):
CP write on A: REFUSED (cannot reach the other node) | A = v3 B = v3
AP write on A: ok | A = v5 B = v3
a client reading from B now sees: v3 (stale, but B still answers)
AP write on B: ok | A = v5 B = v6
-> the two nodes now disagree and must be reconciled after the partition heals
The same two rules in SQL. This lesson runs on the sample database you chose in lesson 4.1 (use the Example data picker at the top). The nodes table has the two copies, and the net table says whether the network is cut. A CP write only goes ahead when the network is healthy; an AP write is applied to the node the client reached, and to the other node only if the network is healthy. The tables are small ones of their own; Reset data removes them.
CREATE TABLE nodes (name TEXT PRIMARY KEY, value TEXT);
CREATE TABLE net (partitioned INTEGER);
INSERT INTO nodes VALUES ('A', 'v1'), ('B', 'v1');
INSERT INTO net VALUES (0);
UPDATE nodes SET value = 'v2' WHERE (SELECT partitioned FROM net) = 0;
UPDATE nodes SET value = 'v3' WHERE name = 'A' OR (name = 'B' AND (SELECT partitioned FROM net) = 0);
SELECT name, value FROM nodes ORDER BY name;
name value
---- -----
A v3
B v3
(2 rows)
Now cut the network. A CP write changes nothing (the client gets an error, here "0 rows changed"):
UPDATE net SET partitioned = 1;
UPDATE nodes SET value = 'v4' WHERE (SELECT partitioned FROM net) = 0;
(0 rows changed)
An AP write on A is accepted, but B keeps its old value, and B can still be read (stale):
UPDATE nodes SET value = 'v5' WHERE name = 'A' OR (name = 'B' AND (SELECT partitioned FROM net) = 0);
SELECT name, value FROM nodes ORDER BY name;
name value
---- -----
A v5
B v3
(2 rows)
Then a client writes to B as well, and the two nodes disagree:
UPDATE nodes SET value = 'v6' WHERE name = 'B' OR (name = 'A' AND (SELECT partitioned FROM net) = 0);
SELECT name, value FROM nodes ORDER BY name;
name value
---- -----
A v5
B v6
(2 rows)
CREATE TABLE nodes (name TEXT PRIMARY KEY, value TEXT);
CREATE TABLE net (partitioned INTEGER);
INSERT INTO nodes VALUES ('A', 'v1'), ('B', 'v1');
INSERT INTO net VALUES (0);
UPDATE nodes SET value = 'v2' WHERE (SELECT partitioned FROM net) = 0;
UPDATE nodes SET value = 'v3' WHERE name = 'A' OR (name = 'B' AND (SELECT partitioned FROM net) = 0);
SELECT name, value FROM nodes ORDER BY name;
name value
---- -----
A v3
B v3
(2 rows)
Now cut the network. A CP write changes nothing (the client gets an error, here "0 rows changed"):
UPDATE net SET partitioned = 1;
UPDATE nodes SET value = 'v4' WHERE (SELECT partitioned FROM net) = 0;
(0 rows changed)
An AP write on A is accepted, but B keeps its old value, and B can still be read (stale):
UPDATE nodes SET value = 'v5' WHERE name = 'A' OR (name = 'B' AND (SELECT partitioned FROM net) = 0);
SELECT name, value FROM nodes ORDER BY name;
name value
---- -----
A v5
B v3
(2 rows)
Then a client writes to B as well, and the two nodes disagree:
UPDATE nodes SET value = 'v6' WHERE name = 'B' OR (name = 'A' AND (SELECT partitioned FROM net) = 0);
SELECT name, value FROM nodes ORDER BY name;
name value
---- -----
A v5
B v6
(2 rows)
CREATE TABLE nodes (name TEXT PRIMARY KEY, value TEXT);
CREATE TABLE net (partitioned INTEGER);
INSERT INTO nodes VALUES ('A', 'v1'), ('B', 'v1');
INSERT INTO net VALUES (0);
UPDATE nodes SET value = 'v2' WHERE (SELECT partitioned FROM net) = 0;
UPDATE nodes SET value = 'v3' WHERE name = 'A' OR (name = 'B' AND (SELECT partitioned FROM net) = 0);
SELECT name, value FROM nodes ORDER BY name;
name value
---- -----
A v3
B v3
(2 rows)
Now cut the network. A CP write changes nothing (the client gets an error, here "0 rows changed"):
UPDATE net SET partitioned = 1;
UPDATE nodes SET value = 'v4' WHERE (SELECT partitioned FROM net) = 0;
(0 rows changed)
An AP write on A is accepted, but B keeps its old value, and B can still be read (stale):
UPDATE nodes SET value = 'v5' WHERE name = 'A' OR (name = 'B' AND (SELECT partitioned FROM net) = 0);
SELECT name, value FROM nodes ORDER BY name;
name value
---- -----
A v5
B v3
(2 rows)
Then a client writes to B as well, and the two nodes disagree:
UPDATE nodes SET value = 'v6' WHERE name = 'B' OR (name = 'A' AND (SELECT partitioned FROM net) = 0);
SELECT name, value FROM nodes ORDER BY name;
name value
---- -----
A v5
B v6
(2 rows)
The nodes now hold different values and must be reconciled after the partition heals.
Read the output:
- Without a partition, both rules work and both nodes agree (
A = v3, B = v3). - During the partition, the CP rule says
REFUSED: nothing is lost or inconsistent, but the client gets an error, so the system was not available. - The AP rule accepts the write:
A = v5, whileBstill hasv3. A reader ofBgets an old answer (stale), but gets an answer. When a client then writesv6onB, both sides have accepted different writes, so the nodes disagree. After the partition heals, the system must reconcile the two versions (for example by "last write wins", or by asking the application, as in lesson 14.2). Some updates may be lost or merged.
Neither choice is "better". A bank balance would usually choose consistency. A shopping cart or a "like" count would often choose availability, because refusing the customer costs more than a short disagreement.
Quick check: is a single-machine database (no copies) affected by CAP?
Not in the same way: with one copy there is nothing that can disagree, and no network between copies to partition. CAP is about systems with copies on several machines.
4. Common misunderstandings
- "Pick any two." You do not pick "CA" for a distributed system, because partitions happen. A system that appears to give both is usually one that fails completely during a partition.
- "AP means no consistency ever." Most AP systems are consistent when the network is healthy, and may offer stronger guarantees for some operations.
- "CP means always down." A CP system refuses only the requests it cannot answer safely, usually on the side of the partition that cannot reach enough machines (lesson 14.7).
- Labels for products. Calling a whole product "CP" or "AP" is a simplification: many systems let you pick per operation (for example the quorum settings in lesson 14.4). This lesson names no products because it does not verify any product's behaviour.
5. PACELC: the rest of the time
CAP says nothing about normal operation, yet even without a partition there is a trade-off. Keeping copies strongly consistent means waiting for the other machines to confirm a write, which takes time. An extension of CAP called PACELC captures this. Read it as a sentence:
If there is a Partition, choose between Availability and Consistency; Else (no partition), choose between Latency and Consistency.
| Situation | The choice |
|---|---|
| Partition | availability or consistency (this is CAP) |
| Normal | low latency (answer from the nearest copy, possibly stale) or consistency (wait for confirmation, slower) |
So the replication settings of lesson 14.2 (synchronous or asynchronous) and the quorum settings of lesson 14.4 are the "else" half of this rule: you pay latency to buy consistency.
Worked example: choosing for two features
A made-up ticket-booking service has two features.
| Feature | During a partition | In normal operation |
|---|---|---|
| Reserving the last seat | consistency: refuse rather than sell a seat twice | accept a slower write that waits for confirmation |
| Showing "seats left" on the search page | availability: show a slightly old number | answer from the nearest copy, quickly |
The same service makes both choices, one per feature. The cost of a wrong answer decides which side to take.
Common mistakes
- Treating CAP as "choose two" for ever. The choice is about the time of a partition.
- Confusing the C of CAP with the C of ACID.
- Labelling a whole product CP or AP without reading what it guarantees for each operation.
- Forgetting normal operation. Latency versus consistency is a trade-off every day, not only during failures.
Key takeaways
- During a network partition, a replicated system must choose consistency or availability.
- Partitions cannot be ruled out on real networks, so the choice is not "any two of three".
- A CP choice refuses requests it cannot answer safely; an AP choice answers but may return stale data and need reconciling later.
- PACELC adds the normal-operation trade-off between latency and consistency.
- The right choice depends on the cost of a wrong answer, and can differ per feature.
Practice
1. State the CAP theorem in one careful sentence.
Show answer
If a network partition occurs between the copies of the data, the system cannot be both consistent (every read sees the latest write) and available (every working node answers every request); it must give up one during the partition.
2. Why is "pick two of three" misleading?
Show answer
Partitions cannot be avoided on a real network, so partition tolerance is not optional. The real choice is between consistency and availability, and only while a partition lasts.
3. In the simulation, what happened to a client that wrote to node A with the CP rule during the partition?
Show answer
The write was refused with an error, so the data stayed consistent but the system was not available to that client.
4. In the simulation, why were A and B different at the end of the AP run, and what must happen later?
Show answer
Each node accepted a different write while they could not talk. After the partition heals the system must reconcile the two versions, for example with last-write-wins or with application rules.
5. What does the "ELC" part of PACELC describe?
Show answer
When there is no partition ("else"), the trade-off between latency and consistency: waiting for copies to confirm costs time, answering from the nearest copy is fast but may be stale.
6. Give one feature that should choose consistency during a partition and one that should choose availability.
Show answer
For example: reserving the last seat or making a payment should choose consistency; showing a like count or a rough number of seats left can choose availability.