System Design

Core Concepts

CAP and What It Actually Constrains

Almost everything you have been told about CAP is a simplification of a simplification. The theorem is real, it is narrow, and the version with the triangle diagram is wrong in a way that will cost you an interview.

In a lot of system design interviews, the candidate says "so this is an AP system" at some point, and the interviewer looks a little disappointed.

The sentence isn't exactly wrong. It's a category error: it puts a label on the wrong kind of thing. That's worse than being wrong, because it shows the candidate learned CAP from a triangle diagram and not from what the theorem proves. For most topics, the popular version is a simpler form of the truth. For CAP, the popular version makes a different claim altogether.

Here is what this article is built on:

CAP doesn't classify databases. It classifies single operations on single pieces of data. And it only says anything while your network is broken.

Both halves matter. The first half rules out "we are an AP system". Inside one product, a few operations need the strong guarantee and most don't, and any serious datastore lets you choose per query. The second half explains why CAP is nearly useless as a design tool. It describes what happens during an event that fills a tiny fraction of your year, and it says nothing about the rest of the year.

You don't have to take my word for either half. Eric Brewer, who proposed CAP, wrote a paper in 2012 looking back at it, and it says the same thing. He wrote that the "2 of 3" framing is misleading. Partitions are rare, and outside them you can have both consistency and availability. He also wrote that the choice between the two can differ from one subsystem to another, and even from one operation to the next. So for more than a decade, the person who proposed CAP has been telling people not to use it the way most people use it.

CAP's strong guarantee is called linearizability: every read sees the latest completed write, as if there were only one copy of the data. So the goal here isn't to memorise a triangle. The goal is to point at one specific operation and say out loud: this one needs linearizability, here is what that costs, and these fourteen don't.


Why this theorem gets misused

The popular version packs three separate errors into one sentence that's easy to remember.

Error one: it isn't a choice of two out of three. Partition tolerance isn't a property you decide to have. A partition is when the network stops delivering messages between some of your machines, and it's something the network does to you. If your system has more than one machine and they talk over a network, that network can drop messages, and one day it will. You can't opt out. So "CA" isn't a real option. A triangle diagram that lets you sit on that edge is describing a system that doesn't exist. What you do choose is much narrower: while a partition is happening and a request arrives, do you answer it or refuse it? That's a choice between two options.

Error two: the words don't mean what they look like. The C isn't "the data is correct", and it isn't the C in ACID, the set of guarantees a database transaction gives. It's linearizability, a specific and very strong rule about the order in which operations take effect. The A isn't "high availability" or "99.99 percent uptime". It's a formal condition that most real systems fail. Almost every bad CAP argument starts from a loose definition of one of these two letters.

Error three: it describes one moment, not a system. The theorem says what is impossible during a partition. Your service spends almost none of its life partitioned. Your decisions about latency, staleness, replication and quorums apply while the network is healthy. Replication means keeping copies of the data, called replicas, on several machines. A quorum is how many replicas must answer before a read or a write counts. CAP says nothing about any of these decisions.

So when should you bring CAP up at all? It's useful for one purpose: it makes you decide, out loud, what happens to a specific operation when a replica can't be reached. If you use CAP for anything else, such as classifying a database or justifying a technology choice, it's decoration. An interviewer who knows the material will notice.


What CAP actually says

The formal version comes from Seth Gilbert and Nancy Lynch. In 2002 they turned Brewer's conjecture, a claim he had made without a proof, into a proven theorem. Their result is precise, and that precision is what makes it useful.

C is linearizability, and nothing else

Linearizability means the system behaves as if there were exactly one copy of the data. Every operation takes effect all at once, at a single instant somewhere between when you called it and when it returned.

Here is the part to remember: once a write has completed, every later read, by anybody, anywhere, returns that value or a newer one. No reader anywhere can see the old value again. That's a promise about real time, and it's why linearizability is expensive. To keep the promise, the nodes have to talk to each other before they answer.

What linearizability rules out
Client A's write of x = 2, in blue, takes effect at some instant inside its span and returns at 40 ms, the dashed line. Client B starts a read after that line and gets 2, which is allowed. Client C also starts after the line but gets 1, in red, from a replica that hasn't caught up. A linearizable system can't return that answer.Client A's write of x = 2, in blue, takes effect at some instant inside its span and returns at 40 ms, the dashed line. Client B starts a read after that line and gets 2, which is allowed. Client C also starts after the line but gets 1, in red, from a replica that hasn't caught up. A linearizable system can't return that answer.
Once a write returns, nobody may read the old value. Client A's write of x = 2, in blue, takes effect at some instant inside its span and returns at 40 ms, the dashed line. Client B starts a read after that line and gets 2, which is allowed. Client C also starts after the line but gets 1, in red, from a replica that hasn't caught up. A linearizable system can't return that answer.

Two things it isn't:

  • It's not ACID's consistency. ACID's C means "this transaction leaves the database obeying the constraints you declared". That's a statement about your schema. Linearizability is a statement about the order of operations across replicas. They share a letter and nothing else.
  • It's not serializability. Serializability means transactions appear to run one at a time, in some order. Linearizability means single operations on single objects take effect in real-time order. You can have either one without the other.

A means "an answer", and there is no clock in the definition

In CAP, availability means every request that reaches a working node gets a response that isn't an error. The response doesn't have to be fast, and it doesn't have to be correct. It only has to be a response.

This has two consequences that surprise people.

There is no time limit. A system that takes an hour to answer is available under CAP. A system that answers in one millisecond with an error isn't. This is why CAP can't help with the decisions you make day to day. In practice, a response that arrives after the user has left is the same as no response, and CAP can't see that difference at all.

It has to be every node. Say a partition leaves three nodes on one side and one on the other. The lone node returns errors, and the other three keep serving traffic. Under CAP the system is not available, even though most of your users are fine. Real systems almost never meet this condition. As Kleppmann observes, that's why most databases are neither C nor A in CAP's terms. So if you call a database one or the other, you're wrong before you've finished the sentence.

