CAP theorem explained: consistency vs availability when the network breaks

The CAP theorem is famous and often misquoted. The idea itself is short: when the network between your servers breaks, each side must either refuse requests or risk giving wrong answers. Learn what C, A and P really mean, why 'pick 2 of 3' is misleading, CP vs AP with real examples, and the speed-vs-accuracy trade-off you face even when the network is fine.

An ATM in the middle is connected by a cable to the bank's central computer on the left, and the cable is cut. A customer asks the ATM for 8,000 rupees. Two arrows lead from the ATM to two possible outcomes. Option 1, marked C for consistency: the screen says 'Can't reach your bank. Please try later.' No cash, but the bank's records stay correct. Option 2, marked A for availability: the ATM pays out 8,000 rupees using the last balance it knew. The customer gets cash, but the balance may now be wrong. A banner asks 'Bank unreachable. Now what?'
Fig. 1 — One ATM, cut off from the bank. It can refuse (consistency) or pay out on old information (availability). It can't do both.

You’re at an ATM. Your account has ₹10,000, and you ask for ₹8,000. Normally the ATM checks your balance with the bank’s central computer before paying. Right now, the network link between them is down.

The ATM has exactly two options:

  1. Refuse: “Sorry, we can’t reach your bank. Please try again later.” You leave without cash, but the bank’s records can never be wrong.
  2. Pay out anyway, trusting the last balance it knew (₹10,000). You get your money. But if a family member withdrew ₹8,000 from another ATM a few minutes ago, one that could still reach the bank, your account is now overdrawn.

There’s no third option. While it’s cut off, the ATM simply can’t know what happened elsewhere. Refusing protects consistency: the data is never wrong. Paying out protects availability: the service keeps working. You can’t have both while the link is down. That is the CAP theorem, and everything else in this article is detail.

In the previous part we saw that replicas can disagree for a while. CAP answers the harder question: what happens when replicas can’t reach each other at all?

What CAP actually says

Eric Brewer proposed CAP in 2000; Seth Gilbert and Nancy Lynch proved it in 2002. It talks about three properties of a system whose data is copied across several machines:

  • C, Consistency: every read sees the latest write, as if there were only one copy. (This is linearizability, the strongest model. It is not the “C” in ACID, which is about database rules like foreign keys.)
  • A, Availability: every request that reaches a working server gets a real answer, not an error or a timeout. Stale data counts as an answer.
  • P, Partition tolerance: the system keeps running even when messages between servers are lost, so some servers can’t talk to others. That split is called a network partition.

The theorem, stated properly:

“When a network partition happens, a system must give up either consistency or availability. It cannot keep both.”
Two replicas, A and B, both hold x = 1. The network between them is cut. A client writes x = 2 to replica A. Another client then reads x from replica B. Replica B has two options. Choice C: refuse to answer, returning an error such as 'cannot confirm latest value', which keeps the data correct but makes B unavailable. Choice A: answer with x = 1, the old value, which keeps B available but returns stale data. There is no option that returns x = 2, because B has no way of knowing about the write.
The core of the proof. Replica B can't know about a write it never received, so it can refuse (consistent) or answer with old data (available). Nothing else is possible.

Why is it impossible to have both? Look at replica B in the figure: it’s the ATM from the story. A write just happened on A, and B can’t hear about it. When a read arrives at B:

  • If B answers, it can only give the old value. Not consistent.
  • If B wants to be sure it’s not giving an old value, it has to wait or refuse. Not available.

No clever algorithm can fix this, because the information B would need is on the other side of a broken link.

Four myths about CAP

Myth 1: “Pick any 2 of 3”

This is the most common way CAP is taught, and it’s misleading. It suggests you can choose “C and A” and give up “P”. But partitions aren’t something you choose. Cables get cut, switches fail, cloud zones lose contact, and a server stuck in a long garbage-collection pause looks exactly like one that’s unreachable. If your data lives on more than one machine, partitions will happen.

So the real choice is only between C and A, and only while a partition is happening.

Myth 2: “CA systems exist”

A single database on one machine is sometimes called “CA”: it’s consistent, and there’s no network inside it to break. But that’s not because it beat CAP. It’s because it isn’t distributed. And if that one machine dies, everything is unavailable anyway.

A distributed system that claims to be “CA” really means “we assume partitions won’t happen”. When one does, it will end up either refusing requests or giving inconsistent answers. It just won’t have planned which.

Myth 3: “CP means the system goes down”

In a well-designed CP system, only the cut-off minority stops. The side that still has a majority of servers keeps working normally. Users connected to the healthy side may notice nothing at all.

Myth 4: “The whole system is either CP or AP”

