CAP and Consistency

What CAP says, the consistency guarantees users can see, quorums, conflict resolution, and how to state the consistency each feature needs.

18 minLesson 1 of 8
On this page
  1. Replication lag between leader and replicas
  2. What the CAP theorem says
  3. Consistency models as users see them
  4. Quorums
  5. Conflict resolution
  6. Failure modes and decisions interviewers ask about
  7. In the interview
  8. What to practise next

When data is stored on more than one machine, the copies can disagree for a short time, and a consistency model states what a read is allowed to return after a write. The CAP theorem describes the choice you face when the network between the copies fails: you either refuse some requests or answer with data that may be out of date.

Without this distinction a system gets one setting for everything. If every read goes to the leader, distant users wait on every request. If every read goes to the nearest replica, a user can save a change and then see the old value, and two users can claim the same username.

Replication lag between leader and replicas

The leader accepts writes and sends them to the replica asynchronously, so the replica can lag behind.Users in East to App East; Users in West to App West; App East to Leader database (reads, writes); App West to Replica database (reads); App West to Leader database (writes); Leader database to Replica database (replication), asynchronous.Users in EastUsers in WestApp EastApp WestLeader databaseReplica databasereads, writesreadswritesreplication

request and replyasynchronous message

The leader accepts writes and sends them to the replica asynchronously, so the replica can lag behind.

Most systems start like this: one leader takes all writes, and replicas serve reads. Replication is usually asynchronous, so the leader acknowledges a write before the replicas have it, and the replicas lag by milliseconds or, under load, by seconds. Every guarantee below is a statement about what a reader may see during that gap.

What the CAP theorem says

The statement

The theorem is about three properties. Consistency here means linearizability: every read returns the result of the latest completed write, as if there were a single copy of the data. Availability means every request sent to a node that is working receives a non-error response. Partition tolerance means the system keeps operating when the network splits the nodes into groups that cannot talk to each other.

Networks do fail, so partition tolerance is not optional, and while a partition lasts each operation has to pick one of two behaviours. A CP operation refuses the request, or waits, on the side that cannot confirm it has the latest data. An AP operation answers from whatever the node has, which may be stale, and accepts that writes made on the two sides of the split may conflict later.

What it does not say

When the network is healthy you can have both consistency and availability. The theorem is also not a rule that you pick any two of three properties, because partition tolerance is not something you can give up. It also does not label a database as CP or AP for good: the choice is made per operation, and many databases let you set it per request.

The trade-off when there is no partition

Partitions are rare, but the trade-off between latency and consistency applies to every request. This is the second half of the PACELC rule: if there is a partition, choose availability or consistency, and else, choose latency or consistency. A strongly consistent write waits for other replicas, and across continents each write pays a round trip of around 100 ms. A write acknowledged after updating only the local copy is faster and weaker.

Consistency models as users see them

Each model is described by what a user notices when it is missing.

Strong consistency (linearizability)

Once a write has been acknowledged, every later read from any client sees it. The system behaves as if there were one copy that is updated instantly. This is what makes a conditional write safe: if two people try to book seat 14C with "book only if free", exactly one of them succeeds. It is built by sending operations through a single leader or by requiring a majority of replicas to agree on each one.

The cost is latency, because a request waits for the leader or a majority, and availability, because the side of a partition that cannot reach them must refuse requests. It is therefore used for a small set of data such as balances, inventory and unique names.

Read-your-writes consistency

A user always sees their own changes, even if other users still see the old data for a moment. Without it, a user saves a new bio, the page reloads, and the old bio appears because the read went to a replica that has not received the write yet.

There are two common ways to provide it. One is to send a user's reads to the leader for a few seconds after that user writes. The other is to remember the log position of the user's last write and read only from a replica that has reached it.

Monotonic reads

A user who has seen a value never sees an older one afterwards. Without this guarantee, a user refreshes a page, sees a comment, refreshes again and the comment is gone, because the second request was served by a replica that is further behind than the first.

The usual fix is to route each user to the same replica, for example by hashing the user id.

Eventual consistency

Eventual consistency means that if writes stop, all copies converge to the same value after some time. Before that a read can return anything, so a like count may show 42 and then 41. It is the fastest model, because any replica answers without talking to the others. It suits counters, feeds and search results.

