Home CS Fundamentals CAP Theorem in Distributed Databases: Consistency, Availability, Partition Tolerance
Advanced 3 min · July 13, 2026

CAP Theorem in Distributed Databases: Consistency, Availability, Partition Tolerance

Learn CAP theorem fundamentals: Consistency, Availability, Partition Tolerance.

N
Naren Founder & Principal Engineer

20+ years shipping production systems from the metal up. Everything here is grounded in real deployments.

Follow
Production
production tested
July 13, 2026
last updated
2,165
articles · all by Naren
Before you start⏱ 15-20 min read
  • Basic understanding of distributed systems
  • Familiarity with SQL and NoSQL databases
  • Knowledge of network concepts (latency, partitions)
 ● Production Incident 🔎 Debug Guide ⚙ Triage Commands
Quick Answer

CAP theorem states a distributed data store can only provide two of three guarantees: Consistency, Availability, and Partition Tolerance. In practice, partitions are inevitable, so you must choose between CP (Consistency + Partition Tolerance) and AP (Availability + Partition Tolerance).

✦ Definition~90s read
What is CAP Theorem and Distributed Databases?

The CAP theorem is a fundamental principle in distributed databases that states you can only guarantee two out of three properties: Consistency, Availability, and Partition Tolerance.

Imagine a library with two branches connected by a phone line.
Plain-English First

Imagine a library with two branches connected by a phone line. If the phone line breaks (partition), you can either keep both branches open but risk different answers (AP), or close one branch to ensure everyone gets the same answer (CP). You can't have both perfect consistency and full availability during a network split.

When building distributed systems, you'll eventually face the CAP theorem. Coined by Eric Brewer in 2000, it describes the fundamental trade-offs between Consistency, Availability, and Partition Tolerance. In a world where network failures are inevitable, understanding CAP is crucial for designing robust databases. This tutorial dives deep into each property, explores real-world database choices (e.g., Cassandra, MongoDB, PostgreSQL), and shows how to apply CAP in production. You'll learn why many modern databases are 'AP' or 'CP' and how to choose based on your application's needs. We'll also walk through a production incident where CAP ignorance caused a major outage.

What is the CAP Theorem?

The CAP theorem states that a distributed data store can only provide two of the following three guarantees simultaneously: Consistency (C), Availability (A), and Partition Tolerance (P). Consistency means every read receives the most recent write or an error. Availability means every request receives a (non-error) response, without guarantee that it contains the most recent write. Partition Tolerance means the system continues to operate despite an arbitrary number of messages being dropped or delayed by the network between nodes. In practice, network partitions are unavoidable, so you must choose between CP and AP. This trade-off is fundamental to distributed database design.

cap_example.sqlSQL
1
2
3
4
5
6
7
8
9
-- Example: Simulating a partition in a distributed SQL database
-- Assume two nodes: node1 and node2
-- On node1:
INSERT INTO orders (id, amount) VALUES (1, 100);
-- Network partition occurs between node1 and node2
-- On node2, the insert is not visible
-- If we query node2:
SELECT * FROM orders WHERE id = 1; -- Returns empty (inconsistent)
-- To maintain consistency, node2 would need to reject the read or wait for partition to heal.
Output
Empty set (0.00 sec)
🔥Key Insight
📊 Production Insight
In real-world systems, you often relax consistency for better availability (e.g., social media feeds) or sacrifice availability for strong consistency (e.g., banking transactions).
🎯 Key Takeaway
CAP theorem forces a trade-off: you cannot have perfect consistency and full availability during a network partition.

Consistency Models in Depth

Consistency in CAP refers to strong consistency: after a write, all subsequent reads see that write. This is similar to ACID consistency in single-node databases. In distributed systems, achieving strong consistency often requires coordination (e.g., Paxos, Raft) which can reduce availability. Weaker consistency models include eventual consistency (updates propagate eventually), causal consistency, and read-your-writes consistency. For example, Amazon DynamoDB offers eventual consistency by default but can be configured for strong consistency at higher latency. SQL databases like PostgreSQL with synchronous replication can provide strong consistency but may become unavailable during a partition.