The choice applies per operation, and often per piece of data. The same app can refuse a payment during a partition while happily accepting a “like”. And when there’s no partition, which is most of the time, a system can be both consistent and available.

CP: refuse rather than be wrong

A CP system chooses consistency. During a partition, servers that can’t confirm they have the latest data refuse reads and writes, returning an error instead of a possibly wrong answer.

Most CP systems use majority rule. Nothing counts as written until more than half of the servers agree. During a split, only one side can possibly have a majority, so only one side keeps going:

A cluster of five servers, A to E, is split by a network partition into two groups. The left group has A, B and C: three of five, a majority, so it keeps accepting reads and writes. The right group has D and E: two of five, not a majority, so it refuses writes and returns errors like 'no quorum, try again'. A note explains that two groups can never both have more than half of five, so the two sides can never accept conflicting writes.
Majority rule: only a group with more than half of all servers may accept writes. Two groups can never both have a majority, so they can never disagree.

This is how etcd, ZooKeeper and Consul work, and why systems like Kubernetes keep their critical state in them. It’s also how Google Spanner and CockroachDB handle each piece of data. Use 3 or 5 servers, not 2 or 4: with 4, a 2-and-2 split leaves neither side with a majority, and everything stops.

In your code, a CP system’s refusal is just an error you must handle well:

// Java · etcd/ZooKeeper-style write: fail clearly, never guess
public void reserveUsername(String name, long userId) {
    try {
        registry.createIfAbsent("/usernames/" + name, userId);    // needs a majority
    } catch (NoQuorumException | TimeoutException e) {
        throw new ServiceUnavailableException(
            "We can't confirm this username right now. Please try again in a moment.");
    } catch (AlreadyExistsException e) {
        throw new UsernameTakenException(name);
    }
}

Choose CP when a wrong answer does real damage: money, stock counts, seat bookings, unique usernames, locks, and deciding which server is the leader.

AP: answer now, fix it later

An AP system chooses availability. During a partition, every reachable server keeps accepting reads and writes. Each side may drift apart, and when the network heals, the system reconciles: it merges the differences.

A timeline in three stages. Before: both regions show the same shopping cart with one book. During the partition: in the US region, the user adds headphones; in the EU region, the same user on another device adds a lamp. Both writes succeed, and the two carts now differ. After the network heals: the carts are merged into one with the book, the headphones and the lamp. A note says merging works for carts, but for a bank balance there is no safe automatic merge.
AP keeps every side working and merges later. That's easy for a cart, and dangerous for a balance.

How the merge works depends on the data:

  • Merge both: two versions of a cart become one cart with all items. Amazon’s original Dynamo paper used exactly this example.
  • Last write wins: keep the newest version. Simple, but one write is silently lost.
  • Store changes, not totals: record “+1 like” events instead of “likes = 42”, so all changes can be added up in any order.
  • Fix it in business terms: if two people bought the last item, apologise to one and offer a refund or a voucher.
// Java · AP cart: accept the write locally, merge versions when they meet
public Cart merge(Cart a, Cart b) {
    Map<String, Integer> items = new HashMap<>(a.items());
    b.items().forEach((sku, qty) -> items.merge(sku, qty, Math::max));   // keep every item
    return new Cart(a.userId(), items);
}

This is how Cassandra, Riak and the original Dynamo behave by default, and how most social feeds, like counts, presence (“online now”) and shopping carts are built.

Choose AP when being unavailable costs more than being briefly wrong, and when conflicts can be merged or fixed later.

Some systems pick a careful middle path. Back to the ATM: some payment systems approve small amounts while offline, up to a fixed limit, and settle them later. That’s availability on purpose, with a cap on how wrong things can get.

How to choose for each piece of data

Ask these questions about each kind of data, not about the whole system:

  1. What’s the cost of a wrong answer? Money lost, double-booked seats, safety risk → lean CP.
  2. What’s the cost of an error page? Lost sales, users leaving → lean AP.
  3. Can two conflicting versions be merged safely? Carts and counters, yes → AP is fine. Balances, no → CP.
Data During a partition Why
Account balance, payments CP: refuse Two withdrawals of the same money can’t be “merged”
Last item in stock, seats CP: refuse Selling one thing twice costs money and trust
Usernames, locks, leader election CP: refuse Two winners breaks everything that depends on them
Shopping cart AP: accept, merge later Merging carts is easy and harmless
Likes, views, feeds AP: accept A briefly wrong number hurts nobody
Driver location in a ride app AP: accept A slightly old position beats no position

The everyday trade-off: PACELC

