CAP, PACELC & Consistency

System Design · Distributed Systems · Intermediate · 18 min

Explain CAP with a real partition, use PACELC for the everyday latency trade-off, pick a consistency level, and reason with quorums (R + W > N).

Two bank branches connected by one phone line. The line goes dead. A customer walks into each branch to withdraw from the same account. Each branch must choose: refuse until the line is back, or pay out and risk overdrawing.

The idea in everyday words

Three friends keep copies of the same shopping list. When they can all text each other, the lists stay in sync. If one friend's phone dies (a partition) and someone asks her 'do we need milk?', she can either say 'I can't be sure, ask later' (consistent, not available) or answer from her old list (available, maybe wrong). She cannot do both.

CAP with a concrete partition story

You run a database on 3 replicas (copies) in 3 places. A network partition happens: a cable or router fails and replica C can no longer talk to A and B. All three machines are still running.

  • C = Consistency: every read returns the latest successful write (like there is only one copy).
  • A = Availability: every request to a working replica gets a (non-error) answer.
  • P = Partition tolerance: the system keeps working while messages between replicas are lost.

Key idea: partitions are not optional in a distributed system, so CAP really asks: during a partition, do you give up C or A?

A client on C's side asks for the balance:

  • CP choice: C refuses ("can't confirm the latest value"). Correct, but that client gets an error.
  • AP choice: C answers from its own copy. The client gets an answer, but it may be stale, and if C also accepts writes the two sides diverge and must be merged later.

Banks, stock counts, seat booking and "username taken?" lean CP. Shopping carts, likes, view counts and feeds lean AP.

PACELC: the trade-off you pay every day

Partitions are rare. CAP says nothing about the other 99.9% of the time. PACELC fills the gap:

If there is a Partition, choose A or C. Else (normal operation), choose Latency or Consistency.

Why latency? To be consistent, a write must wait for other replicas to confirm, and a read may need to ask several replicas. Waiting = latency. Skipping the wait = faster, but readers can see old data for a moment.

System (roughly) Partition Else
DynamoDB, default eventually consistent reads A L (fast, may be stale)
DynamoDB with ConsistentRead=True C for that read C (pays a bit more latency and read capacity)
Aurora: writer + read replicas in one Region C on the writer replicas lag slightly, reading from them is the L choice
Raft / Paxos clusters (etcd, ZooKeeper) C C

Read it as a menu, not a label. Most AWS databases let you choose per request or per endpoint.

Consistency levels in plain words

Level Promise Real-life example
Strong (linearizable) every read sees the latest write bank balance after a transfer
Read-your-writes you always see your own writes you edit your profile and immediately see the change
Monotonic reads you never see time go backwards a comment doesn't vanish on refresh
Eventual if writes stop, all replicas converge like counts catching up after a few seconds

Replication lag = how far a replica is behind the leader. It is the cause of most "my update disappeared" bugs.

How to get read-your-writes on AWS without paying for strong reads everywhere:

  • Right after a user writes, read from the writer endpoint (Aurora) or with ConsistentRead=True (DynamoDB).
  • For everyone else (other users browsing), read from replicas or use eventually consistent reads.
import boto3
t = boto3.resource("dynamodb").Table("Accounts")
t.get_item(Key={"pk": "ACC#7"})                       # eventually consistent (default)
t.get_item(Key={"pk": "ACC#7"}, ConsistentRead=True)  # strongly consistent

Strongly consistent reads work on the base table and LSIs, not on GSIs.

Quorums: R + W > N

Keep N copies. A write succeeds after W replicas confirm. A read asks R replicas and takes the reply with the highest version.

Key idea: if R + W > N, every read set overlaps every write set in at least one replica, so a read always meets the latest write.

Tiny example, N = 3, W = 2, R = 2. A write lands on {A, B}. Any 2 replicas you read include A or B. Try it: {A, C}, {B, C}, {A, B} all contain the new version.

