SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
  • Scalability
  • Availability
  • Reliability
  • Single Point of Failure (SPOF)
  • Latency vs Throughput vs Bandwidth
  • Consistent Hashing
  • CAP Theorem
  • Fault Tolerance and Redundancy
  • Failover
  • Stateless vs Stateful
  • Concurrency vs Parallelism
  • Capacity Planning
  • Back Pressure
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
Part 6: Distributed Systems
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/Foundations/Core Concepts

CAP Theorem

When the network breaks, a distributed system must choose: stay consistent or stay available.

⏱ 14 min readIntermediateMust KnowInterview FavouriteHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

The CAP theorem says a distributed data system cannot promise all three of these at the same time when the network breaks:

  • Consistency: everyone sees the same, latest data.
  • Availability: every request gets an answer.
  • Partition tolerance: the system keeps working even if the network between machines breaks.

Networks do break, so partition tolerance is not optional. The real choice is: when a partition happens, do we choose Consistency (CP) or Availability (AP)?

02Concept: What is it?

In a distributed system, data is stored on many machines (copies, called replicas). The machines talk over a network. Sometimes that network fails between some machines. This is called a partition.

🔄Consistency (C)
Every read gets the most recent write, or an error. All copies look the same to the user.
🟢Availability (A)
Every request to a working node gets a real answer (not an error), though it may not be the latest.
✂️Partition tolerance (P)
The system keeps running even when messages between nodes are lost or delayed.
🧠The real meaning
CAP does not mean "pick any 2 of 3" all the time. When the network is fine, you can have both C and A. The trade-off only appears during a partition. Then you must give up one of C or A.
⚠️This C is not the database ACID C
In CAP, consistency means all nodes agree on the latest value (also called linearizability). In ACID it means data follows the rules of the database. They are different.

Why P is not a choice

If your data is on more than one machine, messages can be lost, cables break and servers pause. You cannot buy a network that never fails. So any real distributed system must handle P. That leaves CP or AP.

03Real-Life Example

🍵Two bank branches with a broken phone line
A bank has two branches, A and B. They keep the same account balance and tell each other about every change by phone. Suddenly the phone line is cut. A customer comes to Branch A and wants to withdraw money. What should the branch do?
Choose Consistency (CP)
Be safe
  • Branch A says: "Sorry, our system is down. Come back later."
  • No wrong balance is ever shown
  • But the customer gets no service (not available)
Choose Availability (AP)
Be helpful
  • Branch A serves the customer using its own copy
  • Customer is happy right now
  • But Branch B may not know about it, so balances differ until the line is fixed
A partition
🏦Branch Abalance = 100
↔✂️ cut
🏦Branch Bbalance = 100
The link between the two nodes is cut. Each side must decide what to do.
Bank branches
Software system
A branch
A database node (replica)
The phone line
The network between nodes
The phone line is cut
A network partition
Refuse to serve until reconnected
CP: stay consistent, lose availability
Serve using the local copy
AP: stay available, risk stale data
Branches compare notes later
Eventual consistency

04Why Do We Need It?

CAP is a way of thinking. It helps us choose the right database and design for each feature.

🎯Choose a database
Some databases lean CP, some lean AP. You must know which one you need.
🧠Set honest promises
You cannot promise perfect data and 100% uptime during a network break.
💥Plan for failure
Decide ahead what the system does when nodes cannot talk.
💬Talk with the business
Is showing old data OK? Or is it better to show an error?
🧪Avoid bad surprises
No more "why did two users see different balances?" during an outage.
🎤Interviews
It is one of the most asked system design ideas.
When the network breaks, you cannot have both perfect agreement and always answering. Choose on purpose.

05Where Do We Use It?

When we lean CP (correctness first)

💳Payments and banking
A wrong balance is worse than a short delay.
🎟️Seat and ticket booking
Never sell the same seat twice.
📦Stock and inventory counts
Do not oversell the last item.

When we lean AP (always answer)

📱Social feeds and likes
A slightly old like count is fine.
🛒Shopping cart
Let users add items, fix conflicts later.
🎬Video views, recommendations
Old data is okay. Downtime is not.

06Types / Parts / How It Works

The three combinations

CAP triangle
🔺Pick for your design
CPConsistent and partition tolerant
APAvailable and partition tolerant
CAOnly works with no partitions (one machine)
CP: error instead of stale data AP: answer, maybe stale CA: not real for distributed systems
In a real distributed system P is always required, so the practical choice is on the CP or AP side.
TypeDuring a partitionYou getYou give upExamples (typical)
CPRefuses some requestsCorrect, latest dataAvailabilitySystems built on consensus: ZooKeeper, etcd, HBase, MongoDB (default settings)
APKeeps answeringAlways respondsLatest data (stale reads)Cassandra and DynamoDB (default settings), CouchDB
CANot possible once data is on many machinesA single node databasePartition toleranceA single-server SQL database
📝Note
Many databases can be tuned either way (for example with read and write settings). Treat the examples as typical defaults, not fixed labels.

What happens after the partition? Eventual consistency

AP systems usually promise eventual consistency: if nobody writes for a while, all copies will become equal. Conflicts are solved with rules such as last write wins, version numbers (vector clocks) or merge types (CRDTs).

Consistency levels, from strongest to weakest
StrongAlways the latest
→↓
Read-your-writesYou see your own changes
→↓
EventualEqual after some time

PACELC: CAP when there is no partition

