Distributed systems are inherently chaotic. Networks drop packets, servers crash, and data centers lose power. When you replicate data across multiple nodes to survive these failures, you hit a fundamental mathematical wall: the CAP theorem. Understanding CAP and the spectrum of consistency models is not just an academic exercise. It sits at the core of every system design interview. Whether you are designing a financial ledger or a social media feed, your choices around consistency will dictate your database selection, replication strategy, and failover mechanisms.
What it is and why it matters
The CAP theorem, formulated by Eric Brewer in 2000, states that a distributed data store can only simultaneously provide two of the following three guarantees:
- Consistency (C): Every read receives the most recent write or an error. In CAP terms, this means linearizability: the system behaves as if there is only one copy of the data, and all operations occur instantaneously.
- Availability (A): Every request receives a non-error response, without the guarantee that it contains the most recent write. As long as a node is up, it must answer the client.
- Partition Tolerance (P): The system continues to operate despite an arbitrary number of messages being dropped or delayed by the network between nodes.
Why does this matter in interviews? Because interviewers want to see you make deliberate trade-offs based on business requirements. If you are designing UPI Payments, a stale read could mean double-spending money; you must choose CP. If you are designing a Twitter Timeline, a user seeing a slightly outdated like count is perfectly fine; you should choose AP to ensure the system stays fast and responsive.
How it works
To understand the CAP trade-off, let's visualize a simple distributed system with two database nodes. They replicate data to each other to ensure durability. Suddenly, the network link between them breaks. This is a network partition.
In this scenario, Client A writes X = 1 to Node 1. Because of the partition, Node 1 cannot replicate this update to Node 2. Now, Client B connects to Node 2 and asks to read X.
Node 2 faces a dilemma:
- Option 1 (Choose Consistency - CP): Node 2 knows it cannot communicate with Node 1 to verify if it has the latest data. To prevent serving stale data, Node 2 returns an error or blocks the request until the network recovers. The system is Consistent, but not Available.
- Option 2 (Choose Availability - AP): Node 2 serves the request using the old value of
Xit currently holds. The system is Available, but not Consistent (Client B reads stale data).
Beyond CAP: The PACELC Theorem
The CAP theorem has a significant limitation: it only describes what happens during a network partition. But partitions are rare. What happens during normal operations?
Enter the PACELC theorem, an extension of CAP that states:
- If there is a Partition (P): The system must choose between Availability (A) and Consistency (C).
- Else (E): When the system is running normally, it must choose between Latency (L) and Consistency (C).
If you want strong consistency during normal operations, you must wait for data to be replicated to multiple nodes before acknowledging a write to the user. This increases latency. If you want low latency, you must acknowledge the write immediately and replicate in the background, which risks serving stale data (sacrificing consistency).
Consistency Models Compared
Consistency is not a binary switch; it is a spectrum. Here are the main consistency models you will discuss in system design interviews, ranging from strongest to weakest.
| Consistency Model | Description | Trade-offs | Real-World Example |
|---|---|---|---|
| Strong (Linearizable) | Every read returns the absolute latest write. The system behaves as if there is only one node. | High latency, low availability during partitions. | Bank account balances, Distributed locks (Zookeeper). |
| Sequential | Operations appear in the same order to all nodes, though not necessarily instantaneously. | Better latency than strong, but still requires coordination. | Multi-player turn-based games. |
| Causal | Operations that are causally related are seen by every node in the same order. Unrelated operations can be out of order. | Good balance of performance and logical correctness. | Comment threads (replies must appear after the parent comment). |
| Read-Your-Writes | A user will always see their own updates immediately, but other users might see them later. | Requires session stickiness or client-side caching. | Updating your profile picture. |
| Eventual | If no new updates are made, all nodes will eventually return the last updated value. | Lowest latency, highest availability. High risk of stale reads. | YouTube view counts, Instagram likes. |
Implementing Consistency: Quorums
In systems like Cassandra or DynamoDB, you can tune consistency per request using Quorums. A quorum is the minimum number of nodes that must participate in an operation for it to be considered successful.
Let N be the replication factor (total copies of data), W be the write quorum, and R be the read quorum.
To achieve Strong Consistency, you must configure your system such that: W + R > N
This ensures that the set of nodes you write to and the set of nodes you read from will always overlap by at least one node. That overlapping node will have the latest data.
Here is how you might implement a simple write quorum check in code. Notice how the logic attempts to write to all nodes and succeeds as soon as W nodes acknowledge the write.
def write_quorum(nodes, value, W):
success_count = 0
for node in nodes:
try:
if node.write(value):
success_count += 1
except Exception:
continue
if success_count >= W:
return True
return FalseTrade-offs and Failure Modes
Choosing a consistency model introduces specific failure modes that you must handle in your application logic.
1. Split-Brain Problem (CP Systems)
In a CP system, if a network partition divides the cluster in half, both halves might try to elect a new leader, resulting in two active leaders (split-brain). This causes data corruption. To prevent this, CP systems use consensus algorithms like Raft or Paxos, which require a strict majority (e.g., 3 out of 5 nodes) to elect a leader. The minority partition simply stops accepting writes.
2. Conflict Resolution (AP Systems)
In an AP system, during a partition, multiple nodes might accept conflicting writes for the same key. When the network recovers, the system must merge these conflicts. Common strategies include:
- Last Write Wins (LWW): Relying on timestamps. The write with the latest timestamp overwrites the others. (Risk: relies on synchronized clocks, which are notoriously unreliable in distributed systems).
- Vector Clocks: Tracking the causal history of updates. If a conflict is detected, the database returns both versions to the client, forcing the application layer to resolve it (e.g., merging two shopping carts).
- CRDTs (Conflict-Free Replicated Data Types): Specialized data structures that mathematically guarantee eventual consistency without conflicts (often used in collaborative editors).
How it shows up in real systems
Let's look at how these theories apply to standard interview problems.
Designing an E-commerce Shopping Cart
For an e-commerce site like Amazon, availability is king. If a user cannot add an item to their cart because a database node is down, the company loses money. Therefore, shopping carts are typically designed as AP systems. They use eventual consistency. If a partition occurs, the system might temporarily lose track of a deleted item, resulting in the item reappearing in the cart later. The business accepts this trade-off because the user can simply delete it again at checkout.
Designing a Ride-Matching Service (Uber)
When matching a driver to a rider, you cannot assign the same driver to two different riders simultaneously. This requires Strong Consistency (CP). The system must use distributed locks or atomic transactions to ensure that once a driver's state changes to "matched," all subsequent reads reflect this immediately.
Interview questions
Here are the most common questions interviewers ask regarding CAP and consistency, along with model answers.
1. Can a distributed system be CA (Consistent and Available)?
Model Answer: No. In a distributed system, network partitions (P) are unavoidable due to hardware failures, network congestion, or power outages. Because P is a given, you must choose between C and A when a partition occurs. A single-node relational database is CA, but it is not distributed.
2. How do you handle concurrent writes in an eventually consistent system?
Model Answer: When nodes accept concurrent writes, conflicts arise. We can resolve them using Last Write Wins (LWW) based on timestamps, though this risks data loss if clocks drift. A safer approach is using Vector Clocks to detect conflicts and passing both versions to the client application to resolve (like Amazon Dynamo's shopping cart). Alternatively, we can use CRDTs for automatic, conflict-free merging.
3. What is the PACELC theorem and why is CAP not enough?
Model Answer: CAP only dictates the trade-off during a network partition. PACELC extends this to normal operations. It states that even when there is no partition (Else), a system must trade off Latency (L) versus Consistency (C). For example, synchronous replication gives strong consistency but high latency, while asynchronous replication gives low latency but eventual consistency.
4. How does a Quorum guarantee strong consistency in a leaderless database like Cassandra?
Model Answer: By tuning the Write (W) and Read (R) quorums such that W + R > N (where N is the replication factor). This ensures that any read operation will overlap with at least one node that participated in the most recent write operation. The system can then compare timestamps among the R nodes and return the latest value.
5. If you are designing a banking ledger, which CAP properties do you prioritize?
Model Answer: I would prioritize Consistency and Partition Tolerance (CP). In banking, serving stale data (like an outdated balance) can lead to double-spending, which is catastrophic. During a partition, it is better to deny the transaction (sacrifice Availability) than to process an invalid one.
6. How do you implement "Read-Your-Writes" consistency?
Model Answer: I can implement this by routing all of a specific user's read requests to the same primary node where their writes occurred (Session Stickiness). Alternatively, I can cache the user's writes locally on their client device, so the UI instantly reflects the change while the backend asynchronously propagates the update to replicas.
Common mistakes
- Confusing CAP Consistency with ACID Consistency: In ACID (Databases), Consistency means data transitions from one valid state to another based on constraints (like foreign keys). In CAP (Distributed Systems), Consistency means linearizability: every node agrees on the latest data. They are completely different concepts.
- Assuming "Eventual Consistency" means "Immediately Consistent most of the time": While often true in practice, eventual consistency offers zero guarantees on when the data will converge. Under heavy load, replication lag can stretch from milliseconds to minutes. Always design your application to handle stale data gracefully if you choose this model.