Available, in CAP's sense
A partition, the red dashed line, cuts node 4 off from the other three. Clients of nodes 1 to 3 get answers, in green. The client of node 4 gets an error, in red. Most users are fine, but CAP's A needs every working node to answer, so this system is not available under CAP.A partition, the red dashed line, cuts node 4 off from the other three. Clients of nodes 1 to 3 get answers, in green. The client of node 4 gets an error, in red. Most users are fine, but CAP's A needs every working node to answer, so this system is not available under CAP.
One node returning errors makes the whole system unavailable. A partition, the red dashed line, cuts node 4 off from the other three. Clients of nodes 1 to 3 get answers, in green. The client of node 4 gets an error, in red. Most users are fine, but CAP's A needs every working node to answer, so this system is not available under CAP.

P is not something you pick

Partition tolerance means the system keeps working when the network drops or delays any number of messages between nodes.

You don't choose it, because you don't choose whether packets get dropped. The only way to escape P is to have no network between your copies of the data. That means one machine. Then nothing keeps serving if that machine fails, and nothing saves your data if its disk dies. As soon as you add a second machine to survive losing the first, you're in CAP's world for good.

Partitions are also far more common than the name suggests. You can't tell the difference between a node that is partitioned, a node that has crashed, and a node that is only too slow to answer. From the outside all three look the same: you sent a message and nothing came back. Nodes send each other small "I'm alive" messages, called heartbeats, every second or so. So a garbage collection pause, where the runtime freezes the program to free memory, is a partition if it lasts long enough to miss a few heartbeats. An overloaded replica that stops answering in time is a partition. A wrong firewall rule is a partition. Almost none of the real ones are cut undersea cables.

Three failures that look the same
On the left, the network drops the request and node B never sees it. In the middle, node B has crashed. On the right, node B is paused, and its reply, the dashed arrow, arrives after node A has stopped waiting. In all three, node A sees the same thing: no reply before the timeout.On the left, the network drops the request and node B never sees it. In the middle, node B has crashed. On the right, node B is paused, and its reply, the dashed arrow, arrives after node A has stopped waiting. In all three, node A sees the same thing: no reply before the timeout.
To node A, a partition, a crash and a pause are all silence. On the left, the network drops the request and node B never sees it. In the middle, node B has crashed. On the right, node B is paused, and its reply, the dashed arrow, arrives after node A has stopped waiting. In all three, node A sees the same thing: no reply before the timeout.

So the choice is two-way, and it only binds during a partition

Without the triangle, CAP is a single question. A partition is in progress, and a request arrives at a node that can't reach its peers. The node has exactly two options:

  • Answer it using whatever it has locally. It might serve stale data, or accept a write that conflicts with a write on the other side. You've given up linearizability.
  • Refuse it, by returning an error or waiting until the partition heals. You've given up availability.

There's no third option. The proof shows exactly that, and nothing more. Everything else people attach to CAP is commentary.

The one question CAP asks
Client A writes x = 2 to node 1. A partition, the red dashed line, stops that write reaching node 2. When client B reads x from node 2, node 2 has two choices. It can answer with x = 1, which is stale, and give up C. Or it can refuse, in red, with an error or by waiting, and give up A. There is no third branch.Client A writes x = 2 to node 1. A partition, the red dashed line, stops that write reaching node 2. When client B reads x from node 2, node 2 has two choices. It can answer with x = 1, which is stale, and give up C. Or it can refuse, in red, with an error or by waiting, and give up A. There is no third branch.
Cut off from its peer, a node can only answer or refuse. Client A writes x = 2 to node 1. A partition, the red dashed line, stops that write reaching node 2. When client B reads x from node 2, node 2 has two choices. It can answer with x = 1, which is stale, and give up C. Or it can refuse, in red, with an error or by waiting, and give up A. There is no third branch.

Now look at how often that question comes up.

One year, with four partitions
The green strip is one year. The four red marks are the partitions, 10 minutes each. They are drawn far wider than they really are, because at true scale you couldn't see them. CAP's choice only applies inside the red marks. For the rest of the year the network is healthy, and CAP says nothing.The green strip is one year. The four red marks are the partitions, 10 minutes each. They are drawn far wider than they really are, because at true scale you couldn't see them. CAP's choice only applies inside the red marks. For the rest of the year the network is healthy, and CAP says nothing.
CAP covers 40 minutes of the year. The green strip is one year. The four red marks are the partitions, 10 minutes each. They are drawn far wider than they really are, because at true scale you couldn't see them. CAP's choice only applies inside the red marks. For the rest of the year the network is healthy, and CAP says nothing.
Back of envelopeHow much of your year CAP actually describes
Assume partitions that isolate part of your cluster happen
4 times a year and last 10 minutes each. (An assumption,
but the order of magnitude is what matters.)

  partitioned time     4 × 10          =      40 min/year
  minutes in a year                    = 525,600 min/year
  share of the year    40 / 525,600    =   0.008%

For grounding: Google reports five nines of availability
for Spanner, which is about 5 minutes a year of downtime
in total.
  ─────────────────────────────────────────────────
  The C-or-A choice governs roughly 0.008% of your year.
  Something else governs the other 99.99%, and CAP does
  not mention it.

The ladder of consistency models

People use the word "consistency" for at least six different guarantees, and that's why arguments about it go nowhere. Here they are, strongest first.

modelwhat it promiseswhat breaks without it
Linearizableone copy, ordered in real timeuniqueness constraints, locks, leader election, reads that follow an out-of-band message
Sequentialone total order, but not tied to wall-clock timelittle in practice; mostly of theoretical interest
Causalanything that caused something else is seen in that ordera reply appearing before the message it answers
Read-your-writesyou always see your own writes"I saved it and it vanished"
Monotonic readsyou never see time run backwardsa counter going 5, then 3, then 5
Eventualreplicas converge if writes stopnothing is promised about when, or about what you see meanwhile

The line that matters sits at causal consistency, because causal is the strongest guarantee you can offer and still answer requests during a partition. Every model above it needs the nodes to agree with each other, and during a partition they can't. For every model at or below it, each side can keep the guarantee on its own, and the two sides merge after the partition heals.

Quorums buy you freshness, not linearizability

The quorum rule is simple arithmetic. Say you have N replicas. A write must be acknowledged by W of them, and a read must get answers from R of them. If W + R > N, the replicas that took the write and the replicas that answer the read must share at least one node. So every read reaches at least one replica that has the latest completed write.