CAP only talks about partitions. PACELC adds more: if there is a Partition, choose Availability or Consistency; Else (normal times), choose Latency or Consistency. Waiting for every replica to agree makes writes slower. So even on a good day we trade speed for correctness.

VisualizerCut the networkPick CP or AP, cut the link, then write on one node and read on the other.
When the network breaks, we choose...
Network between nodes
🗄️Node Avalue = v1
↔copies sync
🗄️Node Bvalue = v1
Last request answered?
Yes
Availability
Do both copies agree?
Yes
Consistency
Mode
CP
Both copies hold v1. Try a write on Node A, then a read on Node B. Then cut the network and try again.

07How to Use It / Steps / Implementation

How to decide in a design

  1. 1
    Ask: what if two copies disagree?
    Is a wrong answer dangerous (money, seats) or just a little old (likes)?
  2. 2
    Choose CP or AP per feature
    One product can use both. Payments CP, feed AP.
  3. 3
    If CP
    Use quorum or consensus (Raft, Paxos). Return an error or wait when a majority is not reachable.
  4. 4
    If AP
    Accept writes on any node. Resolve conflicts later (last write wins, merge, or version numbers).
  5. 5
    Tune the knobs
    Many databases let you set how many replicas must answer for a read or write (a quorum).
  6. 6
    Test failures
    Cut the network on purpose in a test and see what users experience.
💡Quorum in one line
With N copies, if you write to W of them and read from R of them, and R + W > N, a read always touches at least one copy with the latest write. Example: N = 3, W = 2, R = 2.
Quorum, N = 3, W = 2, R = 2
3 copies
Copy 1new value ✓
Copy 2new value ✓
Copy 3old value
Write goes to 2 of 3. Read asks 2 of 3. The two sets must overlap, so the read sees the latest write.

08Key Terms to Know

TermMeaning in easy words
Distributed systemMany computers working together as one system.
ReplicaA copy of the data on another machine.
PartitionA network failure that stops some nodes from talking to others.
Consistency (CAP)Every read returns the latest write (or an error).
Availability (CAP)Every request to a working node gets a non-error answer.
Strong consistencyAfter a write, everyone sees it right away.
Eventual consistencyCopies become equal after some time if writes stop.
Stale readReading an old value.
QuorumThe minimum number of nodes that must agree. Usually a majority.
ConsensusA way for nodes to agree on one value (Raft, Paxos).
Split brainTwo parts of a system both think they are in charge after a partition.
PACELCCAP plus the latency vs consistency trade-off when there is no partition.

09Pros, Cons and Trade-offs

✅ Pros
  • CP: correct data, safe for money and stock
  • AP: always responds, great user experience and uptime
  • CAP gives a simple language to discuss trade-offs
⚠️ Cons
  • CP: some requests fail during a partition
  • AP: users may see old data, and conflicts must be solved
  • CAP is simplified: real systems are not just two boxes

Trade-offs

ChoiceWe gainWe lose
CPAlways correctSome downtime during a partition
APAlways answersMay serve stale data, needs conflict handling
Strong consistency (no partition)Simple for developersHigher write latency
Eventual consistencyLow latency, high uptimeMore complex application logic

10Common Problems and Mistakes

Common mistakes

  1. "Pick any 2 of 3". P is not optional. The choice is C or A during a partition.
  2. Thinking CAP is always on. When the network is fine, you can have both.
  3. Labelling a whole database CP or AP. Settings change the behaviour, and the choice can differ per operation.
  4. Mixing up CAP consistency with ACID consistency.
  5. Choosing AP for money. Two withdrawals on two sides can overdraw the account.
  6. Forgetting latency. PACELC reminds us that consistency also costs speed.

Problems you will meet

🧠Split brain
Both sides think they are the leader. Fix with majority quorum.
⚔️Write conflicts
Two sides changed the same item. Decide who wins.
🕰️Clock problems
"Last write wins" can pick the wrong write if clocks differ.
🩹Healing
After the network returns, nodes must sync safely.

11Real-World Examples

🏦Banking
Leans CP. It is better to show an error than a wrong balance.
🎟️Ticket booking
Needs the seat count to be right, so it leans CP.
📱Social media likes and feeds
Leans AP. A slightly old count is fine.
🛒Shopping cart (Dynamo-style)
Leans AP. The cart should always accept items. Conflicts are merged later.
🗂️Config and leader election
Tools like ZooKeeper and etcd lean CP. Everyone must agree on the leader.
🌍DNS
Leans AP. Old answers can be served for a while, and updates spread slowly.
📝Note
These are common textbook examples of the trade-off. Real products can behave differently with other settings.

12Related Topics to Read Next

Availability→

The A in CAP, and how we measure it in nines.

Reliability→

Correct results even when parts fail.

Consistent Hashing→

How replicas are placed across nodes.

Scalability→

Spreading data across machines is what creates the CAP problem.

Single Point of Failure (SPOF)→

Why we copy data to many nodes in the first place.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • ✔CAP: Consistency, Availability, Partition tolerance.
  • ✔Rule: during a network partition, choose C or A. Not both.
  • ✔P is required in any real distributed system.
  • ✔CP: correct but may refuse (money, seats, leader election).
  • ✔AP: always answers but may be stale (feeds, carts).
  • ✔Eventual consistency: copies become equal later.
  • ✔Quorum: R + W > N means reads see the latest write.
  • ✔PACELC: else, latency vs consistency.
  • ✔One line: "When the network breaks, choose between right and always-on."
← Previous
Consistent Hashing
Next →
Fault Tolerance and Redundancy