Difficulty: Advanced
Explain the CAP theorem. Why do people say you must choose between CP and AP, and what does that mean for real databases?
The CAP theorem says that when a distributed system experiences a network partition, it must choose between Consistency (every read returns the most recent write) and Availability (every request to a non-failed node gets a non-error response). You cannot have both during the partition. Because partitions happen in any real network, the practical choice is between CP (refuse some requests to stay correct) and AP (keep answering, possibly with stale data).
The "pick two of three" phrasing is misleading. You cannot opt out of partitions, so "CA" only describes a single-node system. Eric Brewer himself clarified in 2012 that the choice only arises during a partition; the rest of the time you can have both.
Two replicas of a Swiggy restaurant-status store, one in Mumbai and one in Chennai, lose connectivity. A write arrives in Mumbai marking a restaurant closed. A read hits Chennai. Chennai has two options:
| Choice | Behaviour during partition | Examples |
|---|---|---|
| CP | Minority side rejects writes or reads | etcd, ZooKeeper, HBase, Spanner, MongoDB with majority write/read concerns |
| AP | All sides accept requests, reconcile later | Cassandra, DynamoDB (default eventually consistent reads), Riak, CouchDB |
Many databases are tunable: Cassandra with QUORUM reads and writes (R + W > N) behaves much closer to CP for a given key, while ONE favours availability. So label configurations, not products.
CAP only talks about partitions. PACELC adds: if Partition, choose A or C; Else, choose Latency or Consistency. Even with a healthy network, synchronous replication to guarantee consistency adds latency. DynamoDB and Cassandra are PA/EL; Spanner and traditional synchronous setups are PC/EC. This is the trade-off engineers actually face daily.
Use CP where wrong answers cost money or safety: payment ledgers, inventory decrements, leader election, distributed locks. Use AP where a briefly stale answer is fine and downtime is not: product catalogues, feeds, likes counters, shopping carts that can merge.
-- Replication factor 3 per data centre
CREATE KEYSPACE shop WITH replication =
{'class': 'NetworkTopologyStrategy', 'dc_mumbai': 3};
-- In cqlsh:
CONSISTENCY QUORUM; -- 2 of 3 replicas must respond
INSERT INTO shop.stock (sku, qty) VALUES ('SKU-1', 10);
SELECT qty FROM shop.stock WHERE sku = 'SKU-1';
-- R(2) + W(2) > N(3): reads see the latest acknowledged write
CONSISTENCY ONE; -- any single replica; more available, may be stale
SELECT qty FROM shop.stock WHERE sku = 'SKU-1';
The same database can lean CP or AP per request. Quorum overlap gives strong reads for a key, at the cost of failing when a majority of replicas is unreachable.
Consistency, Availability, Partition Tolerance, PACELC, Linearizability, Quorum