Skip to content
System Design Fundamentals

Lesson 9 of 12 · 20 min

x
9/12

Lesson position in the course — not completion. Use Mark Complete to track finished lessons (saved in this browser).

CAP Theorem & Consistency Models

The CAP theorem states that a distributed system can guarantee at most two of three properties simultaneously: Consistency (every read sees the latest write), Availability (every request gets a response), and Partition tolerance (the system keeps working during network splits). Since partitions are unavoidable in distributed systems, the real choice is between CP (consistent but may reject requests during partitions) and AP (always responds but may return stale data).

In practice, consistency is a spectrum. Strong consistency — every read sees the latest write — is achieved by routing reads through the primary or using a consensus protocol like Raft. Eventual consistency means replicas converge over time but may serve stale reads. Choosing wrong causes real bugs: an e-commerce site using eventual consistency for inventory may oversell stock; a social feed that is eventually consistent for likes is perfectly acceptable.

Before
Strong consistency — always correct, primary only
1// All reads go to primary — always fresh2// Primary is a bottleneck at high read volume3async function getBalance(accountId: string) {4  return primaryDb.query(5    'SELECT balance FROM accounts WHERE id = $1',6    [accountId]7  );8}9// Correct for financial data — never use a replica
After
Eventual consistency — fast reads, may lag briefly
1// Reads go to replica — may be 100ms behind primary2// Acceptable for social content, not for money3async function getUserFeed(userId: string) {4  return replicaDb.query(5    'SELECT * FROM posts WHERE ...',6    [userId]7  );8}9// Rule: strong consistency for money and inventory,10//       eventual consistency for feeds and analytics

Check your understanding

  • Under partition, what does CP vs AP choose?Show answer

    Answer

    CP: prefer consistency (may error/reject). AP: prefer availability (may serve stale).
  • Give one domain for strong consistency.Show answer

    Answer

    Balances, inventory reservation, or anything where stale reads cause real money/stock errors.
  • Give one domain for eventual consistency.Show answer

    Answer

    Social feeds, like counts, or analytics where brief lag is acceptable.
Previous

Progress is saved in this browser.

Next Lesson