consistency_check.sqlSQL
1
2
3
4
5
6
-- PostgreSQL synchronous replication example
-- Ensure all replicas acknowledge writes
SHOW synchronous_commit; -- 'on'
-- During a partition, if replicas are unreachable, writes will fail.
INSERT INTO accounts (id, balance) VALUES (1, 500);
-- If partition occurs, this insert may timeout or error.
Output
ERROR: could not connect to standby server
⚠ Performance Impact
📊 Production Insight
Many NoSQL databases offer tunable consistency, allowing you to choose per operation.
🎯 Key Takeaway
Strong consistency ensures correctness but can hurt availability and performance.

Availability and Its Trade-offs

Availability means every request gets a response, even if it's not the latest data. This is critical for systems that must always be up, like e-commerce catalogs or social media. To achieve high availability, databases often replicate data across multiple nodes and allow reads from any replica. However, during a partition, replicas may diverge. For example, Cassandra is AP: it accepts writes on any node and resolves conflicts later via last-write-wins. The trade-off is that reads may return stale data. Availability is often measured in 'nines' (e.g., 99.999% uptime).

availability_example.sqlSQL
1
2
3
4
5
-- Cassandra (AP) example: write to any node
-- Even during partition, write succeeds
INSERT INTO orders (id, amount) VALUES (2, 200) USING TIMESTAMP 123456;
-- Read from another node may not see this write immediately
SELECT * FROM orders WHERE id = 2; -- May return empty or old value
Output
id | amount
----+--------
(0 rows)
💡When to Choose AP
📊 Production Insight
DynamoDB's default eventual consistency gives high availability; you can request strongly consistent reads at extra cost.
🎯 Key Takeaway
Availability ensures the system stays responsive but may sacrifice consistency.

Partition Tolerance: The Non-Negotiable

Partition Tolerance means the system continues to function despite network failures that prevent communication between nodes. Since network partitions are inevitable in distributed systems (e.g., due to hardware failure, network congestion), you must tolerate them. This is why CAP is often framed as a choice between CP and AP: you cannot sacrifice partition tolerance. A system that is not partition-tolerant would simply stop working during a network split. Most distributed databases are designed to be partition-tolerant by replicating data and handling splits via strategies like quorum-based decisions or conflict resolution.

partition_handling.sqlSQL
1
2
3
4
5
6
-- MongoDB (CP by default) handles partition via primary election
-- If primary is isolated, a new primary is elected, but writes to old primary fail
-- Example: replica set with 3 nodes
-- During partition, if primary is isolated, it steps down
rs.status() -- shows primary change
-- Writes to old primary will fail with 'not master' error
Output
{ "stateStr" : "PRIMARY", "name" : "node1:27017" }
🔥Remember
📊 Production Insight
Use quorum-based systems (e.g., etcd, ZooKeeper) for coordination to maintain consistency during partitions.
🎯 Key Takeaway
Partition tolerance is mandatory; you must choose between consistency and availability.

Real-World Database Choices: CP vs AP

Different databases make different CAP trade-offs. CP databases: HBase, MongoDB (with default settings), Redis (with replication), and traditional SQL with synchronous replication. They prioritize consistency over availability during partitions. AP databases: Cassandra, DynamoDB (eventual consistency), CouchDB, and Riak. They prioritize availability. Some databases offer tunable consistency (e.g., Cassandra allows you to set consistency level per query). Choosing the right database depends on your application's requirements. For example, a banking system needs CP, while a social media feed can use AP.

