CAP and PACELC applied to real databases
A worked example: state CAP precisely, add the latency trade-off with PACELC, then place real configurations of PostgreSQL, Cassandra, DynamoDB and etcd per operation, including a run of PostgreSQL synchronous replication with an unreachable standby, and write the guarantee sheet.
Contentsand lesson path
On this page
- The problem
- Step 1: State CAP precisely
- Step 2: Add the else branch with PACELC
- Step 3: PostgreSQL with a synchronous standby
- Step 4: Cassandra consistency levels across two datacentres
- Step 5: DynamoDB and etcd choose per request too
- Step 6: The guarantee sheet
- Check your understanding
- Apply it
- Review prompt
Lessons of Distributed Systems Fundamentals
- Partial failure and the fallacies of distributed computing Concept · 20 min
- Time, clocks and ordering Concept · 20 min
- Consistency models from linearizable to eventual Concept · 25 min
- CAP and PACELC applied to real databases Worked example · 20 min
- Quorums, Raft and leader leases, step by step Lab · 25 min
- Distributed reasoning check Knowledge check · 8 questions
What you will learn
- Place a design on the consistency spectrum (linearizable, sequential, causal, read-your-writes, eventual) and explain the trade-offs with CAP and PACELC.
01. The problem
A ticketing company runs four stores. PostgreSQL holds orders, with one synchronous standby in a second zone. Cassandra holds the activity feed, with three replicas in each of two datacentres. DynamoDB holds user preferences. etcd holds feature flags and elects the leader of a job scheduler. An architect is asked: "Which of these are CP and which are AP?"
That question has no useful answer, because CAP does not describe products. Your task in this worked example is to replace it with a guarantee sheet: for each important operation, the consistency model it gets with the configured settings, what a client gets during a network partition, what the stronger setting costs in normal operation, and one anomaly a user could see. Every claim must point to a setting and to the documentation.
02. Step 1: State CAP precisely
Start from the theorem, because the popular slogan "pick two of three" is not what Gilbert and Lynch proved in 2002. Their setting is a single read/write object replicated over an asynchronous network that may lose any number of messages. Consistency means atomic, that is linearizable, operations (lesson 3). Availability means every request received by a non-failing node eventually gets a response. The theorem: no system can guarantee both while the network is partitioned.
Four consequences shape the rest of the example:
- CAP is a choice made during a partition, per operation. When the network is healthy it says nothing.
- Partitions are not optional, so "CA" is not a real option for a replicated system.
- CAP availability is strict. Martin Kleppmann points out that a single-leader database is not CAP-available, since a client cut off from the leader cannot write, and that it is not CAP-consistent either once reads go to asynchronous followers. Many real systems are neither, and are still useful.
- CAP says nothing about latency: a system that answers after two minutes counts as available.
03. Step 2: Add the else branch with PACELC
Daniel Abadi argued in 2012 that the trade-off designers face every day is not the rare partition but latency. His PACELC reads: if there is a Partition, choose Availability or Consistency; Else, choose Latency or Consistency. Any system that replicates synchronously makes the client wait for another machine; any system that answers from one replica risks returning stale data.
Even Abadi labelled the default versions of Dynamo, Cassandra and Riak as PA/EL and noted that their settings move them. So the sheet will place each configured operation on four letters, never a product.
04. Step 3: PostgreSQL with a synchronous standby
When synchronous_standby_names names a standby, each commit waits for that standby's confirmation; Leaders, read replicas, sync versus async replication and failover explains the synchronous_commit levels. To see the partition case, start PostgreSQL 18 in Docker and name a standby that never connects. To the primary, an unreachable standby and an absent one look the same: no confirmation arrives.
docker run -d --name pgsync -e POSTGRES_PASSWORD=lab postgres:18
until docker exec pgsync pg_isready -U postgres -h 127.0.0.1; do sleep 1; done
docker exec -i pgsync psql -U postgres -v ON_ERROR_STOP=1 <<'SQL'
CREATE TABLE bookings (seat text PRIMARY KEY, guest text);
INSERT INTO bookings VALUES ('1A', 'Asha');
ALTER SYSTEM SET synchronous_standby_names = 'standby1';
SELECT pg_reload_conf();
SQLCREATE TABLE
INSERT 0 1
ALTER SYSTEM
pg_reload_conf
----------------
t
(1 row)docker exec pgsync psql -U postgres -c "INSERT INTO bookings VALUES ('2B', 'Bruno')"docker exec pgsync psql -U postgres -c 'SELECT * FROM bookings'
docker exec pgsync psql -U postgres -c "SELECT pid, state, wait_event, query
FROM pg_stat_activity WHERE wait_event = 'SyncRep'"
docker exec pgsync psql -U postgres -c "SELECT pg_cancel_backend(pid)
FROM pg_stat_activity WHERE wait_event = 'SyncRep'" seat | guest
------+-------
1A | Asha
(1 row)
pid | state | wait_event | query
-----+--------+------------+---------------------------------------------
117 | active | SyncRep | INSERT INTO bookings VALUES ('2B', 'Bruno')
(1 row)
pg_cancel_backend
-------------------
t
(1 row)WARNING: canceling wait for synchronous replication due to user request
DETAIL: The transaction has already committed locally, but might not have been
replicated to the standby.
INSERT 0 1docker exec pgsync psql -U postgres -c 'SELECT * FROM bookings'
docker exec pgsync psql -U postgres -c 'SET synchronous_commit = local' \
-c "INSERT INTO bookings VALUES ('3C', 'Chen')"
docker rm -f -v pgsync # clean up when you are done seat | guest
------+-------
1A | Asha
2B | Bruno
(2 rows)
SET
INSERT 0 1While the standby was unreachable, the write on the primary waited (wait event SyncRep) and other sessions could not see the row. That is the PC choice for this write: no answer rather than an answer the standby lacks. Cancelling ended the wait, but the transaction had already committed locally: the client got INSERT 0 1 with a warning, and the row became visible. If the primary had then failed over to the standby, Bruno's booking would be gone. This is lesson 1's unknown outcome again, now inside a database. In our run, statement_timeout did not end this wait; a cancel request did.
The setting can change per transaction. With synchronous_commit = local, the next insert committed at once: that transaction chose availability and latency (PA/EL) and accepted losing the write if the primary dies before the standby catches up. In normal operation every synchronous commit waits at least one round trip to the standby, so the default here is PC/EC for commits. The PostgreSQL documentation recommends naming more potential standbys, for example ANY 1 (s1, s2), so that one unreachable standby does not stop every write.
05. Step 4: Cassandra consistency levels across two datacentres
Cassandra lets each request choose a consistency level: how many replica answers the coordinator waits for. The documentation notes that writes are always sent to every replica; the level only decides when the client hears back. The script applies the documented level definitions to the feed: three replicas in each of two datacentres, a client in dc1, the link between the datacentres cut, and round-trip times that are assumptions for this scenario.
"""Cassandra-style consistency levels with 3 replicas in each of 2 datacentres.
For a client in dc1: how many replica answers each level waits for, whether
it still works when the link to dc2 is cut, and the round-trip floor it pays
in normal operation. RTTs are scenario assumptions, not measurements.
"""
RF = {"dc1": 3, "dc2": 3}
RTT_MS = {"dc1": 1, "dc2": 80} # seen from a coordinator in dc1
TOTAL = sum(RF.values())
def needs(level: str) -> dict:
"""Answers required per datacentre ('any' = from anywhere)."""
local_quorum = RF["dc1"] // 2 + 1
return {
"ONE": {"any": 1},
"LOCAL_ONE": {"dc1": 1},
"LOCAL_QUORUM": {"dc1": local_quorum},
"QUORUM": {"any": TOTAL // 2 + 1},
"EACH_QUORUM": {dc: n // 2 + 1 for dc, n in RF.items()},
"ALL": {"any": TOTAL},
}[level]
def works(need: dict, reachable: dict) -> bool:
if "any" in need:
return sum(reachable.values()) >= need["any"]
return all(reachable[dc] >= n for dc, n in need.items())
def rtt_floor(need: dict) -> int:
rtts = sorted(RTT_MS[dc] for dc, n in RF.items() for _ in range(n))
if "any" in need:
return rtts[need["any"] - 1]
return max(RTT_MS[dc] for dc in need)
split = {"dc1": 3, "dc2": 0} # dc1 still sees only its own replicas
print(f"{'level':13} {'answers':>7} {'works in split':>15} {'RTT floor':>10}")
for level in ["ONE", "LOCAL_ONE", "LOCAL_QUORUM", "QUORUM", "EACH_QUORUM", "ALL"]:
need = needs(level)
count = need.get("any") or sum(need.values())
ok = "yes" if works(need, split) else "NO"
print(f"{level:13} {count:>7} {ok:>15} {rtt_floor(need):>7} ms")
print("\nDoes every read set overlap every write set? (any datacentre)")
for w, r in [("QUORUM", "QUORUM"), ("LOCAL_QUORUM", "LOCAL_QUORUM"),
("ALL", "ONE"), ("ONE", "ONE")]:
nw = needs(w).get("any") or sum(needs(w).values())
nr = needs(r).get("any") or sum(needs(r).values())
local = w.startswith("LOCAL") or r.startswith("LOCAL")
verdict = "only inside one DC" if local else ("yes" if nw + nr > TOTAL else "no")
print(f" write {w:12} + read {r:12}: {nw}+{nr} of {TOTAL} -> {verdict}")level answers works in split RTT floor
ONE 1 yes 1 ms
LOCAL_ONE 1 yes 1 ms
LOCAL_QUORUM 2 yes 1 ms
QUORUM 4 NO 80 ms
EACH_QUORUM 4 NO 80 ms
ALL 6 NO 80 ms
Does every read set overlap every write set? (any datacentre)
write QUORUM + read QUORUM : 4+4 of 6 -> yes
write LOCAL_QUORUM + read LOCAL_QUORUM: 2+2 of 6 -> only inside one DC
write ALL + read ONE : 6+1 of 6 -> yes
write ONE + read ONE : 1+1 of 6 -> noWith LOCAL_QUORUM for reads and writes, each datacentre keeps working during the split and waits only on local replicas: PA/EL. The documentation describes the guarantee as reads seeing the latest write from within the same datacentre. A user whose traffic moves to dc2 may see an older feed, and concurrent writes in both datacentres are settled by last-write-wins timestamps from lesson 2.
QUORUM needs 4 of the 6 replicas. Each side of this split has only 3, so QUORUM fails in both datacentres, and in normal operation every request waits for a remote reply: PC/EC. Overlapping quorums make acknowledged writes visible to later quorum reads in the documentation's terms, but they are not a proof of linearizability (Multi-leader and leaderless quorums lists the gaps); for a compare-and-set, Cassandra offers lightweight transactions on a single partition.
06. Step 5: DynamoDB and etcd choose per request too
DynamoDB. Reads are eventually consistent by default: they might not reflect a write that just completed, and they cost half as much as strongly consistent reads. Setting ConsistentRead to true on GetItem, Query or Scan returns data reflecting all prior successful writes, but only for tables and local secondary indexes; global secondary indexes and streams are always eventually consistent. Global tables default to multi-Region eventual consistency (MREC), replicating typically within a second, and offer multi-Region strong consistency (MRSC). The read-consistency page does not describe partition behaviour in CAP terms, so the sheet says so instead of guessing.
etcd. Key-value operations are strictly serializable by default and pass through Raft consensus, which needs a majority of members (lesson 5). A member cut off from the majority cannot complete them: PC, and EC because each one waits for consensus. A read with --consistency=s (serializable) is answered from the member's local copy and may be stale. We checked this with etcd 3.7.4, three members on one machine and two of them stopped: a default etcdctl get failed with context deadline exceeded, while the serializable get returned the stored value. That one option turns the read into PA/EL.
07. Step 6: The guarantee sheet
Put the findings in one place, one line per operation:
- PostgreSQL, order insert, default commit: durable on the standby when acknowledged; during a primary–standby partition, commits wait (PC); each commit pays a round trip to the standby (EC). Anomaly: a cancelled commit is kept locally and can vanish on failover.
- PostgreSQL, read on an asynchronous replica: may be stale; keeps answering when cut off (PA/EL). Anomaly: a user misses their own new order.
- Cassandra feed, LOCAL_QUORUM: latest write within one datacentre; both sides keep working (PA/EL). Anomaly: older feed after moving to dc2; concurrent edits lose one by timestamp.
- DynamoDB preference read: eventual by default (stale reads possible, half the cost);
ConsistentReadfor tables and local indexes, never on global indexes. - etcd flag read: linearizable by default (PC/EC);
--consistency=sanswers when cut off but may be stale.
08. Check your understanding
09. Apply it
Finish the guarantee sheet for your three stores in the format of Step 6: for each main operation, the setting, the consistency model, the behaviour on each side of a partition, the latency cost of the stronger setting, and one anomaly a user could see. Cite the documentation page for every line. Then pick one line and say which setting you would change, and what you would give up.
10. Review prompt
Without looking back:
- State the CAP theorem with its definitions of consistency, availability and partition.
- Why is "CA" not an option, and why is a single-leader database often neither CP nor AP?
- What does the else branch of PACELC add, and why does it apply even without failures?
- Place PostgreSQL synchronous commit, Cassandra LOCAL_QUORUM and an etcd serializable read on PACELC.
- What happened to the cancelled INSERT in Step 3, and why does it matter for failover?
References
- Brewer's Conjecture and the Feasibility of Consistent, Available, Partition-Tolerant Web Services (Gilbert and Lynch, 2002)
- Consistency Tradeoffs in Modern Distributed Database System Design (Abadi, PACELC)
- Please stop calling databases CP or AP (Martin Kleppmann, 2015)
- PostgreSQL documentation: Synchronous Replication
- PostgreSQL documentation: synchronous_commit
- Apache Cassandra documentation: Dynamo (tunable consistency)
- Amazon DynamoDB Developer Guide: read consistency
- etcd documentation: API guarantees
- etcdctl README: consistency option
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.