01.4 CAP theorem — the fundamental constraint

Mid-level · Fundamental

Core idea

In a distributed system during a network partition (which WILL happen), you must choose between Consistency (every read gets the latest write) and Availability (every request gets a response). You cannot have both.

Mental model

Imagine two bank branches that briefly lose phone contact. Branch A can refuse transactions until contact is restored (C, not A). Branch B can allow transactions and reconcile later (A, not C). A social media feed can afford branch B’s approach. A bank balance cannot.

Why it matters

  • Every database and distributed system makes this choice — you need to know which
  • It explains why there are so many different databases
  • Interviewers will probe: ‘what consistency model does your design use and why?’

What to know

  • CP systems: consistent + partition tolerant (MongoDB, HBase, Zookeeper) — refuse requests during partition
  • AP systems: available + partition tolerant (Cassandra, DynamoDB, CouchDB) — serve possibly stale data
  • CA: only possible without partitions — single-node DB
  • Eventual consistency: all nodes converge to same value eventually (if no new writes)
  • Strong consistency: read always returns latest write

Common traps

  • Saying ‘I’ll use Cassandra’ without knowing it’s AP (eventual consistent)
  • Applying strong consistency everywhere — overkill and slow for most use cases
  • Forgetting that network partitions are not rare — they happen, plan for them

Recognise it

Recognition trigger: Any question about a distributed system → ask yourself ‘what happens if two nodes can’t talk?’ Then decide: can I serve stale data? (use AP) or must I refuse requests? (use CP). Match to requirements.

Practice question

If a user posts a tweet and their follower doesn’t see it for 2 seconds, is that a problem? What about a bank transfer?

Go deeper