CAP and eventual consistency

CAP
Consistency, Availability, Partition tolerance

Senior Frequently asked 5 min

On this page

The question

What does the CAP theorem say, and what does it mean in practice?

30-second answer

CAP says that when the network partitions, a distributed data store must choose between consistency, every read sees the latest write, and availability, every request to a working node gets an answer. It cannot have both during the partition. Partitions are not optional in real networks, so the practical choice is CP, refusing what you cannot confirm, or AP, answering with possibly stale data.

Understand it

Partition the network, then choose C or A

Explore

No partition: A replicates the new balance to B and C, so the read on C returns 50. Consistent and available; the price is replication latency.

View as text

Two zones. Zone 1 holds replicas A and B; zone 2 holds replica C. Client 1 sets a balance from 100 to 50 on A, and client 2 reads it on C. Each replica shows the balance it holds, and a line shows what the read returns.

No partition: A replicates the new balance to B and C, so the read on C returns 50. Consistent and available; the price is replication latency.

Partition, consistency first: C cannot reach a majority, so it refuses the read. No stale answer, but zone 2 gets errors.

Partition, availability first: C answers from its own copy, 100. Every zone keeps working, but the reader sees an old balance.

The partition healed: C syncs from the majority and answers 50 again. While cut off, it refused rather than lie.

The partition healed: C receives the missed write and converges to 50. Readers saw 100 for a while: eventual consistency.

Two zones. Zone 1 holds replicas A and B; zone 2 holds replica C. Client 1 sets a balance from 100 to 50 on A, and client 2 reads it on C. Each replica shows the balance it holds, and a line shows what the read returns.

No partition: A replicates the new balance to B and C, so the read on C returns 50. Consistent and available; the price is replication latency.

Partition, consistency first: C cannot reach a majority, so it refuses the read. No stale answer, but zone 2 gets errors.

Partition, availability first: C answers from its own copy, 100. Every zone keeps working, but the reader sees an old balance.

The partition healed: C syncs from the majority and answers 50 again. While cut off, it refused rather than lie.

The partition healed: C receives the missed write and converges to 50. Readers saw 100 for a while: eventual consistency.

Takeaway: A network partition will happen, so the real choice is what a cut-off replica does: refuse to answer, staying consistent, or answer with what it has, staying available. Without a partition you can have both.

CAP during a partition, and the latency trade-off without oneIf the network is partitioned, a system chooses between consistency, refusing some requests, and availability, answering with possibly stale data. If there is no partition, it still chooses between low latency and consistency, which is the else part of PACELC.YesConsistencyAvailabilityNo, elseLatencyConsistencyNetworkpartition?Consistency oravailability?CP: refuse what youcannot confirmAP: answer, maybewith stale dataLatency orconsistency?Async replicas:fast, may lagSync replicas orquorum: slower
CAP during a partition, and the latency trade-off without oneIf the network is partitioned, a system chooses between consistency, refusing some requests, and availability, answering with possibly stale data. If there is no partition, it still chooses between low latency and consistency, which is the else part of PACELC.YesConsistencyAvailabilityNo, elseLatencyConsistencyNetworkpartition?Consistency oravailability?CP: refuse what youcannot confirmAP: answer, maybewith stale dataLatency orconsistency?Async replicas:fast, may lagSync replicas orquorum: slower
CAP during a partition, and the latency trade-off without one

In code

// 3 replicas. QUORUM is 2. A write to 2 and a read from 2 must share a replica: 2 + 2 > 3.
session.execute(SimpleStatement.newInstance(
        "UPDATE accounts SET balance = ? WHERE id = ?", 50, id)
    .setConsistencyLevel(DefaultConsistencyLevel.QUORUM));

Row row = session.execute(SimpleStatement.newInstance(
        "SELECT balance FROM accounts WHERE id = ?", id)
    .setConsistencyLevel(DefaultConsistencyLevel.QUORUM)).one();   // sees 50

// ONE + ONE = 2, not more than 3: faster, answers in a partition, may return 100
Tunable consistency in Cassandra: quorum reads and writes overlap
@Entity
class Account {
    @Id UUID id;
    long balance;
    @Version long version;          // UPDATE ... WHERE id = ? AND version = ?
}

@Transactional
void withdraw(UUID id, long amount) {
    Account a = accounts.findById(id).orElseThrow();
    if (a.balance < amount) throw new InsufficientFunds(id);
    a.balance -= amount;            // a concurrent withdraw makes this commit fail with
}                                   // ObjectOptimisticLockingFailureException: retry it
Inside one database, optimistic locking keeps concurrent writes consistent
// Wrong: the replica may be a second behind, so the user sees the old address
customers.updateAddress(id, address);                 // goes to the primary
 Wrong return replicaReader.findCustomer(id);                // goes to a read replica

// Right: answer from what the primary just wrote
Customer saved = customers.updateAddress(id, address);
 Right return saved;
