Skip to content
Tech Intuition
Tech Intuition

Appearance

Theme

Signal · Dark with amber

Background

Slow stars and the odd comet

Connect

Core concepts · Lesson 7 of 44

Consistency and availability

What the CAP theorem actually says, the consistency models you can choose between, how quorums work, and how to decide which trade-off fits which feature.

ConceptCore11 min readUpdated

  • 1 architecture diagram
  • 1 sequence flow
  • 2 code samples
  • 5 interviewer follow-ups
  • 3 self-checks

Read first: Replication and sharding, Queues and asynchronous work

By the end you will be able to
  • State CAP correctly, as a choice during a network partition, not "pick two of three".
  • Name the common consistency models and give an example where each is enough.
  • Use quorum arithmetic (R + W > N) to reason about reads and writes.
  • Decide per feature whether to favour consistency or availability, and say why.
Prefer to watch? · 16 min video

2 code samples (58 lines), collapsed so the explanation stays in focus.

The moment data lives on more than one machine, you must decide what happens when those machines disagree or cannot talk to each other. Every distributed system answers this somewhere, whether or not its designers say so.

The CAP theorem, stated correctly

The CAP theorem is often summarised as "pick two of consistency, availability, partition tolerance". That wording misleads. Network partitions (messages between nodes being lost or delayed) are not optional: in any real distributed system they will happen. So the real statement is:

  • Consistency (in CAP): every read sees the most recent write, as if there were a single copy of the data (linearizability).
  • Availability (in CAP): every request to a non-failed node eventually gets a non-error response. This is a stricter, all-requests property than the uptime percentage in an SLA, which is also called "availability" (the SLO lesson does the arithmetic of nines and of dependencies in series).
  • Partition tolerance: the system keeps operating despite lost or delayed messages between nodes. A CP system stays up on the side that still has a quorum.

A CP system refuses some requests during a partition rather than risk returning stale or conflicting data. An AP system keeps answering from whichever side it can reach, and reconciles differences afterwards.

Fig. A partition forces the choice: refuse the write, or accept it on both sides
Fig. A partition forces the choice: refuse the write, or accept it on both sides

Refuse and the system stays consistent but is unavailable to one side (CP). Accept on both sides and every client gets an answer, but the replicas now disagree and must reconcile later (AP).

PACELC: the part CAP leaves out

CAP only describes behaviour during a partition. The everyday trade-off is described by PACELC (Abadi, 2012): if there is a Partition, choose between Availability and Consistency; Else (normal operation), choose between Latency and Consistency.

Even with no failures, keeping replicas strongly consistent means waiting for them to confirm, which costs latency, especially across regions. Many "eventually consistent" systems are simply choosing low latency in the normal case.

Consistency models

From strongest to weakest, the ones that come up most:

  • Linearizable (strong). Operations appear to happen in one global order, and a read always returns the latest completed write. Easiest to reason about, most expensive.
  • Sequential. All clients see operations in one agreed order, but that order need not match real time.
  • Causal. Only causally related operations are ordered: if you reply to a comment, nobody sees the reply without the comment. Weaker than sequential and cheaper, and enough for many social features.
  • Read-your-writes. You always see your own updates, even if others lag. Often the minimum users expect.
  • Eventual. If writes stop, all replicas converge to the same value eventually. Says nothing about what you read in the meantime.

These are guarantees about how recent a read is when there are replicas. Isolation levels such as snapshot isolation and serializable are a different axis: they describe what concurrent transactions may see (see transactions and isolation levels).

The practical skill is matching the model to the feature, not choosing one for the whole system.

FeatureWhat it needs
Account balance, inventory at checkoutStrong consistency; wrong answers cost money
Seeing your own profile editRead-your-writes
Comment threadsCausal ordering
Like counts, view counters, feedsEventual is fine
Rate limit countersUsually near-accurate beats unavailable (see rate limiting)

Quorum reads and writes: R, W and N

In leaderless or multi-replica stores, you can tune consistency with three numbers: N replicas hold each item, a write must be acknowledged by W of them, and a read consults R of them.

If R + W > N, every read set overlaps every write set, so a read sees at least one replica with the latest write. For N = 3:

SettingBehaviour
W = 2, R = 2Overlaps (2 + 2 > 3): a read always includes at least one replica holding the latest acknowledged write (with strict quorums); tolerates one node down
W = 3, R = 1Fast reads, but one down node blocks writes
W = 1, R = 1Fast and highly available, but no overlap: stale reads possible

Quorums are not a free lunch: concurrent writes, failed writes and node replacement still create edge cases. They are a tool for reasoning, not a guarantee of linearizability.

HLD

A quorum in motion

With three replicas, writing to two and reading from two means every read overlaps at least one replica that took the latest write.

Fig. N=3, W=2, R=2: reads overlap writes
Fig. N=3, W=2, R=2: reads overlap writes

Conflicts: when two sides both accepted a write

AP systems must reconcile divergent copies.

  • Last write wins (LWW): keep the update with the latest timestamp. Simple, but clocks drift and it silently discards one side's change (see time, clocks and ordering).
  • Version vectors: track causal history so the system can tell "A happened before B" from "A and B were concurrent". They only detect concurrency; the application or a merge rule still has to decide what the merged value is.
  • CRDTs: data structures designed so that concurrent updates converge to the same state on every replica without coordination (counters, sets, some collaborative text). They guarantee convergence by construction, at the cost of restricted operations.

Choosing a consistency level, feature by feature

A useful way to talk about it in an interview:

  1. Ask what is the cost of a wrong answer versus the cost of no answer.
  2. If wrong is worse (money, inventory, uniqueness), choose consistency and accept that some requests fail or slow down during failures.
  3. If unavailable is worse (browsing, feeds, counters), choose availability and design the reconciliation.
  4. Different parts of one product can choose differently.

A single-leader system with consensus-based failover (Raft or Paxos, explained in consensus and leader election) leans CP: during a partition the minority side stops accepting writes. Plain asynchronous replication with naive failover can lose acknowledged writes. Many wide-column and Dynamo-style stores lean AP and let you tune per request.

LLD

Detecting conflicts with a version vector

Last-write-wins hides conflicts by picking a winner. To do better, a system first has to notice that two writes were concurrent: neither writer had seen the other's write. A version vector (the structure behind what are often called vector clocks) does that with one counter per node.

C# · Causality, VersionVector45 lines
using System;
using System.Collections.Generic;
using System.Linq;

public enum Causality { Equal, Before, After, Concurrent }

public sealed class VersionVector
{
    private readonly Dictionary<string, int> _counters;

    public VersionVector() { _counters = new Dictionary<string, int>(); }
    private VersionVector(Dictionary<string, int> counters) { _counters = counters; }

    public int this[string node] => _counters.TryGetValue(node, out int n) ? n : 0;

    /// <summary>The vector after this node accepts a write. Vectors never change in place.</summary>
    public VersionVector Increment(string node)
    {
        var next = new Dictionary<string, int>(_counters);
        next[node] = this[node] + 1;
        return new VersionVector(next);
    }

    /// <summary>The smallest vector that has seen everything either side has seen.</summary>
    public VersionVector Merge(VersionVector other)
    {
        var next = new Dictionary<string, int>(_counters);
        foreach (var kv in other._counters) next[kv.Key] = Math.Max(this[kv.Key], kv.Value);
        return new VersionVector(next);
    }

    public Causality Compare(VersionVector other)
    {
        bool behind = false, ahead = false;
        foreach (string node in _counters.Keys.Union(other._counters.Keys))
        {
            if (this[node] < other[node]) behind = true;
            if (this[node] > other[node]) ahead = true;
        }
        if (behind && ahead) return Causality.Concurrent;
        if (behind) return Causality.Before;
        if (ahead) return Causality.After;
        return Causality.Equal;
    }
}

One version is before another if every counter is less than or equal and at least one is smaller: the later writer had seen the earlier one, so the later value simply replaces it. If each has a counter the other lacks, they are concurrent, a real conflict.

C#13 lines
using System.Diagnostics;

var v1 = new VersionVector().Increment("A");         // A writes: {A:1}
var v2 = v1.Increment("B");                          // B read v1, then wrote: {A:1, B:1}
Debug.Assert(v1.Compare(v2) == Causality.Before && v2.Compare(v1) == Causality.After);    // v2 saw v1: no conflict

var left = v2.Increment("A");                        // A writes again: {A:2, B:1}
var right = v2.Increment("B");                       // B writes again, without seeing A's: {A:1, B:2}
Debug.Assert(left.Compare(right) == Causality.Concurrent);                                // neither saw the other

