CAP Theorem Explained Simply, with Examples

When the network splits, a system must refuse (CP) or answer with possibly stale data (AP). CAP per feature, plus PACELC, consistency levels and quorums.

The CAP theorem: common questions

What does the CAP theorem say?

During a network partition a distributed system must choose between consistency (every read sees the latest write) and availability (every request gets an answer).

Is MongoDB CP or AP?

It depends on settings. With majority write and read concerns it behaves as CP; with relaxed concerns and secondary reads it leans AP. Classify features, not products.

Related chapters

Keep learning

Overview

Seat booking 14C free 14C → Asha Asha books 14C Ravi: is 14C free? Selling one seat twice costs money and trust. Ravi also bought 14C in B → conflict, one refund Like count 41 likes 42 likes Asha likes the post Ravi opens the post A count that lags a few seconds hurts nobody. Counts merge: 42 + any likes made in B apply change sync: A waits for B’s ack (+1 cross-region trip) async: B catches up in milliseconds both agree Region A reads + writes Region B CP still pays latency on every write. That is the “Else” in PACELC. AP is faster, but a read right after a write can still miss it for a moment. A holds the majority (2 of 3 copies) → accepted ship to B link down: message lost B is behind B cannot prove it is current → 503 / timeout no answer Region A (majority) Region B (minority) refuses reads + writes No double booking. Users in B get an error and retry later. Right choice: a refused request beats a seat sold twice. Correct, but users in B see errors over a like count. Overkill: you gave up availability for data nobody needs exact. accepted locally link down: queued for later answer, but old link heals → reconcile replicas converge Fast answer, wrong answer: 14C can be sold twice. Someone must detect the conflict and refund. Do not do this for seats. Everyone keeps liking. B shows 41 for a moment, then 42+. Right choice: counters merge cleanly after the link heals. Cable between regions Network link link up ✂ cut (partition) Region ARegion B Consistency mode CP: refuse if unsure AP: answer anyway Each region right now PostgreSQL / MySQL, one leader + sync replica Commits wait until the sync replica acks. Unreachable replica → writes stall. With async replicas, failover can lose recent commits. AP by default, tunable ONE answers from any replica. QUORUM fails if a majority is unreachable. Conflicts resolved by last-write-wins timestamps. Reads are eventually consistent by default. Strongly consistent reads are opt-in. Strong reads cost more and fail more often under trouble. Google Spanner Paxos majority per shard. The minority side stops serving. So well engineered that outages are rare: CP with high availability. Redis + async replicas Neither, strictly Leader acks before replicas copy. Failover can drop acknowledged writes. Fine for cache. Not a source of truth for money. system design · core concepts CAP theorem: when the network breaks, pick one Two copies of your data, a broken cable between them. Answer now with possibly old data, or wait until you are sure?

1. The problem: the cable breaks

A flight app runs in Mumbai and Frankfurt. Each region holds a copy of the seat map. Asha (Mumbai) books the last seat, 14C Mumbai copy 14C → Asha ✂ link down update never arrives Frankfurt copy still says 14C free Ravi (Frankfurt) asks: is 14C free? Frankfurt cannot reach Mumbai. It must either answer “free” (maybe wrong) or say “try later”. Answer now Ravi sees “free” and pays. Two people hold 14C. Wait or refuse Ravi sees an error. No double booking, but no sale either.

2. The three letters, precisely

Every read sees the latest write. Formally: linearizability, as if one copy existed. Every request to a non-failed node gets a non-error reply. No “wait forever”. Partition tolerance The system keeps working when messages between nodes are lost. Careful: the C in CAP is not the C in ACID. ACID’s C means “rules like balance ≥ 0 hold”.

3. P is not optional, so the choice is C or A

Cables get cut, switches fail, GC pauses look like dead nodes. Partitions will happen. all nodes talk messages lost A request arrives node can’t check the others refuse (CP) or answer (AP) CP: consistent, not always available The side that cannot confirm the latest value returns an error or times out. No stale reads, no lost writes. AP: available, not always consistent “CA” is not a real option It only exists on a single machine. Across a network, you cannot opt out of partitions. The choice is only during a partition When the link is healthy, a good system gives you both C and A.

4. Lab: cut the cable

Asha writes in region A. Ravi reads in region B. Cut the link and switch modes.

5. Choose per feature, not per company

One app mixes both. Ask: “What does a wrong answer cost here?” A wrong answer means… Seat / table booking double booking Payments, wallet balance money spent twice Inventory: last item in stock oversell, cancel order Unique username two users, one name Likes, view counts count off by a few News feed, timeline a post shows up late Profile picture old photo for a minute Food menu, restaurant hours slightly old menu A food app can keep the menu AP and the payment CP. Same app, two choices.

6. Consistency is a dial, not a switch