Reading your own write from a lagging replica
A quorum write and read with three replicasThe client writes balance 50, and two of three replicas acknowledge, which is a quorum. A later quorum read asks two replicas; at least one of them has the write, and the newest value, 50, wins.Replica 3Replica 2Replica 1Clientwrite 50write 50okok, quorumreadread50, newer100, older
A quorum write and read with three replicasThe client writes balance 50, and two of three replicas acknowledge, which is a quorum. A later quorum read asks two replicas; at least one of them has the write, and the newest value, 50, wins.Replica 3Replica 2Replica 1Clientwrite 50write 50okok, quorumreadread50, newer100, older
A quorum write and read with three replicas

Solve it

Choose the consistency for a bank balance and a like counter

A banking app shows each account’s balance and lets users like posts in a community feed. Both run in two regions for availability. The team asks whether to make everything strongly consistent, or everything eventually consistent. Decide per piece of data and explain how you would build each.

  1. Ask what a stale or lost value costs. A stale balance can let a user overdraw: real money. A like count off by three for a second costs nothing.
  2. Balance: consistency first. Keep each account in one strongly consistent store, change it in a transaction with a lock or version check, and accept that a cut-off region refuses withdrawals.
  3. Likes: availability first. Accept likes in any region, append them as events, and update the count asynchronously. Counts converge after the partition heals.
  4. Mind the user. After a withdrawal, show the balance the write returned, not a replica’s copy, so users read their own writes.
  5. Check. Cut the network between regions in a test: withdrawals in the cut-off region fail cleanly, and likes keep working and converge when it heals.
@Transactional
Balance withdraw(UUID accountId, long amount) {
    Account a = accounts.findByIdForUpdate(accountId);        // SELECT ... FOR UPDATE on the primary
    if (a.balance() < amount) throw new InsufficientFunds(accountId);
    return accounts.save(a.debit(amount)).balance();          // the user sees this value
}

@KafkaListener(topics = "posts.liked")
void onLike(PostLiked e) {
    likeCounts.increment(e.postId());                         // any region, converges later
}
One service locks the balance; another counts likes from events

How to answer

  • Consistency in CAP means linearizability, not the C of ACID (atomicity, consistency, isolation, durability).
  • Without a partition, a system can be both consistent and available.
  • Examples: ZooKeeper, etcd and a single primary database lean CP; Cassandra and DynamoDB lean AP, tunable per query.
  • The choice can differ per operation, not just per system.

Common mistakes

  • Saying you pick any two of the three, as if a system could give up partition tolerance. A network that never partitions does not exist.
  • Calling a system that loses data in a failover consistent, or one that returns errors available.

Follow-up questions

What is the difference between strong and eventual consistency?

With strong consistency, once a write is acknowledged every later read, from any node, returns it, as if there were one copy. With eventual consistency, replicas may disagree for a while, but if writes stop they converge to the same value. Strong costs latency and availability, since replicas must coordinate; eventual is fast and survives partitions, but readers can see old data.

  • Between services with their own databases, eventual consistency through events is the norm.
  • Read-your-writes and monotonic reads are useful middle grounds.
  • Conflicting concurrent writes need a resolution rule, such as last write wins or a merge.

See it in the infographic: Partition the network, then choose C or A

How do quorum reads and writes give strong consistency in a replicated store?

With N replicas, a write waits for W acknowledgements and a read asks R replicas. If R plus W is greater than N, every read set overlaps every write set, so at least one replica in the read has the latest write, and the newest version wins. With N of 3, QUORUM writes and reads use 2 and 2. Lower values are faster and more available, but may read stale data.

  • Cassandra and DynamoDB let you choose the level per query.
  • A quorum needs a majority, so the minority side of a partition cannot serve quorum requests.
  • Overlapping sets alone are not linearizable without care for concurrent writes and repairs.

See it in the infographic: Partition the network, then choose C or A

In a microservices system that is eventually consistent, how do you keep users from being confused?

Let users read their own writes: answer a command with the state it produced, or read from the primary for that user right after a write. Show pending states honestly, such as "payment processing", instead of a wrong final value. Return 202 with a link to poll, or push an update when the read model catches up. Keep the lag small and measure it.

  • Version numbers let a client wait until a read model reaches the version it wrote.
  • Monitor consumer lag; it is the size of the inconsistency window.
  • Design the business process to tolerate delay, as banks do with pending transactions.

See it in the infographic: Partition the network, then choose C or A

What does PACELC add to CAP?

It covers the normal case. If there is a Partition, choose Availability or Consistency; Else, choose Latency or Consistency. Even with a healthy network, waiting for replicas to confirm a write costs latency, so systems with asynchronous replicas trade consistency for speed every day, not only during failures.

Check yourself

1. During a partition, a CP system's replica is cut off from the majority. A client asks it to read a balance. What happens?
Show answers
  • It refuses or times out, because it cannot confirm the latest value: Correct. Consistency first: no answer rather than a possibly stale one.
  • It returns its own copy, which may be stale: Incorrect. That is what an AP system does.
  • It becomes the new majority: Incorrect. One replica out of three cannot be a majority.
2. A store has 3 replicas. Which read and write sizes guarantee that every read sees the latest acknowledged write?
Show answers
  • Write to 2, read from 2: Correct. 2 + 2 > 3, so the read and write sets always share a replica.
  • Write to 1, read from 1: Incorrect. 1 + 1 is not more than 3; the read may miss the write.
  • Write to 1, read from 2: Incorrect. 1 + 2 is not more than 3; both read replicas may lack the write.