CAP only describes the moment the network breaks, which is rare. What about the other 99.9% of the time? Daniel Abadi’s PACELC adds the everyday trade-off:

A decision tree. Start: is there a network partition? If yes, the P branch: choose availability or consistency, which is CAP. If no, the E branch, meaning else: choose low latency or consistency, because keeping replicas in sync means waiting for them on every write. Examples at the bottom: Cassandra and DynamoDB by default lean PA and EL, available and fast. etcd and Spanner by default lean PC and EC, putting consistency first in both cases. A note says the everyday trade-off you feel most often is latency versus consistency, not the partition case.
PACELC: if Partition, choose Availability or Consistency; Else, choose Latency or Consistency.
  • If there’s a Partition: choose Availability or Consistency (that’s CAP).
  • Else, when everything is healthy: choose Latency or Consistency.

Even with a perfect network, keeping every copy in sync means waiting for other servers on every write, and often on reads too. That’s the trade-off you actually feel day to day: synchronous replication is slower, async replication is faster but briefly stale (we saw this in replication models).

System (default settings) If partition Else
Cassandra, DynamoDB Availability Low latency
etcd, Spanner Consistency Consistency (by default)
Single-leader SQL + async replicas Mixed: the leader is consistent, replicas may be stale Latency on replica reads

Treat these labels as rough guides. Most modern databases are tunable: Cassandra with QUORUM reads and writes behaves much more like CP, and DynamoDB lets you ask for a strongly consistent read. What matters is the behaviour you configure.

What breaks, and how to fix it

What breaks Why The fix
Split brain Both sides of a partition think they’re in charge and accept writes Majority rule; fence the old leader with a term or epoch number
Everything stops on a 2–2 split An even number of servers, so neither side has a majority Use an odd number: 3 or 5
AP copies never converge Replication broken or a backlog building up silently Monitor replication lag and alert; run background repair
“CP” errors cascade Clients retry the refused side instantly and pile up Retries with backoff and jitter; a clear “try again later” message
Wrong labels in design docs “We use X, so we’re CP” without checking the settings Check the actual consistency settings per query

Puzzle 1: CP or AP for a ride-hailing app?

Ask the same question each time: what’s worse, an error or a wrong answer?

  • Driver locations: AP. A dot on the map that’s a few seconds old is fine. A blank map is not.
  • Assigning a driver: CP. If both sides assign the same driver to two riders, one rider waits for a car that never comes. Better to say “finding a driver, please wait” for a moment.
  • Charging the fare: CP. Charging twice, or not at all, costs real money and trust. It can also simply wait and retry once the link is back.
  • Ride history: AP. Showing yesterday’s list without the very latest ride is harmless, and it catches up shortly.

One app, two choices. That’s normal: CAP is decided per feature, not per company.

Puzzle 2: the shrinking majority

No. A is now 1 out of 5. A majority means more than half of all 5 configured nodes, which is 3, and it must be true right now, not when the partition started. If A carried on, and D and E later reconnected with B and C, a new majority could form and accept different writes, and the two histories would conflict.

Consensus protocols like Raft (used by etcd) handle this by requiring a majority of the full cluster to confirm every write. A leader cut off from the majority simply can’t commit anything, so it can’t create a second, conflicting history. If you build your own check, count against the configured cluster size, not “how many nodes I can see”, and never cache the answer.

Puzzle 3: the “eventually” that never came

No. “Eventually” means once replication is working. Five minutes means something is broken: a replica is down or cut off, a replication queue is stuck, or a repair process isn’t running. Eventual consistency doesn’t fix any of that by itself.

Monitor replication lag for every replica and alert well before users notice (say, past 30 seconds). Take badly lagging replicas out of the read pool, and run the database’s repair process (Cassandra calls it anti-entropy repair) on a schedule so missed writes are filled in.

Key takeaways

  1. CAP is about network partitions. When servers can’t talk, each side must either refuse (C) or risk stale answers (A).
  2. “Pick 2 of 3” is misleading. In a distributed system partitions will happen, so the real choice is C or A during one.
  3. C in CAP means linearizability, not ACID’s C. A means every working server gives a real answer.
  4. CP systems use majority rule: only the side with more than half the servers keeps going. Use odd cluster sizes.
  5. AP systems keep every side working and reconcile later. Great for carts and likes; wrong for balances.
  6. Choose per piece of data, and remember PACELC: without a partition, you still trade latency for consistency.

That completes the Consistency & CAP theorem thread: how data is copied, what reads can promise, and what happens when copies can’t talk. Next comes Part 7, performance and caching: making all of this fast.

Comments

LEAVE A COMMENT
No sign-up. Comments appear after a quick review.