Back of envelopeQuorum overlap, and what it does not buy
  N = 3 replicas

  W=2, R=2   →  4 > 3  ✓  sets overlap
  W=1, R=1   →  2 > 3  ✗  no overlap, no guarantee
  W=3, R=1   →  4 > 3  ✓  fast reads, writes need every replica up
  W=1, R=3   →  4 > 3  ✓  fast writes, reads need every replica up

What overlap gives you
  at least one replica in your read set holds the newest write

What it does NOT give you
  a way to know which returned value is newest, without versions
  any promise about a write that got 1 ack and then returned an error
  agreement between replicas on the order of concurrent writes
  ─────────────────────────────────────────────────
  W + R > N is a freshness condition, not linearizability.
A quorum read that goes backwards
With N = 3, W = 2 and R = 2, a write of x = 2 has reached replica A, in green, and is still waiting for a second acknowledgement. Reader 1 asks A and B, sees 2 on A, and returns 2. Reader 2 starts after reader 1 has finished, asks B and C, and gets 1, in red. Nothing copied the 2 to B before reader 1 answered, so a later read saw an older value.With N = 3, W = 2 and R = 2, a write of x = 2 has reached replica A, in green, and is still waiting for a second acknowledgement. Reader 1 asks A and B, sees 2 on A, and returns 2. Reader 2 starts after reader 1 has finished, asks B and C, and gets 1, in red. Nothing copied the 2 to B before reader 1 answered, so a later read saw an older value.
Overlap promises a fresh copy somewhere, not an order. With N = 3, W = 2 and R = 2, a write of x = 2 has reached replica A, in green, and is still waiting for a second acknowledgement. Reader 1 asks A and B, sees 2 on A, and returns 2. Reader 2 starts after reader 1 has finished, asks B and C, and gets 1, in red. Nothing copied the 2 to B before reader 1 answered, so a later read saw an older value.

The middle of the ladder is cheap. Read-your-writes and monotonic reads fix most of what people reach for linearizability to fix, and they cost almost nothing. One way is to send a user's reads to a copy that already has their write. Another is to hand the client a token that records how up to date its view is, and have it ask for at least that much on later reads. Reaching for linearizability where read-your-writes would do is the most common piece of over-engineering in this area.


PACELC: the question CAP forgot

If CAP covers 0.008 percent of your year, what covers the rest? Daniel Abadi answered this in 2012 with an extension called PACELC. It's more useful than CAP, and far less well known.

if (Partition)  then choose Availability or Consistency
else                 choose Latency     or Consistency

The P half is CAP. The E half, for "else", is the normal case, and it's where your system spends its time. Even on a healthy network, a linearizable operation has to hear back from other nodes before it can answer. That isn't a failure. It's the cost of the guarantee, and you pay it on every request.

Back of envelopeWhat linearizability costs when nothing is wrong
A linearizable write waits for a majority to acknowledge it,
so it costs one round trip to the middle member of the quorum.

  3 replicas, same availability zone
    majority ack                       +0.25 to 0.5 ms
  3 replicas, one per zone in one region
    majority ack                       +0.5 to 2 ms
  3 replicas: Mumbai, Singapore, Frankfurt
    from Mumbai, wait for Singapore    +55 ms
  5 replicas across three continents
    wait for the 2 nearest others      +100 ms or more

Linearizable reads are not free either. They need a leader
lease or a quorum read, which is why DynamoDB charges
exactly twice as much for a strongly consistent read as for
an eventually consistent one.
  ─────────────────────────────────────────────────
  Same guarantee, 100× the price or more, depending only
  on where you put the replicas.

Linearizability isn't expensive in general. It's expensive in proportion to the distance between your replicas. Three copies in one datacenter make it nearly free. Three copies spread across continents make it a visible part of your latency budget on every write. So the price is set by where the replicas go. That decision is usually made for durability, so the data survives losing a whole site, by someone who never thought about consistency.

A write waits for the nearest majority
The leader counts as one copy, so a majority of three needs one more acknowledgement. In one region it comes from zone b after about 1 ms, too short to see on this axis. With replicas in Mumbai, Singapore and Frankfurt, the orange bar shows the write waiting 55 ms for Singapore. Frankfurt's reply, in grey, comes at 120 ms, and nobody waits for it.The leader counts as one copy, so a majority of three needs one more acknowledgement. In one region it comes from zone b after about 1 ms, too short to see on this axis. With replicas in Mumbai, Singapore and Frankfurt, the orange bar shows the write waiting 55 ms for Singapore. Frankfurt's reply, in grey, comes at 120 ms, and nobody waits for it.
Where the replicas sit sets the price of every write. The leader counts as one copy, so a majority of three needs one more acknowledgement. In one region it comes from zone b after about 1 ms, too short to see on this axis. With replicas in Mumbai, Singapore and Frankfurt, the orange bar shows the write waiting 55 ms for Singapore. Frankfurt's reply, in grey, comes at 120 ms, and nobody waits for it.
systemduring a partitionnormallynote
Cassandra, Riak, Dynamoavailabilitylatencyboth tunable per query
MongoDBavailabilityconsistencydepends heavily on write concern
HBase, BigTableconsistencyconsistency
SpannerconsistencyconsistencyBrewer calls it "technically CP" but "effectively CA"
Single-node Postgresnot applicablenot applicableno network between replicas, so no partition
Postgres, synchronous replicaconsistencyconsistency
Postgres, asynchronous replicaavailabilitylatencyif you read from the replica

Treat every row as a default, not a fact about the software. DynamoDB gives you a strongly consistent read or an eventually consistent one on the same table, and you choose on each call. Cassandra takes a consistency level on each query. This per-call choice is the strongest evidence that CAP classifies operations, not systems.