var resolved = left.Merge(right).Increment("A");     // someone reconciles the two: {A:3, B:2}
Debug.Assert(resolved.Compare(left) == Causality.After && resolved.Compare(right) == Causality.After);
Debug.Assert(left.Compare(left) == Causality.Equal);

Detecting a conflict is only half the job. What to do with it is a product decision, covered in the follow-up below. The cost is metadata that grows with the number of writers, which is why real systems prune or bound it.

Senior depth

What senior interviews ask about consistency and availability

Interviewer follow-upL6If R + W > N, do you get linearizable reads?How to answer

No. The overlap guarantee holds only in the simple case. Sloppy quorums and hinted handoff let writes land on nodes outside the usual replica set. Concurrent writes need a way to be ordered. A write that returned an error may still have reached some replicas, so a later read can return it. Clock-based last-write-wins can discard newer data. Linearizability needs a consensus protocol or additional mechanisms such as read repair with careful versioning; Dynamo-style quorums give tunable, eventual consistency.

Interviewer follow-upL6Why is last-write-wins dangerous?How to answer

It decides by timestamp, and clocks on different machines disagree, so a genuinely later write can lose to an earlier one with a higher timestamp. Concurrent updates are silently dropped instead of merged. Alternatives: version vectors to detect concurrency and keep both values for the application to merge, CRDTs for data that merges naturally, or routing all writes for a key through a single writer.

Interviewer follow-upL7How does a consensus protocol such as Raft avoid two leaders?How to answer

Time is divided into numbered terms. A candidate needs votes from a majority of nodes, and each node votes once per term, so two leaders cannot be elected in the same term. A leader that is cut off from the majority cannot commit new entries, and when it learns of a higher term it steps down. Followers reject messages from lower terms, so a stale leader's writes are ignored.

Interviewer follow-upL6A user saves a profile change and reloads the page, but sees the old value. Why, and what are your options?How to answer

The write went to the leader and the read went to a follower that has not applied it yet: replication lag, which breaks read-your-writes. Options: read a user's own recent writes from the leader (for a short window after a write, or for data only they can change); have the client carry the position of its last write and read only from a replica that has reached it; or pin a user's session to one replica. State which guarantee you are buying and for whom, because sending every read to the leader gives up the read scaling that replicas were added for.

Interviewer follow-upL7Two replicas accept conflicting writes to the same key. What does a system do with the concurrent versions?How to answer

First it must notice they are concurrent, which is what version vectors are for. Then there are three honest answers. Pick a winner by rule, usually the latest timestamp: simple, and it silently loses a write. Keep both versions and hand them to the application to merge, as the Dynamo paper describes. Or use a data type that merges by construction, such as a counter or set designed as a CRDT. Cassandra resolves conflicts with last-write-wins timestamps, while Dynamo-style stores such as Riak can keep both versions as siblings. Choose per field, by what losing a write costs.

Summary

Partitions force a choice between consistency and availability; the rest of the time the trade is latency versus consistency. Pick the weakest consistency model each feature can tolerate, use quorums and conflict resolution to make that choice precise, and justify each decision by the cost of a wrong answer.

Check yourself

Try answering out loud before you reveal each answer.

QuestionState the CAP theorem correctly.Reveal answer

Network partitions will happen, so when one does, a system must choose between consistency (linearizability) and availability. When there is no partition it can offer both.

QuestionWith N = 3, W = 2 and R = 2, why does a read see the latest acknowledged write?Reveal answer

R + W = 4 is greater than N = 3, so every read set overlaps every write set in at least one replica holding the latest write (assuming strict quorums).

QuestionWhich consistency would you choose for an account balance, and for a like counter?Reveal answer

Strong consistency for the balance, because a wrong answer costs money. Eventual consistency is fine for the counter. Decide per feature by comparing the cost of a wrong answer with the cost of no answer.

Lesson 7 of 44

Nice. Lock it in, then keep going.

Up next · Lesson 8Rate limitingThe classic algorithms, why a per-server counter breaks the moment you have more than one server, and how shared state, and a decision about failure, fix it. With an interactive 3D system you can break yourself.

Send a message

It goes straight to my inbox. I usually reply within a few days.