Replica lag, then a partitionUse the arrows or ← → keys
  1. Replica lag, then a partition, step 1Ben (East) to App East; App East to Leader DB; Ana (West) to App West; App West to Replica DB (reads); App West to Leader DB (writes); Leader DB to Replica DB (replicate), asynchronous.Ben (East)App EastLeader DBbio v2Ana (West)App WestReplica DBreadswritesreplicate
    leader
    v2
    replica
    v1

    1Ana saves a new bio. Writes always go to the leader, so App West sends the write across regions.

  2. Replica lag, then a partition, step 2Ben (East) to App East; App East to Leader DB; Ana (West) to App West; App West to Replica DB (reads); App West to Leader DB (writes); Leader DB to Replica DB (replicate), asynchronous.Ben (East)App EastLeader DBAna (West)App WestReplica DBreadswritesreplicate
    leader
    v2
    replica
    v1

    2The leader commits and acknowledges. Replication is asynchronous, so the acknowledgement does not wait for the West replica.

  3. Replica lag, then a partition, step 3Ben (East) to App East; App East to Leader DB; Ana (West) to App West; App West to Replica DB (reads); App West to Leader DB (writes); Leader DB to Replica DB (replicate), asynchronous.Ben (East)App EastLeader DBAna (West)downApp WestReplica DBstill v1readswritesreplicate
    leader
    v2
    replica
    v1

    3Ana refreshes the page before replication arrives. The replica still holds the old bio, so read-your-writes is broken.

  4. Replica lag, then a partition, step 4Ben (East) to App East; App East to Leader DB; Ana (West) to App West; App West to Replica DB (reads); App West to Leader DB (writes); Leader DB to Replica DB (replicate), asynchronous.Ben (East)App EastLeader DBAna (West)App WestReplica DBreadswritesreplicate
    leader
    v2
    replica
    v1

    4To fix this, the app reads from the leader for a few seconds after Ana writes. She now sees v2, and other users keep reading the replica.

  5. Replica lag, then a partition, step 5Ben (East) to App East; App East to Leader DB; Ana (West) to App West; App West to Replica DB (reads); App West to Leader DB (writes); Leader DB to Replica DB (replicate), asynchronous.Ben (East)App EastLeader DBAna (West)App WestReplica DBreadswritesreplicate
    leader
    v2
    replica
    v2

    5Replication catches up and both copies hold v2. This convergence is what eventual consistency promises.

  6. Replica lag, then a partition, step 6Ben (East) to App East; App East to Leader DB; Ana (West) to App West; App West to Replica DB (reads); App West to Leader DB (writes); Leader DB to Replica DB (replicate), asynchronous.Ben (East)App EastLeader DBAna (West)App West503, retry laterReplica DBreadswritesreplicate
    leader
    v2
    replica
    v2

    6Now the link between the regions fails and Ana's next write cannot reach the leader. The system can refuse it (consistency) or store it locally and merge later (availability). This design refuses.

1 / 6

Quorums

Stores without a single leader, such as Dynamo-style databases, write each value to several replicas and use a quorum to decide when an operation counts. With N replicas, a write succeeds when W of them acknowledge it, and a read asks R of them and takes the newest value it receives. If R + W > N, every read set shares at least one replica with every write set, so a read reaches at least one replica that has the latest acknowledged write. With N = 3, W = 2 and R = 2, 2 + 2 = 4 is greater than 3.

A high W with a low R makes reads fast and writes slow, and the reverse makes writes fast.

A quorum is not the same as linearizability, and the interviewer may test this. Two concurrent writes can arrive at different replicas in different orders. A write that fails halfway can leave its value on some replicas and still be returned by a later read. A sloppy quorum, which accepts writes on other reachable nodes when some of the right replicas are down, weakens the guarantee further. The accurate claim is that quorum reads usually see the latest acknowledged write, not that quorums give strong consistency.

Conflict resolution

Conflicts occur when two replicas accept writes to the same item without seeing each other, for example on both sides of a partition. A system that accepts such writes has to decide what the final value is, and there are three common approaches.

Last write wins

Each write carries a timestamp, and the replica keeps the value with the latest one. The problem is that it silently discards the other write: if two users edit the same document field, one edit disappears with no error. Clocks on different machines also differ, so the write that is "last" may have happened first. Use it only where losing an update is acceptable, such as a "last seen" time.