tunable_consistency.sqlSQL
1
2
3
4
5
-- Cassandra: tunable consistency per query
-- Strong consistency: require all replicas to acknowledge
SELECT * FROM orders WHERE id = 1 USING CONSISTENCY ALL;
-- Eventual consistency: only one replica needed
SELECT * FROM orders WHERE id = 1 USING CONSISTENCY ONE;
Output
id | amount
----+--------
1 | 100
💡Hybrid Approach
📊 Production Insight
Many companies use multiple databases: PostgreSQL for transactions, Cassandra for analytics.
🎯 Key Takeaway
Choose CP for correctness-critical systems, AP for high-availability systems.

Beyond CAP: PACELC and Modern Trade-offs

CAP is a simplified model. The PACELC theorem extends it: if a partition occurs (P), trade off between consistency (C) and availability (A); else (E), trade off between latency (L) and consistency (C). This acknowledges that even without partitions, there are trade-offs. For example, DynamoDB offers low latency by default but can sacrifice consistency. Google Spanner uses TrueTime to provide strong consistency with low latency, but at complexity cost. Understanding PACELC helps in designing systems that balance all factors.

pacelc_example.sqlSQL
1
2
3
4
5
-- Spanner: strong consistency with low latency using TrueTime
-- Example: read with strong consistency
SELECT * FROM orders WHERE id = 1;
-- Spanner ensures all replicas agree on timestamp
-- Even without partition, it chooses consistency over latency
Output
id | amount
----+--------
1 | 100
🔥PACELC Insight
📊 Production Insight
Google Spanner achieves both consistency and availability during partitions by using atomic clocks, but this is complex and costly.
🎯 Key Takeaway
PACELC provides a more nuanced view of distributed system trade-offs.

Practical Guidelines for Choosing Your Database

When selecting a distributed database, consider: 1) Consistency requirements: do you need strong consistency? 2) Availability requirements: can you tolerate downtime? 3) Partition tolerance: assume partitions will happen. 4) Latency: how fast must reads/writes be? 5) Operational complexity: can your team manage the database? Start by listing your application's critical paths. For example, an e-commerce site might use a CP database for inventory and an AP database for product reviews. Also consider using a multi-model database or a combination of databases. Always test under partition scenarios.

decision_flow.sqlSQL
1
2
3
4
5
6
7
-- Example: decision flow in SQL-like pseudocode
-- IF strong consistency required THEN
--   USE CP database (e.g., PostgreSQL with sync replication)
-- ELSE
--   USE AP database (e.g., Cassandra)
-- END IF;
-- For mixed requirements, use separate databases or tunable consistency.
⚠ Avoid Over-Engineering
📊 Production Insight
Netflix uses Cassandra for high availability and DynamoDB for session data, each tuned for different CAP trade-offs.
🎯 Key Takeaway
Match database choice to your specific consistency, availability, and latency needs.
● Production incidentPOST-MORTEMseverity: high

The Split-Brain Outage: When CAP Ignorance Cost Millions

Symptom
Users saw inconsistent order histories and duplicate payments across different regions.
Assumption
The team assumed the database would automatically resolve conflicts using last-write-wins.
Root cause
The database was configured for AP (Cassandra with eventual consistency) but the application expected strong consistency for financial transactions.
Fix
Switched to a CP database (MongoDB with write concern majority) for financial data and added conflict resolution logic for non-critical data.
Key lesson
  • Always understand the CAP trade-offs of your database.
  • Do not use eventual consistency for financial transactions.
  • Design for partitions: assume network splits will happen.
  • Use separate databases for different consistency requirements.
  • Test partition scenarios in staging environments.