N W R R + W > N? Feel
3 2 2 yes balanced, survives 1 slow/down node
3 3 1 yes fast reads, writes stall if any node is down
3 1 1 no fastest, eventual consistency
5 3 3 yes survives 2 nodes down

Aurora uses this idea in its storage layer: 6 copies across 3 Availability Zones, a write quorum of 4 and a read quorum of 3 (4 + 3 > 6), so it keeps writing even if a whole AZ (2 copies) is lost.

DynamoDB replicates each item across 3 AZs inside a Region. Global tables replicate across Regions; by default that is eventually consistent with last-writer-wins for conflicts, and AWS also offers a multi-Region strong consistency option (check the docs for its limits and Regions).

Other clouds: GCP Spanner (externally consistent), Firestore; Azure Cosmos DB offers five named consistency levels; open source Cassandra exposes tunable R/W (ONE, QUORUM, ALL).

Step by step

  1. Setup:

    N = 3 replicas A, B, C all hold x = 1 (version 1). Quorum config W = 2, R = 2.

  2. Write:

    Client 1 writes x = 2. A and B store version 2 and ack. 2 acks = W, so the write succeeds. C has not received it yet.

  3. Quorum read:

    Client 2 reads with R = 2 and happens to ask B and C. Replies: B v2 (x = 2), C v1 (x = 1). Highest version wins → x = 2. Correct, thanks to the overlap.

  4. Partition:

    The network cuts C off. Client 2 can only reach C. 1 reply < R = 2 → CP system returns an error instead of x = 1.

  5. AP alternative:

    With R = 1, C would answer x = 1 immediately: available but stale. If C also accepted a write x = 9, A/B and C now disagree.

  6. Heal:

    When the network returns, CP just copies v2 to C. AP must reconcile 2 vs 9, e.g. last writer wins, which silently drops one write.

Code example

from itertools import combinations

# N = 3 replicas. A write of version 2 reached the first W replicas only.
def stale_reads(N, W, R):
    replicas = [2] * W + [1] * (N - W)          # versions held
    stale = 0
    sets = list(combinations(range(N), R))
    for read_set in sets:
        newest = max(replicas[i] for i in read_set)
        if newest != 2:
            stale += 1
    return stale, len(sets)

for N, W, R in [(3, 2, 2), (3, 1, 1), (3, 3, 1), (5, 3, 3), (5, 2, 2)]:
    s, total = stale_reads(N, W, R)
    ok = "R+W>N" if R + W > N else "R+W<=N"
    print(f"N={N} W={W} R={R} {ok:7} stale reads: {s}/{total}")

Interview tips

  • Tell CAP as a story: 'the link between AZ-a and AZ-b breaks; a client in AZ-b asks for the balance; we either refuse or answer stale'.

  • Don't claim 'CA'. Say: 'partitions happen, so during one we choose; normally we trade latency vs consistency (PACELC)'.

  • Mix levels per feature: strong reads for checkout and balances, eventual reads for catalog browsing.

  • Quorums: N = 3, W = 2, R = 2 survives one node down for both reads and writes. Aurora's 4-of-6 write / 3-of-6 read is a great real example.

  • For multi-Region on AWS: DynamoDB global tables (last writer wins by default, a strong-consistency option exists), Aurora Global Database (one writer Region, read replicas elsewhere).

Challenge: Quorum Read

Write quorum_read(replicas, r).

replicas is a list in the order you contact them. Each entry is either {"version": int, "value": str} or null / None (unreachable).

  • Read from the first r reachable replicas (skip nulls, ignore everything after you have r replies).
  • If fewer than r replicas are reachable, return "UNAVAILABLE".
  • Otherwise return the value with the highest version among those r replies (on a tie, the first one seen).

Example: quorum_read([None, {"version": 1, "value": "a"}, {"version": 2, "value": "b"}], 2) → "b"

Solve it in the browser with tests, hints and an AI coach.

Practice problems

More in Distributed Systems

Previous: Consistent Hashing · Next: Replication, Failover & Sharding