Two read paths on one DynamoDB table
The app writes to the orders table. DynamoDB copies each change into the global secondary index in the background, the dashed arrow. A read on the table can be strongly consistent, at twice the price of an eventual one. A read on the index can only be eventually consistent. The option in red is the one DynamoDB doesn't offer.The app writes to the orders table. DynamoDB copies each change into the global secondary index in the background, the dashed arrow. A read on the table can be strongly consistent, at twice the price of an eventual one. A read on the index can only be eventually consistent. The option in red is the one DynamoDB doesn't offer.
The guarantee depends on the path, not the product. The app writes to the orders table. DynamoDB copies each change into the global secondary index in the background, the dashed arrow. A read on the table can be strongly consistent, at twice the price of an eventual one. A read on the index can only be eventually consistent. The option in red is the one DynamoDB doesn't offer.

The method: label the operation, not the system

There are six steps. Once you've done it a few times, the whole thing takes a couple of minutes.

1. List the operations, not the components. For example: "claim a username", "read the seat map", "reserve a seat", "increment the view count". CAP applies to operations.

2. Ask the test question below about each one. Most operations will fail it, and that's the useful result.

3. For the ones that pass, find the smallest scope that needs the guarantee. Usually that's one key for a short time, not a table and not a service.

4. Price it. The cost is one round trip to the middle member of the quorum, and that depends on where your replicas live.

5. Decide what happens to that operation during a partition, and say it as a sentence about the product: "signup fails with a retry-able error", not "we choose C".

6. For everything that failed the test, pick the weakest model that hides what the user would notice. That's usually read-your-writes or monotonic reads, and both are cheap.

The method, run on a stadium booking
Step 1 lists four operations. At step 2, only holding a seat passes the test. The purple boxes, steps 3 to 5, follow that one operation: its scope, its price and what it does during a partition. The other three go straight to step 6, which picks the cheapest model for each.Step 1 lists four operations. At step 2, only holding a seat passes the test. The purple boxes, steps 3 to 5, follow that one operation: its scope, its price and what it does during a partition. The other three go straight to step 6, which picks the cheapest model for each.
Only one of four operations needs the guarantee. Step 1 lists four operations. At step 2, only holding a seat passes the test. The purple boxes, steps 3 to 5, follow that one operation: its scope, its price and what it does during a partition. The other three go straight to step 6, which picks the cheapest model for each.

The test

Here is the question that decides it:

Is there an action somebody takes based on this read that cannot be undone?

If two clients briefly disagree and the only result is that someone saw a slightly old number, you don't need linearizability. If the result is two people holding the same seat, two accounts with the same handle, or two workers processing the same payment, you do.

"Cannot be undone" is the right test because linearizability is one way to prevent a bad outcome, and compensation is another. Compensation means you let the bad outcome happen now and then, and pay to put it right. Airlines oversell flights on purpose. They've worked out that paying someone now and then to take a later flight is cheaper than coordinating perfectly, and they're right. If your bad outcome can be fixed with a refund, you may not need the guarantee at all.

One more case passes the test, and it catches people out because it involves no constraint at all.

Your service writes an uploaded photo to the primary database, the one node that takes writes. Then it puts a resize job on a queue, such as Amazon SQS. The queue is fast, and replication isn't. The worker picks up the job and reads a replica that hasn't caught up. It finds no photo, so it either fails or writes out a broken thumbnail.

The queue gets there before replication
The service writes the photo to the primary (1), then puts a job on the queue (2). The worker reads the replica at 100 ms and finds nothing (3), in red. Replication, the dashed orange line, brings the photo to the replica at 250 ms (4), too late for the worker.The service writes the photo to the primary (1), then puts a job on the queue (2). The worker reads the replica at 100 ms and finds nothing (3), in red. Replication, the dashed orange line, brings the photo to the replica at 250 ms (4), too late for the worker.
The job reaches the worker before the photo reaches the replica. The service writes the photo to the primary (1), then puts a job on the queue (2). The worker reads the replica at 100 ms and finds nothing (3), in red. Replication, the dashed orange line, brings the photo to the replica at 250 ms (4), too late for the worker.

Nobody was competing for anything. The problem is that the message queue is a second channel, and it reached the worker before replication did. Whenever news of a write can reach a reader by some route other than the data store, the reader needs a guarantee that the write is visible. In ordinary applications, this is the most common real need for a linearizable read, and it's easy to miss. The same thing happens between people. You tell a colleague you've approved something, they refresh, and their replica hasn't caught up yet.

Naive

Answer with a letter

"We are an AP system." Or "we would pick C here because banking."

The letter isn't wrong. A letter can't be right, because the question doesn't have one answer for the whole system. Any real product has some operations that need linearizability and many that don't, and any real datastore lets you choose per call. So the sentence carries no information, and it tells the interviewer your reasoning stopped at a diagram.

The banking version is wrong in a different way. A bank's ledger is the classic example of a system that is deliberately not strongly consistent from end to end. Cheques take days to clear. A card payment is authorised at the till and settled separately, later. The whole industry runs on eventual consistency plus reconciliation, where the records are checked against each other afterwards and any mismatch is fixed. That's exactly the "compensate rather than coordinate" pattern.

Senior

Split the operations and price each one

Go through the list. Name which operations need linearizability, name what breaks without it, and say what happens to each during a partition. Then pick the cheapest model that works for everything else.

This is the right answer, and it's most of what the topic has to teach. It also leads to a much better conversation, because you're now discussing a product decision ("signup can fail for 2 minutes, checkout can't") instead of a matter of belief.

Name the cost. The operations that need the guarantee are now unavailable during a partition. Say which ones they are, and whether that's acceptable.

Staff

Reframe to PACELC, then try to remove the requirement entirely

This adds two moves to the senior answer.

Point out that the partition is the rare case. The choice you make on every request is latency against consistency, not availability against consistency. Then make the sharper point: where the replicas are sets almost all of the price of linearizability. Three copies in one zone make it nearly free. Three copies in Mumbai, Singapore and Frankfurt add 55 milliseconds to every write. So the consistency conversation and the replica placement conversation are the same conversation, and different people usually have them.

Then try to design the requirement away. An invariant is a rule the data must never break, and coordination isn't the only way to keep one. Make the operation commutative, so the order of operations stops mattering. Partition the resource, meaning split it into separate pieces, so uniqueness only has to hold inside each piece. Make the operation idempotent, so applying it twice has the same effect as applying it once and a duplicate is harmless. Or accept the bad outcome and attach a compensation. Each of these removes a need for coordination instead of paying for it, and a need you've removed costs nothing, ever.


