CAP & PACELC
- State the CAP theorem precisely and correct the most common misreadings of it
- Use PACELC to reason about the latency-vs-consistency trade-off that exists even when the network is healthy
- Classify real systems (etcd, ZooKeeper, Spanner, Cassandra, DynamoDB, PostgreSQL) and explain why "CP" and "AP" labels are only approximations
- Decide, per operation, what a bank ledger and a product catalog should give up during a partition
TL;DR
- CAP: if data is replicated and the network partitions, every replica that keeps answering requests risks returning stale or divergent data. You must choose, during the partition, between refusing some requests (consistency) and answering them (availability). It is not "pick any two of three".
- The C in CAP is linearizability (single-copy, real-time-ordered behavior), not the C in ACID. The A means every non-failing node returns a non-error response — much stronger than "the service is up".
- Partitions are a fact of life, so "CA" is not a real option for a distributed system. The choice is made per operation, not per database.
- PACELC: if Partition, choose Availability or Consistency; Else, choose Latency or Consistency. Most of your design time is spent in the "else" half, because every synchronous replica you wait for costs a round trip.
- etcd, ZooKeeper (for writes), Spanner and CockroachDB lean PC/EC. Cassandra and Dynamo-style stores default to PA/EL with tunable knobs. DynamoDB uses a leader per partition with eventually consistent reads by default and opt-in strongly consistent reads.
- A ledger picks consistency for balance-affecting writes and softens it with bounded-risk fallbacks; a catalog picks availability and low latency and re-validates at checkout.
Why it matters
Picture a bank running two data centers, DC-A and DC-B, with the account database replicated between them. The inter-DC link fails. A customer with a $1,000 balance withdraws $800 at an ATM routed to DC-A while a $700 card payment hits DC-B. If both sides keep accepting debits, the bank has just granted an unapproved $500 overdraft — and nothing in either data center was "wrong" locally. If both sides refuse all debits, the customer is stranded at the ATM and the merchant loses the sale.
Neither outcome is free, and the real answer is a policy: who is allowed to write which account while the link is down, and what risk the bank accepts. Card networks have long done exactly this with stand-in processing: when the issuer cannot be reached, the network approves low-value transactions within pre-agreed limits and reconciles later. That is a deliberate, bounded "AP" choice for a narrow operation inside an otherwise "CP" system.
For e-commerce, the same partition looks different. A product page showing a price that is two minutes stale is fine; a product page that returns 503 during a sale is lost revenue. But the price you charge and the stock you decrement at checkout need stronger guarantees.
Interviewers use CAP as a probe. Answers like "we pick CA" or "NoSQL is AP, so it scales" signal memorized slogans. A strong answer talks about which operations tolerate staleness, what happens on the minority side of a partition, and what latency you pay for consistency when there is no partition at all.
Core concepts
CAP, stated precisely
Brewer presented CAP as a conjecture in 2000; Gilbert and Lynch formalized and proved it in 2002 with these definitions:
- Consistency — the system is linearizable: every operation appears to take effect atomically at a single point between its start and its completion, so once a write completes, every later read (in real time) sees it or something newer.
- Availability — every request received by a non-failing node eventually gets a non-error response. There is no time bound, but "try again later" does not count.
- Partition tolerance — the system keeps its guarantees even if the network drops arbitrarily many messages between nodes.
The proof is almost trivial, which is the point. Two replicas hold x. The network between them drops all messages. A client writes x = 1 to N1. Another client reads x from N2.
N2 cannot know about the write. It either answers (and may be stale) or it does not answer (and is unavailable). That is the whole theorem.
Common misreadings
- "Pick any two of three." Partition tolerance is not a feature you opt out of. A "CA" system is one that assumes partitions never happen — in practice, a single-node database, or a cluster that behaves unpredictably when they do.
- "CAP consistency = ACID consistency." ACID's C is "transactions preserve application invariants". CAP's C is linearizability of a single register. Transaction isolation (serializability) is a different axis again — see Consistency Models and Transactions & Isolation Levels.
- "Database X is CP / AP." Most real systems are neither in the strict sense. PostgreSQL with asynchronous read replicas is not linearizable even with a healthy network (replica reads are stale), and it is not CAP-available either (clients cut off from the primary cannot write). Martin Kleppmann's essay "Please stop calling databases CP or AP" makes this argument at length. Many systems also let you pick per request (Cassandra consistency levels, DynamoDB
ConsistentRead). - "AP means always up; CP means often down." CP systems keep serving on the majority side of a partition, and partitions are rare. Google describes Spanner as technically CP but with availability high enough that users can treat it as if it were CA. Conversely, an AP system does nothing for a client that cannot reach any node.
- "CAP tells me about latency." It does not. CAP only covers the partitioned case and only one register. Slow nodes, partial partitions and multi-object transactions are outside its scope. That gap is what PACELC fills.
What a partition looks like from inside
A partition is rarely a cleanly cut cable. It is a 30-second stop-the-world GC pause, a saturated top-of-rack switch, a firewall rule pushed to half the fleet, or an asymmetric link where node A can send to B but not receive. From a node's perspective, a dead peer, a slow peer and a partitioned peer look identical: a request that has not come back yet. The only partition detector is a timeout. So "choosing C or A" really means deciding what your code does when a replication or quorum call times out: fail the client request, or serve what you have locally.
PACELC
Daniel Abadi (2010 blog post, 2012 IEEE Computer article) pointed out that the more frequent trade-off is the one CAP ignores:
If there is a Partition, trade Availability against Consistency; Else, trade Latency against Consistency.
The "else" trade-off exists because consistency requires coordination. A linearizable write must reach a leader and a quorum of replicas before it is acknowledged; a linearizable read must confirm it is talking to the current leader or read from a quorum. Every coordination step costs at least one network round trip — inside a data center that is sub-millisecond, but between regions it is tens of milliseconds (rough: ≈ 30–80 ms between nearby regions, well over 100 ms across oceans).
Classifying real systems
Treat the labels below as default behavior, not identity. Most of these systems can be configured toward the other side.
| System | During a partition | Without a partition | Rough PACELC | Notes |
|---|---|---|---|---|
| etcd | Minority side cannot elect a leader; writes and linearizable reads fail there | Writes go through Raft leader + majority; reads linearizable by default | PC/EC | serializable reads are served locally and may be stale (an EL option) |
| ZooKeeper | Minority side stops serving writes | Writes via leader + quorum (ZAB); reads served by the local server and may lag | PC/EC for writes, EL for reads | Call sync before a read when you need the latest value |
| Spanner | Paxos groups need a majority; minority replicas cannot commit | Synchronous Paxos replication, TrueTime commit wait | PC/EC | Stale reads at a past timestamp are cheap (EL option) |
| CockroachDB | Each range needs its Raft majority | Raft per range; serializable transactions | PC/EC | Follower reads trade freshness for latency |
| Cassandra | Any reachable replica can accept writes at consistency ONE | Async replication; latency-first defaults | PA/EL | QUORUM / LOCAL_QUORUM tighten it; lightweight transactions use Paxos (SERIAL) |
| DynamoDB (single region) | Leader per partition; a replica cut off from the leader cannot accept writes | Eventually consistent reads (default) may hit any replica | PC/EL by default, PC/EC with ConsistentRead | Global tables historically replicate asynchronously across regions with last-writer-wins; check current docs for newer multi-region strong-consistency options |
| PostgreSQL + async replicas | Primary keeps accepting writes; failover may lose recent commits | Replica reads are stale | Doesn't fit cleanly | Sync replication moves it toward PC/EC at a latency cost |
Note DynamoDB in particular: despite the name, it is not the leaderless Dynamo design from the 2007 paper. The 2022 USENIX ATC paper describes a leader replica per partition elected with Multi-Paxos. The Dynamo paper's leaderless, sloppy-quorum design lives on in Cassandra and Riak — see Replication.
The choice is per operation, not per system
Inside one product, different operations want different answers:
Amazon's original Dynamo paper is the classic example of the AP end: the shopping cart accepts writes on any replica and merges divergent versions, accepting that a deleted item may occasionally reappear. That is a fine trade for a cart and a terrible one for a balance.
Bank ledger vs product catalog
Ledger (see Double-Entry Ledger Design):
- Invariants are hard: no double spending, balance never below the overdraft limit, debits equal credits.
- Debits choose consistency. On the minority side of a partition, debits are refused or queued as "pending", never silently applied.
- Soften the impact without breaking invariants:
- Home region per account. Each account has exactly one writable home. A partition only hurts accounts whose home is on the other side, and there is never more than one writer.
- Accept commutative, invariant-safe operations. Incoming credits cannot push a balance below zero, so they can be accepted and applied later.
- Bounded stand-in. Approve small debits up to a per-account offline limit, record them as provisional, and reconcile. The bank explicitly accepts at most
limit × accountsof exposure.
- Balance reads for display can be AP if labelled ("balance as of 10:42"). The authorization decision cannot.
Catalog (see Product Catalog & Search):
- Staleness of seconds to minutes is acceptable for descriptions, images, even list prices.
- Choose availability and latency: CDN, caches, read replicas, multi-region active-active with last-writer-wins for merchandiser edits.
- Protect the invariant at the boundary: checkout re-reads the authoritative price and stock and stores a price snapshot on the order (see Cart & Checkout).
Trade-offs
| Option | Strengths | Weaknesses | Choose when |
|---|---|---|---|
| CP: minority side refuses | Invariants hold; no reconciliation of conflicting writes | Some users get errors during partitions; needs ≥ 3 failure domains for a majority | Debits, transfers, inventory decrement, unique allocations |
| AP: serve and reconcile | Always answers; low latency; survives region loss | Stale reads, conflicting writes, merge logic, possible user-visible anomalies | Catalog, reviews, carts, feeds, analytics counters |
| Bounded AP (stand-in limits) | Keeps the business running with capped, known exposure | Needs reconciliation, limits, fraud review; complex to explain | Card authorizations, low-value offline payments, loyalty points |
| EC: sync quorum everywhere | Linearizable reads and writes; simple reasoning | Every write pays a quorum round trip; cross-region adds tens of ms | Ledgers, metadata stores, lock and config services |
| EL: async replicas and local reads | Fast reads and writes, cheap to scale reads | Replication lag anomalies; data loss window on failover | Read-heavy, staleness-tolerant views; reporting |
In practice
Knobs you will actually turn:
- Cassandra: consistency level per query —
ONE,LOCAL_QUORUM,QUORUM,EACH_QUORUM,ALL, plusSERIAL/LOCAL_SERIALfor lightweight transactions.LOCAL_QUORUMon both reads and writes is a common middle ground for multi-DC deployments. - DynamoDB:
ConsistentRead: trueonGetItem/Queryreads from the leader. A strongly consistent read consumes twice the read capacity of an eventually consistent one. - etcd: reads are linearizable by default;
etcdctl get --consistency=sgives a serializable (local, possibly stale) read. - ZooKeeper: reads are local to the connected server; issue
syncbefore a read that must be current. - PostgreSQL:
synchronous_commitandsynchronous_standby_namesdecide whether a commit waits for replicas (see Replication).
Three failure domains, not two. A two-data-center deployment cannot form a majority after a clean split: each side has half. Put a third, lightweight voter (a witness or arbiter node) in a third site or availability zone so that one side can keep a majority.
Making the choice explicit in code. The difference between AP and CP behavior usually lives in what your service does on timeout:
// Catalog: availability first. Serve a stale copy and say so.
func (s *CatalogService) GetProduct(ctx context.Context, id string) (Product, error) {
ctx, cancel := context.WithTimeout(ctx, 80*time.Millisecond)
defer cancel()
p, err := s.store.Get(ctx, id)
if err == nil {
s.cache.Set(id, p)
return p, nil
}
if cached, ok := s.cache.Get(id); ok {
cached.Stale = true // the UI can show "prices may have changed"
return cached, nil
}
return Product{}, fmt.Errorf("get product %s: %w", id, err)
}
// Ledger: consistency first. Never guess a balance.
func (s *LedgerService) Debit(ctx context.Context, req DebitRequest) error {
err := s.store.DebitIfSufficient(ctx, req) // quorum write, conditional on balance
switch {
case err == nil:
return nil
case errors.Is(err, context.DeadlineExceeded), errors.Is(err, ErrNoQuorum):
// Outcome may be unknown: the client must retry with the SAME idempotency key.
return ErrRetryLater // mapped to 503 + Retry-After
default:
return err
}
}
The CP path depends on idempotency: a timed-out debit may have committed, and the only safe client behavior is to retry with the same key.
Common pitfalls
- One label for the whole system. "We use Cassandra, so we're AP" — and then the payment capture path silently runs at consistency
ONE. Symptom: rare double captures or lost updates that only show up in reconciliation. - Calling a system CP because the primary database is. Reads from async replicas after a write violate read-your-writes. Symptom: customers see the old balance after a transfer, retry, and create duplicates.
- Two-site quorums. A 2+2 cluster or two-DC etcd loses quorum on any clean split. Symptom: a network blip between DCs takes the whole service down — the worst of both worlds.
- Last-writer-wins on balances. Multi-region active-active with LWW drops one of two concurrent updates. Symptom: money "disappears" with no error logged anywhere.
- Ignoring the client. A CP service that times out still leaves the client unsure whether the write happened. Without idempotency keys, "unavailable" turns into "duplicate".
- Never testing partitions. Behavior on the minority side is often discovered in production. Use fault injection (
tc,iptables, Toxiproxy, chaos tooling) and read Jepsen reports for the databases you depend on.
Interview angle
- Typical prompt: "Our wallet runs in two regions. The link between them goes down. What happens?" A strong answer: per-operation analysis; home region per account so there is a single writer; debits refused or queued on the non-home side; credits accepted and applied later; optional bounded stand-in limits; idempotency keys on every money-moving call; reconciliation after the partition heals; a third site for quorum.
- Expect follow-ups: "How do you make balance reads fast for users far from the home region?" (follower or stale reads with an "as of" timestamp, read-your-writes via version tokens). "What does the node actually observe during a partition?" (timeouts). "What's the latency cost of synchronous cross-region replication?" (one inter-region round trip per commit, at minimum).
- Mention PACELC unprompted when discussing replication: it shows you know the everyday trade-off is latency, not partitions.
- Red flags: "CAP says pick two", "we'll choose CA", "eventual consistency is fine for balances because it converges", or classifying a system without saying which operation and which configuration.
Self-check
1. State the three CAP properties precisely. Which one is most often misdefined, and how?
Consistency is linearizability: operations appear atomic and real-time ordered. Availability is that every request to a non-failing node gets a non-error response. Partition tolerance is continuing to uphold guarantees despite arbitrary message loss. Consistency is the most often misdefined — people conflate it with ACID consistency (invariants) or with serializability (transaction isolation), neither of which is what CAP proves anything about.
2. Why is "CA" not a meaningful choice for a system spanning multiple machines?
Because you cannot prevent the network from dropping or delaying messages; you can only decide how to behave when it does. A "CA" design simply has no defined behavior during a partition, which in practice means it violates either C or A unpredictably. Only a single-node system can honestly claim CA.
3. What does PACELC add that CAP misses, and why does it matter more in day-to-day design?
It adds the trade-off in the normal, non-partitioned case: to be consistent, writes and reads must coordinate with a leader or quorum, which costs latency. Partitions are rare; latency is paid on every request. So decisions like synchronous vs asynchronous replication, leader vs follower reads, and cross-region placement are PACELC "else" decisions.
4. Is PostgreSQL with one async read replica CP or AP? Defend your answer.
Neither, strictly. Reads from the replica are stale even without a partition, so it is not linearizable. Clients partitioned from the primary cannot write, so it is not CAP-available. During a primary–replica partition, the primary keeps accepting writes, and a failover then loses those commits. The useful answer is to describe the behavior of each operation, not to pick a label.
5. Scenario: a wallet's two regions lose connectivity. Design the behavior for debits, credits and balance display.
Assign each account a home region that is the only writer. Debits on the home side proceed normally; on the other side they are refused with a retryable error or queued as pending (or approved within a small, provisional stand-in limit). Credits are accepted on either side and forwarded when the link heals, because they cannot break the "balance ≥ limit" invariant. Balance display can be served from a local replica with an "as of" timestamp. After healing, reconcile provisional items and replay queued requests idempotently.
6. Why should a two-data-center deployment usually include a third site?
Majority quorums need more than half of the voters. With two sites, a clean split leaves each side with exactly half, so neither can make progress and a CP system becomes fully unavailable. A small witness or arbiter in a third failure domain lets one side retain a majority.
7. DynamoDB and Cassandra are both often called "AP". What is wrong with grouping them?
Cassandra is leaderless: any replica can accept a write, and consistency is tuned with quorum levels. DynamoDB has a leader replica per partition elected via Paxos; writes go through the leader, and only reads are eventually consistent by default (strongly consistent reads hit the leader). Their partition behavior and anomalies differ, so a single label hides the important part.
Exercise
Take the checkout flow of an e-commerce platform and list at least eight operations: view product, view price, add to cart, apply voucher, reserve stock, authorize payment, confirm order, send confirmation email.
For each operation, fill in a table with:
- The invariant at risk if data is stale or divergent.
- Behavior during a partition: CP, AP, or bounded AP — and exactly what the user sees.
- Behavior without a partition: latency-first or consistency-first, and the concrete mechanism (cache, follower read, quorum write, leader read).
- How you reconcile afterwards, if at all.
Optional experiment: run a three-node etcd cluster with Docker Compose, disconnect one node (docker network disconnect), and compare etcdctl put and etcdctl get --consistency=l vs --consistency=s on the isolated node and on the majority side.
Done when: the table has a defensible answer for every row, at least one row uses bounded AP with a stated exposure limit, and (if you ran the experiment) you can explain each command's result in CAP terms.
Further reading
- Eric Brewer, "Towards Robust Distributed Systems" — PODC 2000 keynote that introduced the conjecture.
- Seth Gilbert & Nancy Lynch, "Brewer's Conjecture and the Feasibility of Consistent, Available, Partition-Tolerant Web Services" (2002).
- Eric Brewer, "CAP Twelve Years Later: How the 'Rules' Have Changed" — IEEE Computer, 2012.
- Daniel Abadi, "Consistency Tradeoffs in Modern Distributed Database System Design" — IEEE Computer, 2012 (PACELC).
- Martin Kleppmann, "Please stop calling databases CP or AP" — blog post, 2015.
- Eric Brewer, "Spanner, TrueTime and the CAP Theorem" — Google, 2017.
- Martin Kleppmann, Designing Data-Intensive Applications, ch. 9.
- DeCandia et al., "Dynamo: Amazon's Highly Available Key-value Store" — SOSP 2007.
- Elhemali et al., "Amazon DynamoDB: A Scalable, Predictably Performant, and Fully Managed NoSQL Database Service" — USENIX ATC 2022.
Related
- Consistency Models — the spectrum between linearizable and eventual, and session guarantees.
- Replication — the mechanisms that create these trade-offs.
- Consensus & Raft — how CP systems keep a single, majority-agreed history.
- Double-Entry Ledger Design — the invariants a ledger must protect.
- High Availability & Disaster Recovery — multi-site topologies and failover.
- Database Replication & Sharding — the system-design view of the same choices.
Do the self-check first. Marking it complete schedules spaced reviews (1, 3, 7, 14, 30… days).