# Consistency models

> Linearizable, sequential, causal and eventual consistency, from strongest to weakest.

Concept · Consistency & coordination · https://levelcode.org/concepts/consistency-models

A consistency model is a contract about what a read may return when data is replicated. Stronger models allow fewer possible results; they're easier to program against and more expensive to provide.

## From strongest to weakest

**Linearizable (strong).** The system behaves as if there were one copy and each operation took effect at a single instant between its start and finish. Once a write completes, every later read anywhere returns it (or something newer). Needed for uniqueness (usernames, seats), locks and leader election, and balances.

**Sequential.** All clients see all operations in the same order, consistent with each client's own order — but that order needn't match real time, so reads can be stale.

**Causal.** Operations that could have influenced each other (a reply and the message it answers) are seen in that order by everyone; unrelated operations may be seen in different orders. About the strongest model that can remain available during partitions.

**Session guarantees.** Per-client promises layered on weaker models:

- *Read your writes:* you see your own updates.
- *Monotonic reads:* you never see time go backwards.
- *Monotonic writes* and *writes follow reads:* your operations apply in a sensible order.

**Eventual.** If writes stop, replicas converge. No promise about what reads return in the meantime, or how long convergence takes.

## Choosing

| Operation | Typical requirement |
|---|---|
| Claim a username, reserve a seat, decrement stock | Linearizable |
| Transfer money | Linearizable within a transaction |
| See my own profile edit | Read your writes |
| Comment threads | Causal |
| Like counts, view counts, "online" status | Eventual |

Keep the linearizable core small and put it on a store that provides it properly (a single leader, or consensus). Fix most user-visible anomalies with session guarantees ([replication lag anomalies](https://levelcode.org/concepts/replication-lag)).

## A common trap

"Read, check, then write" on a weakly consistent store races: two clients read stock = 1 and both buy. Use an atomic conditional write on the authoritative copy (`UPDATE … WHERE stock > 0`). See [CAP theorem](https://levelcode.org/concepts/cap-theorem) and [PACELC](https://levelcode.org/concepts/pacelc).
