System Design Fundamentals

Lesson 9 of 12 · 20 min

x
75%

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
// All reads go to primary — always fresh
// Primary is a bottleneck at high read volume
async function getBalance(accountId: string) {
  return primaryDb.query(
    'SELECT balance FROM accounts WHERE id = $1',
    [accountId]
  );
}
// Correct for financial data — never use a replica
After
Eventual consistency — fast reads, may lag briefly
// Reads go to replica — may be 100ms behind primary
// Acceptable for social content, not for money
async function getUserFeed(userId: string) {
  return replicaDb.query(
    'SELECT * FROM posts WHERE ...',
    [userId]
  );
}
// Rule: strong consistency for money and inventory,
//       eventual consistency for feeds and analytics

Key Takeaway

Choose strong consistency for financial and inventory data; accept eventual consistency for social, content, and analytics where brief staleness is tolerable.

PreviousNext Lesson