Four decisions, worked

1. A unique username

Two people must not end up with the same handle. No compensation works here. You can't take a username back from someone who has been using it, and if you tried, you'd break every link that points at them.

So this one needs linearizability. The reason is short: it's a uniqueness rule, and breaking it can't be undone. Put username claims behind a single consensus group, or use a conditional write on a linearizable store. A conditional write only succeeds if the data still matches what you expected, here "this handle is still free". Then accept that signup fails during a partition for anyone cut off from the majority. Say that out loud as a product statement. It's clearly acceptable, and saying it shows you know what you traded.

Look at the scope. It isn't "the user service is CP". It's "the claim-a-handle operation is linearizable". Reading a profile, listing followers and rendering a page are all still served from replicas.

2. A like count

For a couple of seconds, one person sees 1,402 likes and another sees 1,404. Nothing bad happens. Nobody acts on the number, and if they did, the action could be undone.

So this needs nothing stronger than eventual consistency. You can use a data structure that merges without coordination: each replica keeps its own counter, and the total is the sum of all of them. Increments commute, meaning they give the same result in any order. So the order doesn't matter, and a partition does no harm. Both sides of a partition keep accepting likes, and the totals agree again once it heals.

A like counter that merges by adding
Each replica keeps one count per replica, A and B, and shows their sum. During the partition, the red dashed line, side A takes 2 likes and side B takes 4, so the two sides show 1,402 and 1,404. When it heals, A's count comes from side A and B's count from side B. Both sides show 1,406, in green, and no like is lost.Each replica keeps one count per replica, A and B, and shows their sum. During the partition, the red dashed line, side A takes 2 likes and side B takes 4, so the two sides show 1,402 and 1,404. When it heals, A's count comes from side A and B's count from side B. Both sides show 1,406, in green, and no like is lost.
Each side counts its own likes, so there's nothing to resolve. Each replica keeps one count per replica, A and B, and shows their sum. During the partition, the red dashed line, side A takes 2 likes and side B takes 4, so the two sides show 1,402 and 1,404. When it heals, A's count comes from side A and B's count from side B. Both sides show 1,406, in green, and no like is lost.

A second point usually ends the conversation early: at any real scale, the count is already approximate. It's sampled, cached and rounded for display. If the number is shown as "1.4K", its consistency isn't worth arguing about.

3. Seats in a stadium

People get this example wrong in both directions. The right move is to refuse to treat it as one operation.

Back of envelopeThree operations, three different answers
BROWSE the seat map
  wrong answer costs: a disappointment, recoverable
  needs: eventual consistency, served from replicas
  reads per booking: hundreds

HOLD a seat (a few minutes)
  wrong answer costs: two people own one seat, unrecoverable
  needs: linearizable conditional write
  scope: one seat key, for a few minutes
  writes per booking: 1

CONFIRM and take payment
  wrong answer costs: a double charge, recoverable via refund
  needs: durability and idempotency, not linearizability
  writes per booking: 1
  ─────────────────────────────────────────────────
  1 of 3 operations needs coordination, on 1 key.
  Hundreds of reads per booking need nothing.

The guarantee belongs on the hold, and its scope is one seat for a few minutes. Everything else runs at replica speed.

Then ask the staff-level question: does the hold need to be linearizable at all? For a stadium, yes. Each seat is a specific seat, and a duplicate means two people arguing at the turnstile. For general admission tickets, hotel rooms of one class, or places on a flight, any one unit is as good as another. There, overselling is a business decision with a known price, and airlines oversell on purpose. If a compensation exists and costs less than coordination, take the compensation.

Naive

Read the remaining count, check it, then write the new one

A client reads the stock, sees 1, decides that's fine, and writes 0. If two clients do this at the same time, both sell the last item.

Two clients sell the last item
The stock is 1. Client 1 reads 1, then client 2 reads 1, in blue. Client 1 writes 0 and sells. Client 2 writes 0 and sells too. Two items are sold from a stock of one, on a healthy network, because the read and the write are two steps and the other client got in between them.The stock is 1. Client 1 reads 1, then client 2 reads 1, in blue. Client 1 writes 0 and sells. Client 2 writes 0 and sells too. Two items are sold from a stock of one, on a healthy network, because the read and the write are two steps and the other client got in between them.
The race needs no partition. The stock is 1. Client 1 reads 1, then client 2 reads 1, in blue. Client 1 writes 0 and sells. Client 2 writes 0 and sells too. Two items are sold from a stock of one, on a healthy network, because the read and the write are two steps and the other client got in between them.

This is the classic race, and it fails without any partition at all. Two requests at the same moment on a healthy network are enough. CAP isn't the problem here. The problem is that the read and the write are two steps, when they need to be one atomic operation, one that can't be split. If you reach for CAP to explain this bug, you've learned the words without the mechanics.

Senior

One conditional write against a linearizable store

Make it a single atomic operation: "decrement if greater than zero", or a compare-and-set on the seat key, which writes only if the current value is still the one you read. Run it on a data store that gives you linearizability for that key. It takes one round trip, there's no race, and the loser gets a clean rejection.

This is correct. Name its two costs. Every one of these operations waits for a majority to acknowledge it, so replica placement sets the price. And during a partition, the minority side can't sell anything. For a booking system that's usually the right trade, and you should say it as one.

Staff

Partition the resource so uniqueness becomes local

Remove the requirement instead of paying for it.

A global stock of 10,000 items needs global coordination on every sale. Ten regional pools of 1,000 items each don't. Each region sells from its own pool with a local atomic operation, so no sale waits for a round trip to another region. A background process moves stock between pools every few minutes. You've turned one global invariant into ten local ones, and a local invariant survives a partition.

Ten pools instead of one
On the left, every sale updates one global count, so each sale waits for a majority across regions, the red arrows. On the right, each region sells from its own pool of 1,000 with a local atomic operation, in green. The rebalancer moves stock between pools every few minutes. Until it runs, Frankfurt is sold out while other pools still have stock.On the left, every sale updates one global count, so each sale waits for a majority across regions, the red arrows. On the right, each region sells from its own pool of 1,000 with a local atomic operation, in green. The rebalancer moves stock between pools every few minutes. Until it runs, Frankfurt is sold out while other pools still have stock.
Each region sells from its own pool without asking the others. On the left, every sale updates one global count, so each sale waits for a majority across regions, the red arrows. On the right, each region sells from its own pool of 1,000 with a local atomic operation, in green. The rebalancer moves stock between pools every few minutes. Until it runs, Frankfurt is sold out while other pools still have stock.

