Skip to content

Practical software architecture · Part 5 of 10

CAP theorem and consistency models in plain words

During a network partition a system must choose between consistency and availability. Strong and eventual consistency explained with simple examples.

· 2 min read

architecturedistributed-systems

Distributed systems copy data to several machines for speed and resilience. The price is that copies can disagree, at least for a moment. The CAP theorem describes the corner you are backed into when the network misbehaves.

The three letters

  • Consistency: every read sees the latest successful write, as if there were a single copy.
  • Availability: every request to a working node gets a response.
  • Partition tolerance: the system keeps working when the network between nodes breaks.

Networks do fail, so partition tolerance is not optional. The real statement is: during a partition you must choose between consistency and availability.

An example

Two database replicas lose contact with each other. A client writes to one and another client reads from the other.

  • A CP system refuses the read, or the write, until the replicas talk again. It stays correct but some requests fail.
  • An AP system answers anyway, possibly with old data. It stays available but may return a stale value.

When there is no partition, a system can offer both, but there is still a trade-off between latency and consistency, because waiting for every replica to confirm is slower.

Consistency models

  • Strong consistency: after a write completes, every reader sees it. Easy to reason about, costs latency and availability.
  • Eventual consistency: replicas converge if writes stop. Readers may briefly see old values. Fast and available.
  • Read-your-writes: a user always sees their own updates, even if others lag. A useful middle ground.

Choosing by feature, not by system

Different parts of one product can choose differently:

  1. A bank balance or an inventory count that must not oversell: favour consistency.
  2. A like counter, a feed or a search index: eventual consistency is fine.
SQL
-- Strong consistency on a single PostgreSQL primary: the transaction is isolated.
BEGIN;
UPDATE accounts SET balance = balance - 100 WHERE id = 1 AND balance >= 100;
UPDATE accounts SET balance = balance + 100 WHERE id = 2;
COMMIT;

Takeaway

Ask what the business can tolerate when things break: a refused request, or an out-of-date answer. Then pick the model for each feature, and design the user experience around its limits.

A knowledge article, drafted with AI assistance and checked with automated tests. It is general background, not a description of my own experience or of any client's work.

Comments

Leave a comment

No account or email needed. Comments appear after review. A one-way hash of your IP address is kept for 30 days to fight spam, then erased.