Between “always latest” and “eventually” sit useful middle levels. Strong (linearizable) Every read sees the latest write, everywhere. Costs coordination. You always see your own changes. Others may lag. Monotonic reads Once you saw a value, you never see an older one. Stop writing and all copies agree… eventually. No time bound. Eventual alone causes this classic bug. A chat user changes their photo, then refreshes. Replica (lagging) upload new photo write → leader ack to user leader: new · replica: old refresh profile read → load balancer picks replica stale read replica not caught up applies change a second later both: new Fix with read-your-writes: route a user’s reads to the leader for a few seconds after they write.

7. PACELC: the trade-off when nothing is broken

CAP only talks about partitions. PACELC adds the everyday cost. If Partition: A or C Rare but dramatic. Refuse requests, or serve stale data. Else: Latency or C Every day. Waiting for other replicas makes each write slower. write, ack from local node only (EL) write, wait for a replica on another continent (EC) By default, Cassandra and DynamoDB lean PA/EL. Spanner is PC/EC. Numbers above are typical, not fixed.

8. Tunable consistency: quorums

copies of each key acks before a write succeeds copies asked on each read R + W > N → at least 1 copy overlaps write v2 lands on nodes 1, 2 node 3 still v1 read asks 2 nodes e.g. 2 and 3 node 2 has v2 newest wins → v2 Any 2 of 3 must share a node with any other 2 of 3. That shared node carries the latest write. Fast and highly available. Stale reads likely. Balanced. Survives one node down for reads and writes. Overlap alone is not full linearizability. Sloppy quorums and concurrent writes can still surprise.

9. How real systems behave

during a partition watch out Interview tip: name the feature, the failure, and what the user sees. Not just “we pick AP”.

Remember

Partitions always happen in distributed systems During one: refuse (CP) or answer stale (AP) Pick per feature: money CP, counters AP No partition? Still latency vs consistency R + W > N makes reads overlap writes ★ Cheat code Ask “what does a wrong answer cost?”: bookings and money → CP, likes and feeds → AP. Consistency is tunable: quorums (R + W > N) and read-your-writes sit in between.

Go deeper

→ quorums in practice · split brain · where you need linearizability · read replicas and lag · multi-region writes · replication log · distributed transactions · ACID · Redis

More courses

  • Jobs, linked to lessons — Browse jobs where every requirement links to the chapter that teaches it. See how ready you are, how long the gap takes to close, and which listings look stale.
  • Match a job post to courses — Paste a job post. Each skill is matched to a track here and put in learning order, foundations first.
  • React patterns from open source — Patterns extracted from Material UI, Radix, React Aria, React Hook Form, Redux Toolkit, TanStack, and Next.js — not slides about hooks.
  • Databases in depth — How a query becomes work. Indexes, isolation, locks, and the plans that explain why a page is slow — not an ORM tour.
  • NestJS: build a real API — One ticket-booking API, built in order: a plain Node server first, then NestJS modules, validation, a real database, and the features real clients lean on.
  • Microservices — Microservice patterns one diagram at a time: how to split a monolith, how services talk, and how data stays consistent without distributed transactions.
  • Kafka — A beginner-to-senior path through event logs, reliable delivery, production operations, and disaster recovery.
  • AI engineering for software engineers — Eight free reads, in order, for software engineers moving into AI: when to build an agent, how to build one, how to test it, and how the model works underneath.
  • Frontend system design — How a UI is sliced when it is a product, not a page: ownership of state, cache, routes, and what happens when the network lies.
  • TypeScript in depth — The type system as a design tool. Inference, narrowing, generics, and the errors that mean the model is wrong — not a catalog of utility types.
  • CSS in depth — See the box, then the page. Visual chapters from the box model through Flexbox surprises, Grid, selectors, and units, then backgrounds, shapes, and visual effects, each with a playground.
  • Accessibility — Foundations first (WCAG in plain words, semantic HTML, lists, alt text), then hands-on HTML labs, a full pass of WAI-ARIA 1.3, and a final fix-the-page challenge.
  • Docker — What an image is, why layers cache, and how containers find each other on a network.
  • Redis — Fifteen Redis patterns, one picture each: cache, session, lock, counter, rate limiter, queue, and when Redis is the wrong tool.
  • Kubernetes — Kubernetes from zero to operators: why it exists, Pods, Deployments and Services, then configuration, networking, storage, scheduling, scaling and security.
  • AWS — AWS networking in plain English. A VPC is a gated housing society: streets are subnets, the Internet Gateway is the main gate, and a route table is the signboard.
  • Networking: the NetRoute game — NetRoute is a packet logistics game. You wire up computers, switches, routers, firewalls and gateways, set each device, and watch glowing packets travel. If a packet gets dropped, the game shows you which header field was wrong.