Production debug guideSymptom to Action4 entries
Symptom · 01
Users see stale data after a network blip
Fix
Check if your database is AP (e.g., Cassandra). Consider read-repair or switching to CP for critical reads.
Symptom · 02
Writes fail during network partition
Fix
Your database is CP (e.g., HBase). Evaluate if you can tolerate unavailability for consistency.
Symptom · 03
Data conflicts after partition heals
Fix
Implement conflict resolution (e.g., CRDTs, last-write-wins, or manual reconciliation).
Symptom · 04
High latency during partition
Fix
Your system may be trying to maintain consistency. Consider relaxing consistency for non-critical operations.
★ Quick Debug Cheat SheetCommon CAP-related symptoms and immediate actions.
Inconsistent reads after partition
Immediate action
Check consistency level settings
Commands
SELECT CONSISTENCY;
SHOW SESSION VARIABLES LIKE 'consistency%';
Fix now
Increase read consistency to QUORUM
Write timeouts during partition+
Immediate action
Reduce write consistency
Commands
ALTER TABLE orders WITH write_consistency='ONE';
Fix now
Temporarily lower write consistency to ONE
Data conflicts detected+
Immediate action
Enable conflict resolution
Commands
ALTER TABLE orders WITH conflict_resolution='last-write-wins';
Fix now
Implement application-level merge logic
PropertyCP Database (e.g., HBase)AP Database (e.g., Cassandra)
ConsistencyStrongEventual
Availability during partitionLow (writes may fail)High (writes succeed)
Use caseFinancial transactionsSocial media feeds
Conflict resolutionNot needed (strong consistency)Last-write-wins or CRDTs
⚙ Quick Reference
6 commands from this guide
FileCommand / CodePurpose
cap_example.sqlINSERT INTO orders (id, amount) VALUES (1, 100);What is the CAP Theorem?
consistency_check.sqlSHOW synchronous_commit; -- 'on'Consistency Models in Depth
availability_example.sqlINSERT INTO orders (id, amount) VALUES (2, 200) USING TIMESTAMP 123456;Availability and Its Trade-offs
partition_handling.sqlrs.status() -- shows primary changePartition Tolerance
tunable_consistency.sqlSELECT * FROM orders WHERE id = 1 USING CONSISTENCY ALL;Real-World Database Choices
pacelc_example.sqlSELECT * FROM orders WHERE id = 1;Beyond CAP

Key takeaways

1
CAP theorem forces a trade-off between consistency and availability during network partitions.
2
Partition tolerance is mandatory in distributed systems; you must choose CP or AP.
3
Real-world databases make different CAP choices; select based on your application's requirements.
4
PACELC extends CAP to consider latency-consistency trade-offs even without partitions.
5
Always test your system under partition scenarios to understand behavior.

Common mistakes to avoid

3 patterns
×

Assuming all databases are CP

×

Ignoring partition tolerance

×

Using eventual consistency for critical data

INTERVIEW PREP · PRACTICE MODE

Interview Questions on This Topic

Q01JUNIOR
Explain the CAP theorem and its implications for distributed databases.
Q02SENIOR
Give an example of a CP database and an AP database. How would you choos...
Q03SENIOR
How does the PACELC theorem extend CAP? Provide a real-world example.
Q01 of 03JUNIOR

Explain the CAP theorem and its implications for distributed databases.

ANSWER
CAP theorem states that a distributed data store can only provide two of Consistency, Availability, and Partition Tolerance. Since partitions are inevitable, you must choose between CP and AP. CP systems sacrifice availability during partitions, while AP systems sacrifice consistency.
FAQ · 5 QUESTIONS

Frequently Asked Questions

01
Can a distributed database be both consistent and available during a partition?
02
What is the difference between CAP and ACID?
03
Is MongoDB CP or AP?
04
What does 'eventual consistency' mean?
05
How does the CAP theorem apply to microservices?
N
Naren Founder & Principal Engineer

20+ years shipping production systems from the metal up. Everything here is grounded in real deployments.

Follow
Verified
production tested
July 13, 2026
last updated
2,165
articles · all by Naren
🔥

That's DBMS. Mark it forged?

3 min read · try the examples if you haven't

Previous
Modern Data Warehousing: Snowflake, BigQuery, Redshift
19 / 19 · DBMS
Next
Introduction to Compiler Design