Name what you gave up. A region can run out while another still has stock. So you either accept some lost sales, or you accept waiting for the next rebalance. That's a much better problem than 55 milliseconds on every write, plus no sales at all on the minority side of a partition.

The same idea works well beyond tickets: you can often give up a little efficiency in where the stock sits, and in return remove the need for coordination completely. Leased quota, where each server is handed its own share of a limit, sharded counters and regional pools are all this same idea.

The choice is about money, not technology, so you can calculate the answer. Put numbers on both sides:

Back of envelopeCoordinate, or oversell and compensate?
Assumptions, all of which you should replace with your own:
  1,000,000 sales, average order value      ₹3,000
  coordination adds 55 ms to every checkout
  uncoordinated sales oversell              0.1% of sales
  cost to settle one oversell               ₹2,000

COORDINATE on every sale
  +55 ms on checkout. Using the Google and Deloitte
  figure of 8.4% more conversions per 0.1 s saved,
  55 ms costs roughly                     4.6% of conversions
  46,000 sales × ₹3,000                   = ₹13.8 crore lost

OVERSELL and compensate
  0.1% of 1,000,000                       = 1,000 oversells
  1,000 × ₹2,000                          = ₹20 lakh
  ─────────────────────────────────────────────────
  Compensating is about 70× cheaper than coordinating.

Change the margin, the oversell rate or the replica layout
and the answer flips. That is the point: it is arithmetic,
not a principle.

The conversion figure comes from a study of mobile retail sites, and here it's used outside that setting. So treat the 70 as a rough size with a clear direction, not as a precise result. What matters is that you can make the comparison at all. Most teams argue this question on instinct, when it has an answer.

When compensating stops being cheaper
The purple line is the cost of coordinating: ₹13.8 crore of lost sales, whatever the oversell rate. The teal line is the cost of compensating, ₹2,000 for each oversell, so it grows with the rate. At our 0.1 percent it is ₹20 lakh. The two lines cross at 6.9 percent, and above that, coordinating is cheaper.The purple line is the cost of coordinating: ₹13.8 crore of lost sales, whatever the oversell rate. The teal line is the cost of compensating, ₹2,000 for each oversell, so it grows with the rate. At our 0.1 percent it is ₹20 lakh. The two lines cross at 6.9 percent, and above that, coordinating is cheaper.
Compensating wins until about 7 percent of sales oversell. The purple line is the cost of coordinating: ₹13.8 crore of lost sales, whatever the oversell rate. The teal line is the cost of compensating, ₹2,000 for each oversell, so it grows with the rate. At our 0.1 percent it is ₹20 lakh. The two lines cross at 6.9 percent, and above that, coordinating is cheaper.

4. Reading your own edit

A user changes their display name and the page reloads. The old name comes back, because the read went to a replica that hadn't caught up. This feels like it needs strong consistency, and it doesn't.

It needs read-your-writes, which sits three places further down the ladder and is nearly free. Here are three ways to get it:

  • In a store where any replica accepts writes, send that user's reads to the replica that took their write, for a short window.
  • Return a version token with the write, and have the client send it on its next read. A replica that is behind that version waits, or forwards the read to one that has caught up.
  • Read from the primary for that one user for a few seconds after a write.

None of these needs the nodes to coordinate, and none of them slows down anyone else's requests. During a partition, they keep working for any user who can still reach a copy that has their write. In ordinary products, most "we need strong consistency" requirements turn out to be read-your-writes requirements. In practice, recognising that is worth more than anything else in this article.

Reading your own edit with a version token
The user saves a new name, and the reply carries token 812 (1). The reload goes to a replica and carries the token (2). The replica is at 810, so it waits. Replication brings 812 at 400 ms (3), and the replica answers with the new name (4), in green. Without the token, the replica would have answered at once with the old name.The user saves a new name, and the reply carries token 812 (1). The reload goes to a replica and carries the token (2). The replica is at 810, so it waits. Replication brings 812 at 400 ms (3), and the replica answers with the new name (4), in green. Without the token, the replica would have answered at once with the old name.
The token makes one read wait, not every read. The user saves a new name, and the reply carries token 812 (1). The reload goes to a replica and carries the token (2). The replica is at 810, so it waits. Replication brings 812 at 400 ms (3), and the replica answers with the new name (4), in green. Without the token, the replica would have answered at once with the old name.

Where CAP reasoning goes wrong

Here are eight failure modes, roughly in order of how often they turn up.

1. Calling a system CP or AP

Brewer says not to. Kleppmann wrote a post titled "Please stop calling databases CP or AP", and a paper arguing that the theorem should be retired in favour of more precise terms. The reason is the one this whole article is about: the label is applied to software, but the property belongs to operations.

In practice, every serious datastore lets you tune this. On the same table and the same key, you get two different guarantees depending on which call you make. A label that changes with each request isn't a label.

2. Thinking you chose P

You didn't. The physical world imposes partitions on you. And as the section on P showed, a node that is too slow looks exactly like a node that is partitioned. So partitions aren't rare events involving cut cables. They're everyday events: a long garbage collection pause, a network link at full capacity, a wrong security group rule, or a replica that fell behind because someone ran a heavy query.

If you describe a system as "CA", you're usually describing a system where nobody has decided what happens during a partition. In practice, that system loses data without raising any error, and nobody notices until an audit.

3. Confusing the many meanings of "consistency"

Three different things share the word. If you mix them up, the argument can't be settled, because each person is talking about a different property:

  • CAP's C, linearizability: an ordering guarantee across replicas.
  • ACID's C: your declared constraints hold after each transaction.
  • Isolation levels such as serializable or snapshot: how concurrent transactions may interleave.

Postgres in serializable mode has strong isolation and isn't linearizable. A Dynamo-style store can be set up for a fresh read and still not be linearizable. Say which one you mean, every time. It costs you three words, and it prevents most of the confusion in this area.

