Consistency: CAP, PACELC and consistency models

Replicas can be behind each other. Consistency is the promise a database makes about what you may read when that happens. This lesson explains the levels of that promise, what each one costs, and how to choose. CAP and PACELC are then easy to understand: they are the same trade-off seen from two sides.

One note on the word. In ACID, "consistency" means a transaction keeps the rules of the data, such as "balance is never negative". Here it means something else: does a read see the latest write? We use only the second meaning.

One more confusion. Strong consistency (linearizable) is about how recent a read of one value is. Serializable isolation (the ACID lesson) is about the order of whole transactions. Spanner offers both, which is called strict serializability.

1. The Problem: A Stale Read

Alice changes her balance from 100 to 90. The leader saves it and tells her "done" at 10 ms. At 12 ms, her phone asks a follower for the balance. The follower is 50 ms behind, so it still says 100.

Is that wrong? It depends on what the system promised. A bank must never show 100 here. A "likes" counter can. The promise is called the consistency model, and there are four levels you need.

2. The Four Levels

Level In plain words Cost Use for
Strong (linearizable) The system acts like there is one copy. Once a write is done, every later read sees it Every read or write waits for the leader or a majority. Slower, and some requests fail during failures Balances, stock, unique usernames, locks
Causal Things that depend on each other appear in order. A reply never shows up before its question Small. Track which write came after which Comments, chat threads
Read-your-writes You always see your own changes. Others may be a little behind Low. Read your own recent data from the leader Profile edits, settings, "my orders"
Eventual If writes stop, all copies end up the same. No promise how soon None. Fastest and most available Counters, feeds, caches, search indexes

Back to the stale read. Under strong, Alice's 12 ms read must return 90. Under eventual, 100 is allowed. Under read-your-writes, 100 is not allowed for Alice (she made the change), but it is fine for Bob.

Two smaller promises also appear: monotonic reads (time never goes backwards for one user) and consistent prefix (a reply never shows before its question). The replication lesson shows how to get both.

Eventual does not mean "wrong". In practice copies agree within milliseconds. It means the application must accept that a read can be briefly old. The replication lesson shows the fixes for read-your-writes. "Bounded staleness" is a useful variant of eventual: "a read is never more than 10 seconds old".

2.1 How Causal Order Works

Causal order sounds abstract, but the idea is simple. Every message carries the ID of the message it replies to. A replica that receives a reply before its parent holds the reply back until the parent arrives, then shows both. Messages that do not depend on each other can appear in any order. For a thread, a sequence number per thread does the same job. Causal consistency is the strongest level that can still answer during a network failure, which makes it a good middle choice. MongoDB offers it as causally consistent sessions.

3. What Strong Consistency Costs

To give a strong read, the system must ask the leader or a majority of replicas, not just the nearest copy. That has two costs:

  • Latency. A majority across three zones in one region adds 2 to 5 ms. A majority across continents adds 70 to 200 ms.
  • Availability. If a majority cannot be reached, requests fail. With three replicas you can lose one, not two.

Systems get strong consistency in three ways: send all reads and writes to one leader, use a consensus algorithm such as Raft so a majority agrees on every change (etcd and ZooKeeper), or use synchronized clocks to order changes across regions (Google Spanner). Quorum reads and writes (R + W > N) come close, but concurrent writes and sloppy quorums can still return stale data (see the replication lesson).

3.1 Worked Example: Distance Between Replicas Sets the Write Time

A strong write is done when a majority of replicas have saved it. The leader counts as one. So with 3 replicas it waits for 1 follower, and with 5 replicas it waits for 2. It does not wait for the slow ones. The write time is the round trip to the last follower it needs. Round trips come from the Numbers lesson: 1 to 2 ms between zones, 60 to 70 ms across the US, 70 to 100 ms across an ocean.

  • 3 replicas in three zones of one region. The leader waits for one follower 1 to 2 ms away. A write takes about 3 ms (the round trip plus saving to disk).
  • 3 replicas: leader in US East, followers in US West and Europe. The leader waits for the nearer one, US West, about 65 ms away. A write takes about 65 ms.
  • 5 replicas on three continents. The leader waits for the two nearest followers. The second one is often 100 ms or more away. A write takes about 100 ms.

The database and the code are the same. Only the distance changed, and a write is more than 20 times slower. So global systems keep strongly consistent data in one region, and replicate other data more loosely.

4. CAP: The Choice During a Network Failure

CAP describes what a distributed database must give up when its network breaks. It uses three terms:

  • Consistency (C): every read returns the latest write, or an error.
  • Availability (A): every working node answers every request, even if the answer may be old.
  • Partition tolerance (P): the system keeps running when the network between nodes breaks and messages are lost. Such a break is called a partition.

Picture two data centers that hold copies of the same data. The link between them fails. Both are alive, but they cannot talk to each other, and users keep sending requests to both. A write accepted on one side cannot reach the other. What should each side do?

flowchart TD
    P["Link between data centers breaks"] --> Q{"What does the side without a majority do?"}
    Q -- "Refuses requests" --> CP["CP: answers stay correct, some requests fail"]
    Q -- "Keeps answering" --> AP["AP: always answers, copies may disagree until healed"]
  • CP (consistent, partition-tolerant): the side that cannot reach a majority refuses requests, because it cannot be sure its data is the latest. Users get errors, but never wrong answers. Examples: ZooKeeper, etcd, Spanner. Right for balances and locks.
  • AP (available, partition-tolerant): both sides keep answering and accepting writes. The copies disagree for a while, and they are merged after the network heals. Examples: Cassandra with default settings, and DynamoDB with its default eventually consistent reads. Right for carts and feeds.