Version vectors

A version vector stores one counter per replica together with the value. When a replica updates an item it increments its own counter. When two versions meet, the system compares the vectors: if every counter in one is at least as large as in the other, the first version is newer and replaces the second. If neither dominates, the writes were concurrent, and the system keeps both values as siblings instead of choosing one. The metadata grows with the number of writers, and the siblings still have to be resolved.

Merging

The siblings can be resolved by application code that knows the data. A shopping cart can be merged by taking the union of the items from both versions, which loses no additions but may bring back a removed item. A counter type designed for merging, called a CRDT, always converges to the sum of the increments made on every replica. Merging needs a rule for each kind of data, and data such as a balance that may never go below zero cannot be merged safely and needs strong consistency.

Summary of the consistency models
OptionGood atBad atPick it when
StrongA read never returns stale data, and uniqueness rules hold.Writes wait for a leader or a majority, and the minority side of a partition refuses requests.Money, inventory, bookings and unique names.
Read-your-writesIt fixes the most visible form of staleness at a low cost.Other users can still see old data.Profiles, settings and a user's own posts.
Monotonic readsUsers never see data move backwards between requests.It needs sticky routing, which breaks when a replica fails.Any page the user refreshes often.
Eventual Usual defaultIt is the fastest model, and replicas answer locally.Reads can be stale and briefly contradict each other.Counts, feeds, recommendations and search.

Failure modes and decisions interviewers ask about

Choosing the consistency for each feature

A feature needs strong consistency when a stale read lets two users break a rule between them, such as claiming a seat, registering a unique username or withdrawing from a balance that may not go below zero. It can use eventual consistency, usually with read-your-writes, when being briefly behind has no lasting effect, as with view counts, feed order and search results.

Split brain after a failover

If the West region promotes its replica to leader because it cannot reach the East leader, the East leader may still be alive, and now two leaders accept writes. The data diverges and has to be reconciled by hand. Promotion should require a majority vote with voters in at least three sites; consensus and leader election covers how.

Writes lost during an asynchronous failover

If the leader dies, the promoted replica is missing the writes from the last moments, even though users were told they succeeded. For payments, replicate synchronously to at least one replica before acknowledging and accept the latency. For likes, losing a few seconds of writes is acceptable.

In the interview

Bring up consistency when you add replicas, a cache or a second region, or when two users can race for the same thing. Do not label the whole system "AP" or "CP". State what each feature needs and why, for example: "Seat booking must be strongly consistent, because two people paying for one seat is the failure we cannot allow, while the seat map can be a few seconds stale."

Questions to expect:

  • "Is your database CP or AP?" The answer depends on the operation, and many databases let you configure it for each request. Say which operations refuse during a partition, such as payments, and which serve stale data, such as the feed.
  • "How do you make sure users see their own writes?" Read from the leader for a few seconds after the user writes, or remember the position of the user's last write and read only from a replica that has reached it.
  • "If W + R > N, is the store linearizable?" No. Reads will usually see the latest acknowledged write, but concurrent writes, partial failures and sloppy quorums can still return stale or conflicting data.
  • "Two replicas accepted different writes to the same record. What now?" Last write wins is simple but drops one write and depends on clocks. Version vectors detect that the writes were concurrent, and the application then merges them. Data that cannot be merged should go through a single leader instead.
Consistency per featureStrong answer
Interviewer

Your design has a leader and replicas in two regions. Is it consistent?

You

It depends on the feature. Usernames and payments go to the leader, so they are strongly consistent. The feed and like counts read from local replicas, and a second of lag does not matter there. After a user posts, I send that user's reads to the leader for ten seconds so they see their own post.

Interviewer

What happens if the two regions lose contact?

You

Reads keep working in both regions. Writes in the region without the leader return a retryable error until the link comes back, which is the right behaviour for payments. For likes I could queue the writes locally and apply them afterwards.

Quick check

A leaderless store has N = 5 replicas and W = 2. What is the smallest R that makes every read overlap the latest acknowledged write?

Two replicas each accepted a write to the same record during a partition. Version vectors show that neither version is newer than the other. What does the system know?

What to practise next

Read Transactions and Isolation for concurrent writers on a single database, then Design Ticket Booking to see consistency chosen for each feature.