4. Assuming "eventual" means "quickly"

Eventual consistency promises that replicas end up the same if writes stop. It promises nothing about when, and the definition has no time limit at all.

Replication lag is how far a replica is behind the primary. In practice it has a long tail: usually milliseconds, sometimes seconds during a traffic spike, and minutes or hours if a replica is overloaded or a queue has backed up. That isn't a theory. It's the shape a graph of lag takes.

Replication lag over one day
The orange line is how far a replica is behind the primary, on a log scale. Most of the day it sits near 5 ms. At the morning and evening peaks it reaches 1.5 and 2 seconds. In the afternoon, a heavy query holds the replica 5 minutes behind, in red. The shape is illustrative, not measured.The orange line is how far a replica is behind the primary, on a log scale. Most of the day it sits near 5 ms. At the morning and evening peaks it reaches 1.5 and 2 seconds. In the afternoon, a heavy query holds the replica 5 minutes behind, in red. The shape is illustrative, not measured.
Lag is usually milliseconds, and now and then minutes. The orange line is how far a replica is behind the primary, on a log scale. Most of the day it sits near 5 ms. At the morning and evening peaks it reaches 1.5 and 2 seconds. In the afternoon, a heavy query holds the replica 5 minutes behind, in red. The shape is illustrative, not measured.

So treat staleness as a number, not an adjective. Measure your replication lag, put its p99 on a dashboard, and alert on it. The p99 is the value that 99 percent of measurements stay under. A system where lag is usually 5 milliseconds and sometimes 5 minutes behaves completely differently in those two states. If you don't measure it, you won't know which state you were in when the bug report arrives.

5. Believing the label

Datastores have a history of claiming guarantees they didn't deliver. That's why Kyle Kingsbury's Jepsen project exists. It takes a database, cuts the network between its nodes while it runs, and checks whether the promised invariants still hold. Many databases have failed those tests.

The lesson isn't that vendors lie. These properties are hard to get right, and they depend on settings you probably haven't touched. The documentation describes the intended behaviour, not what happens during a partition at 3 a.m. If your correctness depends on a guarantee, test that specific guarantee under a simulated partition before you rely on it.

6. Reaching for consensus where a constraint would do

Consensus works for every case, so it's also the expensive option. Before you pay for it, try to remove the need for it:

  • Make the operation commutative. Increments and additions to a set don't care about order, so they need no agreement about order.
  • Make it idempotent. If applying it twice is the same as applying it once, duplicates stop being a correctness problem.
  • Partition the resource, as in the regional stock pools above, so a global invariant becomes several local ones.
  • Attach a compensation. Overselling with a refund policy is often cheaper than coordinating perfectly.

Each of these is cheaper than consensus on every request, for as long as the system runs. Use consensus when none of them apply.

7. Designing for the partition and forgetting the recovery

CAP describes the partition, but the bugs are in what happens afterwards.

If you chose availability, both sides accepted writes. Now you have two histories that differ, and they must be merged. That merge is your real design work, and it's a product decision, not a technical one.

Here are the options, roughly from worst to best:

  • Last write wins. The write with the later timestamp is kept and the other is thrown away. This needs clocks you can trust across machines, and you don't have them. It also deletes one side's data without telling anyone. It's acceptable for a cache or an online-status indicator, and never for anything a person typed. If you pick it, at least know whose data you're throwing away.
  • Highest value wins. This works whenever the value only ever moves one way, such as a version number or a "seen up to here" marker, often called a high-water mark. It's cheap and safe when it applies.
  • Union of additions. Keep everything either side added. This works if you only ever add. Deletion is the hard half. A delete has to leave a tombstone, a marker that says "this was deleted", or the item comes back when the sides merge.
  • Counters that sum. Keep a count per replica and add them up. Increments commute, so the order never mattered and there was never a conflict to resolve.
  • Version vectors. Each value carries a counter per replica, so you can tell whether one version came after the other or whether the two were written independently. That tells you a conflict happened. It's useful, but it doesn't resolve the conflict. Somebody still has to decide.
  • Keep both and ask. Store both versions and let a person or a rule choose. This is what version control does, and for high-value data it's the right answer.
  • Make the conflict impossible. Allow only one replica to write a given key. If there's a single writer per key, there's never anything to merge. This is the option to reach for first, and the one people consider last.
Last write wins, with a slow clock
Side A takes edit 1 at 10:00:05. Side B takes edit 2 two seconds later, but side B's clock is 3 seconds slow, so edit 2 is stamped 10:00:04. The merge, in purple, keeps the later stamp, which is edit 1. Edit 2, in red, is deleted although it was written last, and nothing reports an error.Side A takes edit 1 at 10:00:05. Side B takes edit 2 two seconds later, but side B's clock is 3 seconds slow, so edit 2 is stamped 10:00:04. The merge, in purple, keeps the later stamp, which is edit 1. Edit 2, in red, is deleted although it was written last, and nothing reports an error.
The later edit loses because its clock is behind. Side A takes edit 1 at 10:00:05. Side B takes edit 2 two seconds later, but side B's clock is 3 seconds slow, so edit 2 is stamped 10:00:04. The merge, in purple, keeps the later stamp, which is edit 1. Edit 2, in red, is deleted although it was written last, and nothing reports an error.

Brewer's 2012 paper makes the same point. The useful work is in detecting a partition, in limiting which operations can go ahead during one, and in recovering afterwards. Picking a letter isn't the work. If your design says "we choose A" and stops, you've specified the easy half.

8. Two leaders, and no way to tell

If you chose consistency, you probably chose a leader, the one node that orders all the writes. A partition can leave you with two of them.

If a majority must vote for a leader, two leaders can't be elected at once. But that doesn't stop a leader that was already elected from carrying on. Say a leader pauses for 30 seconds during a long garbage collection. Its peers time it out, elect a replacement, and move on. Then the pause ends. The old leader carries on from where it stopped, still sure it's in charge, and sends a write. It has no way to find out otherwise, because everything it knows is 30 seconds old.

