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:
- A bank balance or an inventory count that must not oversell: favour consistency.
- A like counter, a feed or a search index: eventual consistency is fine.
-- 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.
Comments