Two points clear up most confusion:

  • "Pick two of three" is wrong. You cannot choose to avoid partitions, because networks fail whether you like it or not. So the real choice is only between C and A, and only while a failure lasts. When the network is healthy, a system can have both.
  • CP and AP are defaults, not labels for a product. Many databases let you choose per request: a strongly consistent read in DynamoDB, or QUORUM instead of ONE in Cassandra.

Takeaway: CAP answers one question: when the network breaks, do I return an error or a possibly old answer?

5. PACELC: The Choice When Nothing Is Broken

CAP only covers failures, but failures are rare. The common case is a healthy network, and there is still a trade-off in it. PACELC extends CAP to cover that case. The name reads as a sentence:

If there is a Partition, choose Availability or Consistency. Else (no partition), choose Latency or Consistency.

The "else" half is about speed. A replica that is close to the user answers fast, but it may be a little behind. The only way to be sure of the latest value is to ask the leader or a majority of replicas, which takes a network round trip. Take a user in Mumbai whose data has a leader in Virginia:

  • Fast, possibly old: read the replica in Mumbai. About 1 ms. It may be a few milliseconds behind the leader.
  • Latest, slow: read from the leader in Virginia. About 200 ms for the round trip (India to US East is farther than the Atlantic).

Nothing is broken in either case. You are paying time to buy freshness, on every request.

A system is then described by two choices, one for failures and one for normal operation. Cassandra with default settings and DynamoDB's default reads favor availability and low latency (PA/EL). Spanner and etcd favor consistency in both cases (PC/EC). You do not need to memorize labels for products. You need to say which side you pick for each feature, and why.

Takeaway: PACELC adds the everyday cost that CAP leaves out: fresher reads are slower reads.

6. Choosing per Feature

Do not choose one level for the whole system. Choose one per operation, by asking: what is the worst thing a stale read can cause here? Take a digital wallet:

Feature What a stale read causes Level and how
Spend from balance Overspending Strong. Check and update on the leader in one step
Unique username Two users with one name Strong. Unique index on the leader
History after paying User thinks the payment vanished Read-your-writes. Read the leader for a few seconds
Support chat Reply before question Causal. Keep a thread in one partition, ordered by sequence number
Badge counts A number a few seconds old Eventual. Read replicas or a cache

Most traffic is in the last rows, so most of the system stays fast and cheap. The strong part is small, and often one atomic statement on the leader:

// Check and update in one step: two spends cannot both pass the check
int rows = jdbc.update(
    "UPDATE wallets SET balance_cents = balance_cents - ? " +
    "WHERE id = ? AND balance_cents >= ?", amount, walletId, amount);
if (rows == 0) throw new InsufficientFundsException();

This is a compare-and-set. NoSQL stores offer the same as conditional writes. In an interview, say it in three parts: the feature, the harm of a stale read, and the cost you accept.

6.1 Multi-Region: Pick a Home

With users in several regions, the usual pattern is: each user or account has a home region that takes their writes and strong reads. Other regions keep read-only copies for fast, slightly old reads. A user who travels is still routed to their home region for writes. This avoids paying 100 ms on every operation. The multi-region lesson covers it in full.

A quick rule if you are unsure: use strong consistency for anything about money, stock, identity or permissions. Use eventual for anything that is derived, counted, ranked or shown for information. Move a feature up only when a stale read causes real harm.

7. Living with Eventual Consistency

Most of a real system is eventual, so learn the habits that make it safe:

  • Make writes safe to repeat. Messages and requests can arrive twice. Use an idempotency key so the second copy does nothing.
  • Use data that merges. A "likes" counter that adds up increments from every replica never loses a like. A single "likes = 41" value that each replica overwrites does.
  • Show the user's own change at once. The app can display the new value immediately, even before the read path catches up. Mark it "saving" if needed.
  • Treat caches and search indexes as replicas. They are copies of the database and are always a little behind. Set a time-to-live to bound the staleness, and update them from events. Writing to the database and the search index separately ("dual write") can leave them different if one write fails. The outbox pattern in the distributed transactions lesson solves this.
  • Measure the gap. Track replication lag and cache age, and alert when they pass what the feature can tolerate.

8. Common Pitfalls

  • "Pick two of three." The choice is only C or A, and only during a failure.
  • Mixing the two meanings of consistency. ACID and replica consistency are different.
  • Ignoring latency. Day to day, consistency costs milliseconds, not outages.
  • Strong consistency everywhere. You pay latency and availability for data that does not need it.
  • Eventual consistency with no plan. You still need to handle conflicts and show users something sensible.
  • Using a replica or cache for a decision that needs the latest value, such as a balance or stock check.

9. Interview Questions This Lesson Prepares You For

  • Explain the CAP theorem. When the network between nodes breaks, a system must either refuse some requests (consistent) or answer with possibly old data (available). Failures cannot be avoided, so that is the real choice.
  • Is Cassandra CP or AP? By default, AP. With QUORUM reads and writes it leans to consistency, and fails when a majority is down.
  • What does PACELC add? Even without failures, fresher reads cost latency, because the system must ask the leader or a majority.
  • Strong against eventual consistency? Strong: every read sees the latest completed write, at a cost in latency and availability. Eventual: copies agree later, with the lowest cost.
  • Your cache and your database disagree. Why, and what do you do? A cache is a copy, so it lags the database. Bound the staleness with a time-to-live, update or delete cache entries when the data changes, and read from the database for decisions that need the latest value.
  • Linearizable or serializable? Linearizable is about recency: a read sees the latest completed write of one value. Serializable is about transactions: the result equals some one-at-a-time order. A system can have one without the other. Spanner gives both.
  • How would you handle consistency in a payment app? Per feature: strong for balances and unique names, read-your-writes for history, causal for message threads, eventual for counts.