The fix is a fencing token. Each new leader gets a number that only ever goes up, and every write carries that number. The storage layer refuses any write whose number is lower than the highest it has already accepted. The check has to live in the thing being written to, because that's the only place that can notice. You can't ask the stale leader to check, because its whole problem is that it can't learn it was replaced.

A paused leader, fenced off by its token
Node 1 is the leader, with token 4, and pauses for 30 seconds. Node 2 is elected with token 5 (1), writes with it, and storage accepts the write (2). Node 1 wakes up and writes with token 4 (3). Storage has already seen 5, so it refuses that write (4).Node 1 is the leader, with token 4, and pauses for 30 seconds. Node 2 is elected with token 5 (1), writes with it, and storage accepts the write (2). Node 1 wakes up and writes with token 4 (3). Storage has already seen 5, so it refuses that write (4).
The storage refuses the old leader by its number. Node 1 is the leader, with token 4, and pauses for 30 seconds. Node 2 is elected with token 5 (1), writes with it, and storage accepts the write (2). Node 1 wakes up and writes with token 4 (3). Storage has already seen 5, so it refuses that write (4).

This failure belongs in a CAP article because it survives a correct CAP decision. You can choose consistency and build a majority quorum, and still lose data to an old leader that wakes up after a pause. Only the number check in the storage layer stops it.


If you memorise nothing else

CAP classifies operations, not databasesso "we are an AP system" is not an answer
You never chose Ppartitions are imposed, so the choice is two-way
C means linearizabilitynot ACID's C, not serializability
A means "a response", with no time limitwhich is why CAP says nothing about latency
A slow node looks exactly like a partitioned oneso partitions are common, not exotic
CAP governs about 0.008% of your yearPACELC's else branch governs the rest
Linearizability costs one round trip to mid-quorumunder 1 ms in one zone, 55 ms from Mumbai to Singapore
Postgres serializable is not linearizablecheck the property by name, not the ACID label
Causal is the ceiling for staying availableeverything stronger needs coordination
"Eventual" has no time boundmeasure your lag and alert on its p99
Most "strong consistency" needs are read-your-writeswhich is cheap and survives partitions
A compensation can replace a guaranteeairlines oversell on purpose
Detecting a conflict is not resolving itsomebody still decides whose data is lost
A majority stops two leaders being electedonly a fencing token stops a stale one writing

What is expected at each level

Mid-level

Know what the letters mean and do not repeat the triangle.

You should be able to say that partitions aren't optional, and that the real choice is between answering with possibly stale data and refusing to answer. You should know that CAP's C is a specific rule about order, not "the data is correct". And you should see that a like count and a seat reservation have different requirements.

You aren't expected to bring up PACELC, or to price linearizability in round trips. You are expected not to say "we would pick AP" as though it settled something.

Senior

Apply it per operation and state the product consequence.

Split the operations. Walk the list, name the ones that need linearizability, and name the specific outcome each one prevents that can't be undone. Giving a whole service one guarantee is the most common senior-level miss here.

Say what happens during a partition in product language. "Signup returns a retry-able error for the duration" is a design decision. "We choose consistency" is a letter.

Know that read-your-writes exists and is cheap. Reach for it instead of linearizability for the many problems that are about a user seeing their own change.

Don't confuse the three consistencies. If you can say "I mean linearizability, not serializable isolation" without being prompted, that's a strong signal, because most candidates can't.

Staff+

The shift is from choosing a guarantee to removing the need for one.

Reframe to the normal case. The partition branch covers minutes a year, and the latency branch covers every request. Make that point. Then point out that where the replicas live sets almost all of the price of linearizability. That connects the consistency discussion to the replica placement discussion, where it belongs.

Remove the need for coordination. Use commutative operations, idempotency, split resources or compensation. A requirement you removed is cheaper than one you met efficiently, and it stays cheaper.

Design the recovery, not just the partition. If you chose availability, the merge is the real work, and last-write-wins is a decision about whose data to throw away. Saying so is the clearest sign you've run one of these systems rather than read about them.

Scope the guarantee to the smallest thing that needs it. One key for a few minutes, not a service and not a table.

Be able to say what you wouldn't do. You wouldn't label a datastore with a letter. You wouldn't coordinate globally for a value nobody acts on. You wouldn't use linearizability for a problem that read-your-writes solves. You wouldn't call anything "eventually consistent" without a measured lag figure and an alert on it. And you wouldn't pick a conflict resolution strategy by default instead of on purpose.


Sources

  • Seth Gilbert and Nancy Lynch, Brewer's Conjecture and the Feasibility of Consistent, Available, Partition-Tolerant Web Services, ACM SIGACT News 33(2), 2002, pages 51 to 59. This is the proof itself, given for the asynchronous network model, with a discussion of the partially synchronous case. Read it to see how narrow the claim is.
  • Eric Brewer, CAP Twelve Years Later: How the "Rules" Have Changed, IEEE Computer, 2012. The author of CAP explains that "2 of 3" is misleading. Partitions are rare enough that you can usually have both properties, and the choice between consistency and availability can differ between subsystems, and even between operations. The real work is in detecting a partition, in restricting operations during one, and in recovering afterwards.
  • Martin Kleppmann, Please stop calling databases CP or AP, 2015, and the longer A Critique of the CAP Theorem. The point about Postgres serializable snapshot isolation being serializable but not linearizable comes from here. So does the observation that most systems are neither C nor A under CAP's real definitions.
  • Daniel Abadi, Consistency Tradeoffs in Modern Distributed Database System Design: CAP is Only Part of the Story, IEEE Computer 45(2), 2012, pages 37 to 42. PACELC, and the argument that the consistency versus latency tradeoff has shaped real systems more than CAP did.
  • Eric Brewer, Spanner, TrueTime and the CAP Theorem, Google, 2017. Spanner is "technically CP", chooses consistency when a partition does occur, and is "effectively CA" because Google's network makes those events rare enough to sit inside a five nines availability budget.
  • Amazon's DynamoDB developer documentation on read consistency and read capacity units. One read capacity unit buys one strongly consistent read per second, or two eventually consistent ones. The guarantee costs exactly double. And strongly consistent reads are not offered at all on global secondary indexes. Check the current docs rather than this article, since capacity accounting changes.

Spot a mistake, or something unclear? . Or get in touch.

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.