Skip to content

CAP Theorem and PACELC

Intermediate 60 min read Part 2 of 18

What consistency, availability and partition tolerance really mean, why a partition forces a choice, PACELC's latency trade-off, and how to choose per feature.

Summary#

The CAP theorem concerns data replicated across several machines. When the network partitions (some nodes cannot talk to others), each operation must choose between two properties:

  • Consistency (C): every read sees the latest write, or gets an error.
  • Availability (A): every request to a working node gets a non-error answer, even if it might be stale.

Networks do fail, so partition tolerance (P) is not optional. The practical question is therefore: during a partition, do we refuse or delay requests to stay correct (CP), or keep answering with possibly stale data (AP)?

PACELC extends this: if there is a Partition, choose A or C; Else, in normal operation, choose lower Latency or stronger Consistency. Keeping replicas in sync costs round trips even when nothing is broken, and that cost is felt every day, not just during rare partitions.

Real systems do not choose once. They choose per feature and per operation:

  • Strong consistency where a stale answer is harmful: seat booking, inventory, payments, account balances, matching.
  • Availability and low latency where staleness is harmless: feeds, profiles, product descriptions, view counts.

Why It Exists#

As soon as data lives on more than one machine, whether replicas for availability, regions for latency or shards for scale, the copies can disagree. Most of the time they converge in milliseconds. But messages between machines can be delayed or lost for seconds to hours:

  • cut fibres;
  • misconfigured switches;
  • overloaded links;
  • long garbage-collection pauses, which look exactly like a partition to the other nodes.

At that moment, the system must decide what to tell clients. Eric Brewer stated the trade-off as a conjecture at the PODC conference in 2000. Seth Gilbert and Nancy Lynch proved a formal version in 2002.

CAP matters in design because it forces a requirements question early: "Does every read need the most recent write?" The answer changes databases, replication modes, caching strategy, and even the user experience. It is also one of the most misunderstood ideas in the field, so a precise version is worth having. This page builds on Availability and Reliability.

How It Works#

The setting: replicated data and partitions#

CAP is about a replicated data store: several nodes hold copies of the same data, and clients can contact any of them. A network partition is any situation in which some nodes cannot exchange messages with others, while clients can still reach at least some nodes.

Partitions are not only "the cable between data centers was cut". They include:

  • partial partitions, where A can reach B and B can reach C, but A cannot reach C;
  • asymmetric partitions, where messages flow one way only;
  • a node that stops responding for 30 seconds during a GC pause or a stalled disk: to its peers it is indistinguishable from a partitioned node;
  • overload, where messages arrive so late that timeouts fire.

The key fact is that a node cannot tell the difference between "the other node is dead", "the other node is slow" and "the network between us is broken". All it sees is missing replies. The CAP choice is really about what to do when replies are missing.

The three properties, precisely#

PropertyPrecise meaning (as in the Gilbert-Lynch proof)Plain meaning
ConsistencyLinearizability: the system behaves as if there were a single copy of the data, and every operation takes effect at one instant between its start and its completion. Every read returns the value of the most recent completed write, or an error."Everyone sees the same, latest data."
AvailabilityEvery request received by a non-failing node returns a non-error response, eventually."Any working node answers, even if its answer may be stale."
Partition toleranceThe system keeps satisfying its guarantees even when the network loses arbitrarily many messages between nodes."It keeps working correctly when the network splits."

Two warnings:

  • CAP consistency is not ACID consistency. In ACID, "C" means transactions keep the database's invariants valid (constraints, foreign keys). CAP's C is about replicas agreeing on the latest value. They share a letter and nothing else. See ACID and Isolation Levels.
  • CAP availability is not uptime. CAP's A is a strict, all-or-nothing property: every non-failing node must answer. A system that refuses requests on the minority side of a partition is "not available" in CAP terms, yet it can easily achieve 99.99% uptime, because partitions are rare and short.

Why a partition forces a choice#

The core argument is short. Take two replicas, N1 in the USA and N2 in Europe, both holding display_name = "Sam".

  1. The link between N1 and N2 fails.
  2. A user writes display_name = "Samira" to N1. N1 cannot send it to N2.
  3. Another user reads the display name from N2.

N2 now has exactly two options:

  • Answer with "Sam", the value it has. The system stays available, but the read does not reflect the latest write, so it is not consistent.
  • Refuse, or wait until it can confirm the latest value with N1. The system stays consistent, but N2, a working node, does not answer, so it is not available.

There is no third option. N2 cannot know about a write it never received. Gilbert and Lynch formalised this argument, which also shows why "CA" (consistent and available) is possible only if partitions cannot happen. In practice that means a single node, or nodes that share fate completely, so that they fail together.

In this profile example, showing the old name for a few seconds is far better than showing an error, so the right choice is availability.

What a node does during and after a partition#

The behaviour of one replica can be drawn as a small state machine. A CP replica that loses contact with the majority stops accepting writes, and either stops serving fresh reads or labels them stale. An AP replica keeps serving, but records that it has diverged so that it can reconcile when the link returns.

Three design details follow from this picture:

  1. Timeouts decide when you are "partitioned". A short timeout reacts fast but triggers false failovers during GC pauses. A long timeout leaves clients hanging. Typical values are 1-10 seconds for consensus elections and 5-30 seconds for database failover tools.
  2. Rejoining is a phase of its own. A CP replica must discard any writes it never committed and copy the leader's log. An AP replica must find and merge every key that changed on both sides. Both phases add load right after an incident, so leave headroom for them.
  3. The UX must match the state. In CP mode, show "temporarily unavailable, please retry" and keep the user's input. In AP mode, show possibly stale data, and if a merge later changes what the user saw, explain it. A good example is an "item was out of stock after all" email with an automatic refund.

CP vs AP behaviour#

A CP system keeps one agreed history.

  • Typically only nodes that can reach a majority (quorum) may accept writes, or serve reads that must be up to date. The minority side returns errors or times out.
  • Clients on the minority side see failures, but no one ever sees two conflicting versions of the truth.
  • Examples:
    • consensus-based stores: ZooKeeper, etcd, Consul;
    • NewSQL databases built on consensus: Google Spanner, CockroachDB, YugabyteDB;
    • single-primary relational databases when reads go to the primary.

An AP system keeps answering on every side of the partition.

  • Each side serves reads from its local data and often accepts writes too.
  • When the partition heals, replicas reconcile. Conflicting writes must be merged, using last-writer-wins by timestamp, version vectors that surface siblings for the application to merge, or CRDTs (data types designed to merge automatically).
  • Examples:
    • Dynamo-style stores: Cassandra, Riak, DynamoDB with eventually consistent reads;
    • DNS;
    • caches and CDNs serving stale content;
    • multi-leader setups.
FeatureStale or conflicting data would meanChoose
Ticket / seat bookingTwo people sold seat 6ACP for the booking write
E-commerce inventory at checkoutSelling the last item twiceCP for the decrement (or allow and compensate)
Bank transfer / balance check before debitSpending money that is not thereCP
Stock order bookTrades at wrong pricesCP
Leader election, locks, configTwo leaders, split-brainCP
Social feed, likes, view countsA post appears a few seconds lateAP
Profile picture, display nameOld picture for a minuteAP
Product or movie descriptions, business hoursSlightly outdated textAP
Shopping cartMerging two carts' items later is acceptableAP (as in Amazon's Dynamo)
DNSOld IP for the TTL durationAP

A good test question: "Would it be harmful if a user briefly saw stale or conflicting data here?" If yes, choose consistency for that operation. If no, choose availability and low latency.

Common misunderstandings#

  1. "Pick any two of three." You cannot give up P in a distributed system, because partitions happen whether you like it or not. The real choice is C or A, and only during a partition. Brewer himself called the "two of three" framing misleading in "CAP Twelve Years Later: How the 'Rules' Have Changed" (IEEE Computer, 2012).
  2. "CAP describes the system all the time." It describes behaviour during a partition. When the network is healthy, a well-built system can be both consistent and available; the trade-off then is latency, which is PACELC.
  3. "A database is CP or AP." Many databases let you choose per operation. Cassandra has per-query consistency levels; DynamoDB offers optional strongly consistent reads; MongoDB has read and write concerns. Labelling the database hides the choice you actually make.
  4. "CP means unavailable." CP systems are unavailable only on the minority side, and only during partitions. Google has described Spanner as technically CP, yet effectively highly available because Google's private network makes partitions very rare: Brewer, "Spanner, TrueTime and the CAP Theorem", 2017.
  5. "AP means no guarantees." AP systems can still offer useful guarantees: read-your-writes, monotonic reads, causal consistency, and bounded staleness. See Consistency Models.
  6. "Consistency in CAP is ACID's C." It is not; see above.
  7. "Every system is either C or A." Many systems provide neither in the CAP sense. A primary with asynchronous replicas that fails over automatically can lose acknowledged writes, so it is not linearizable. It also rejects writes on the side without the primary, so it is not CAP-available either. That is often a perfectly reasonable engineering choice, but it is not "CP" or "AP".
  8. "CAP covers all failures." It is a statement about one kind of fault, message loss, under one strict definition of consistency. It says nothing about crashes without partitions, latency, durability, or multi-object transactions.

PACELC: the trade-off you pay every day#

Daniel Abadi proposed PACELC (in a 2010 blog post, then "Consistency Tradeoffs in Modern Distributed Database System Design", IEEE Computer, 2012) because CAP says nothing about the 99.9% of the time when there is no partition:

  • If Partition (P): choose Availability (A) or Consistency (C).
  • Else (E): choose lower Latency (L) or stronger Consistency (C).

Why does consistency cost latency with no failures at all? To guarantee that a read sees the latest write, a write must reach a quorum of replicas before it is acknowledged, or a read must check with a quorum or the leader, or both. That means waiting for network round trips:

  • Within one zone, a replica round trip is ~0.5 ms, which is cheap.
  • Across zones, ~1-2 ms per round trip, which is still cheap.
  • Across regions, 60-200 ms per round trip, which is expensive. A consensus write across US-East, US-West and Europe needs at least one round trip to a majority, about 70-100 ms, on every write.

A system that answers from the nearest replica without coordination answers in about 1 ms but may be stale.

System (typical configuration)PartitionElseNotes
Cassandra, Riak, Dynamo-style storesPAELTunable; QUORUM reads and writes move toward PC/EC
DynamoDB (default eventually consistent reads)PAELStrongly consistent reads go to the leader: EC for that read
Google Spanner, CockroachDB, YugabyteDBPCECConsensus on every write; reads can be stale-by-choice for lower latency
ZooKeeper, etcd, ConsulPCECSmall, critical metadata; writes through a leader and quorum
Single-primary PostgreSQL/MySQL with async replicasPC for primary writesEL if reading from replicasReplica reads are fast and may lag
Yahoo PNUTS (as classified by Abadi)PCELPer-record master; reads may be stale

In everyday design, the "ELC" half matters more than the "PAC" half. Partitions are rare, but the latency of synchronous coordination is paid on every request. That is why so many global systems:

  • read from local replicas;
  • write asynchronously;
  • reserve synchronous, cross-region coordination for the few operations that truly need it.

The spectrum between "C" and "A"#

CAP talks about the strongest consistency model, linearizability, and its opposite, "anything goes until convergence". Real systems choose from a ladder in between. Weaker rungs cost less coordination and can stay available during partitions.

LevelGuaranteeAvailable during a partition?Typical use
Strong (linearizable)Every read sees the latest completed write, system-wideNo (minority side must refuse)Locks, bookings, balances, leader election
SequentialAll clients see operations in one common order, but not necessarily real-time orderNoRarely chosen directly; some coordination services
CausalIf write B depends on write A (B was made after seeing A), everyone sees A before BYes (with sticky clients)Comments and replies, chat threads, collaborative apps
Read-your-writesA user always sees their own writesYes, if the user sticks to a replica or sessionProfile edits, posts, settings
Monotonic readsA user never sees data go "back in time"Yes, with sticky routingFeeds, timelines, dashboards
Bounded stalenessReads lag the latest write by at most T seconds or K versionsOnly while within the boundLeaderboards, analytics, catalogue prices
EventualIf writes stop, all replicas eventually agreeYesDNS, view counts, likes, CDN content

Two examples make the middle rungs concrete:

  • Causal consistency fixes the classic anomaly where someone in a group chat sees the reply "Congratulations!" before the message "I got the job" that it answers. Each write carries the dependencies it saw, and a replica delays showing a write until its dependencies are visible. No global coordination is needed, so the system stays available.
  • Read-your-writes fixes "I changed my profile picture and it reverted". After a user writes, route that user's reads to the primary for a short window, say 5-10 seconds, or until the replica they read from has applied the write's log position. Everyone else keeps reading from fast replicas.

DNS is the textbook eventual system. A change to a record propagates as caches expire, over minutes to a day depending on TTLs. During that window, different resolvers return different answers, and nobody considers DNS "broken". The details are in Consistency Models.

When you state a choice in a design, name the rung, not just "eventual". For example: "the feed is eventually consistent with read-your-writes for the author, and lag is normally under 2 seconds."

Tunable consistency: quorums#

Dynamo-style stores make the trade-off a per-request setting with three numbers:

  • N: the number of replicas;
  • W: how many must acknowledge a write;
  • R: how many are asked on a read.

If R + W > N, the read set and write set overlap, so a read usually sees the latest acknowledged write. N = 3, W = 2, R = 2 is the classic choice.

  • W = 1, R = 1: fastest and most available, the PA/EL corner. Reads may be stale.
  • W = 3 (all): every write waits for the slowest replica and fails if any replica is down.
  • LOCAL_QUORUM in Cassandra: a quorum within the local data center. You get consistency within a region at local latency, and asynchronous replication to other regions.

Quorum overlap alone is not full linearizability. Concurrent writes, sloppy quorums during failures and clock-based conflict resolution can still produce anomalies. See Quorums and Leaderless Replication.

Choosing per feature, not per system#

Real products need both properties, just for different features.

Ticket booking (a Ticketmaster-style system):

  • Browsing events, descriptions, search results: availability and low latency. Serve from caches, a search index fed by change data capture (CDC), and CDNs. Slightly stale descriptions are fine.
  • Seat map display: eventually consistent, but freshness matters. Push updates to clients (Server-Sent Events) so seats taken by others disappear quickly. The seat map is still only a hint: the booking write decides.
  • Reserving a seat during checkout: a short-lived hold, for example 10 minutes. It can live in a fast store with automatic expiry (a Redis key set with SET NX EX), or as a reserved status with an expiry timestamp checked inside a short database transaction. Avoid long-held database locks: holding a row lock for the minutes a user spends typing card details ties up connections and invites deadlocks.
  • Confirming the booking: strong consistency in a single authoritative database. A transaction with a row lock or an optimistic version check guarantees that only one booking per seat ever commits. Even if the reservation store fails, there is never a double booking; the worst case is an error for the slower buyer.
  • Extreme demand (a hugely popular on-sale): put a virtual waiting queue in front of the booking flow. It admits users at a rate the consistent core can handle, and it keeps users informed of their position. Protecting the CP core with admission control is often better than trying to scale the core infinitely.

Dating app: a mutual match needs consistency, because both users should see it at once. Profile views can be stale.

E-commerce:

  • the catalogue and reviews are AP;
  • the cart is AP, with merge;
  • the inventory decrement and payment are CP;
  • the order history is read-your-writes.

Social feed: entirely AP and latency-driven. Precompute feeds (fan-out on write), cache them, and serve from local replicas to hit sub-500 ms targets. Give users read-your-writes for their own posts so they never think a post was lost.

Chat: messages within one conversation should be ordered and not lost, which needs per-conversation ordering through a single partition or leader. Presence indicators and typing notifications are AP and can be lossy.

How each choice shapes the design#

If an operation prioritises consistency:

  • Single source of truth: one primary database, or one leader per partition. Route the critical reads to it, not to replicas.
  • Consensus-replicated storage (Raft or Paxos based) when you need both consistency and fault tolerance across zones or regions.
  • Synchronous replication for zero data loss on failover (RPO = 0).
  • Distributed transactions (two-phase commit) or sagas across stores when an operation spans systems, accepting higher latency. See Distributed Transactions.
  • Locks, leases and fencing tokens for exclusive operations.
  • Expect higher write latency, and errors or waiting during partitions; design the UX for "please retry".

If an operation prioritises availability:

  • Asynchronous read replicas and caches, serving whatever they have.
  • CDC pipelines that propagate changes from the primary to caches, search indexes and other services, eventually.
  • Multi-leader or leaderless replication for writes in several places, with explicit conflict resolution.
  • Session guarantees to hide the worst anomalies: read-your-writes (route a user's reads to the primary for a few seconds after they write), and monotonic reads (stick a user to one replica).
  • Expect stale reads and occasional conflicts; design the data model so merges are safe, for example sets that union and counters that add.

Applying the test: five quick verdicts#

The question "would a brief inconsistency be harmful?" sounds abstract until you run it on real features. Here are five common cases.

  1. The last toothbrush in stock. Two shoppers in different regions click "buy" on the final unit within the same second.
    • With an AP inventory count, both see "1 left" and both orders succeed. One shopper later gets an apology and a refund.
    • With a CP decrement, exactly one order succeeds and the other shopper sees "sold out". A CP decrement is a conditional update such as UPDATE stock SET qty = qty - 1 WHERE sku = 'T1' AND qty >= 1.
    • Many retailers choose AP here on purpose. An oversold toothbrush costs a few dollars and an email, while refusing orders during a partition costs real sales.
    • This is a business decision, which is why you ask the interviewer rather than assume.
  2. A stock exchange order book. Two traders must never both match against the same resting order, and the order of fills decides who gets which price.
    • A stale view means trading at prices that no longer exist, which is both a financial loss and a regulatory problem.
    • Exchanges therefore keep one authoritative sequencer per instrument: a single process that orders every event for that symbol. It is replicated to hot standbys.
    • They halt trading in a symbol rather than run two diverging books. This is CP taken to the extreme.
  3. A restaurant's opening hours on a review site. The owner changes Sunday's hours, and a visitor in another region sees the old hours for 30 seconds. Nothing bad happens, so this is AP, with replicas and caches everywhere.
  4. A film's description on a streaming service. A typo fix that takes a minute to reach every edge cache is invisible to viewers. This is AP, served from CDN and cache.
  5. A profile picture. Other people may see the old picture for a few seconds; that is fine. But if the owner sees the old picture right after uploading a new one, it feels like a bug. So the answer is "AP, plus read-your-writes for the owner". This is the most common shape of all.

The verdict rarely depends on the technology. It always depends on the cost of being wrong: money moved, a promise to a customer broken, a legal obligation, or merely a slightly old pixel. In an interview, say the cost out loud: "a double-sold seat means two people at the venue with one seat, so booking is consistent."

Worked example: reserving a seat without double-booking#

A ticketing site is the standard CP case, and how it stays consistent teaches more than the label does.

The requirement:

  • when a user selects a seat, hold it for them for about 10 minutes while they pay;
  • nobody else may buy the seat during the hold;
  • if they abandon checkout, the seat goes back on sale.

There is a ladder of designs, from fragile to robust.

Fragile: hold a database row lock for the whole checkout. The service runs SELECT ... FOR UPDATE on the ticket row and keeps the transaction open while the user types their card details.

  • It pins connections. Every open checkout holds a database connection and a lock for minutes. A busy on-sale with 20,000 people in checkout needs 20,000 open transactions, far beyond the few hundred connections a PostgreSQL pool comfortably handles.
  • It invites deadlocks when users select several seats in different orders.
  • Crashes leave locks behind. If the application crashes mid-checkout, the lock lingers until the database notices the dead connection.
  • Timeouts only turn waiting into errors. A lock_timeout setting stops waits from lasting forever, but the waiting buyer simply gets an error.

Database locks are meant to last milliseconds, not minutes of human thinking time.

Workable: a status column plus an expiry, cleaned by a cron job. A short transaction sets the ticket row to status = 'reserved' and reserved_until = now() + 10 min. A job runs every minute and resets expired reservations to available.

  • Consistency is fine, because the reservation is a short conditional update.
  • Inventory is lost for a while. A seat can stay "reserved" for up to a minute after its hold expires, waiting for the next cron run. In a high-demand sale, that is a minute of lost inventory per seat.
  • Cron failure is silent. If the job fails, seats stay locked indefinitely, and nobody notices until users complain.

Robust option 1: make expiry implicit. Do not rely on the cleanup job for correctness. A seat counts as available if its status is available, or if it is reserved with reserved_until in the past. The reservation then becomes a single conditional update:

-- Reserve seat 6A for user 42, only if nobody holds a live reservation
UPDATE tickets
SET    status = 'reserved', reserved_by = 42,
       reserved_until = now() + interval '10 minutes'
WHERE  event_id = 901 AND seat = '6A'
  AND  (status = 'available'
        OR (status = 'reserved' AND reserved_until < now()));
-- 1 row updated: the hold is ours. 0 rows: someone else has it.
  • Atomicity does the work. Row-level atomicity in the database guarantees that only one of two concurrent updates matches.
  • Listing uses the same predicate. Queries that list available seats use the same condition, backed by a compound index on (event_id, status, reserved_until) or by a materialised view.
  • Cleanup becomes cosmetic. The cleanup job can still run, but only to tidy the data; correctness never depends on it.

Robust option 2: keep holds in Redis with a TTL. Put the short-lived hold in a fast store with automatic expiry. The durable ticket table stays simple, with just two states, available and sold.

# Acquire a 10-minute hold on seat 6A for user 42 (fails if already held)
SET hold:event901:6A user42 NX EX 600
# Seat map: one sorted set per event, score = hold expiry time (epoch seconds)
ZADD event901:held 1767264600 6A
# Before reading the map, drop holds that expired before "now"
ZREMRANGEBYSCORE event901:held -inf 1767264000
  • Holds expire by themselves. NX means "set only if absent", and EX 600 sets a 600-second expiry. The hold vanishes on its own if the user walks away, so no cron job is needed.
  • The value names the holder. Storing the user ID as the value lets the service check that the person paying is the person holding the seat.
  • Several seats at once. Acquire the holds one by one and release them all if one fails, or run a short Lua script so the multi-seat check-and-set is atomic. A script is atomic only when all its keys live on the same Redis Cluster node, so give every key of an event the same hash tag.
  • The seat map reads the sorted set, after dropping expired members, to grey out held seats.

What if Redis fails, or a hold expires while the user is still paying? The design does not depend on Redis for correctness. The final step, marking the ticket sold, is a transaction in the primary database with an optimistic concurrency check: UPDATE tickets SET status = 'sold', booking_id = ... WHERE seat = '6A' AND status = 'available'.

  • If two buyers somehow both reach payment, exactly one update succeeds.
  • The other buyer's payment is refunded, or never captured.

The Redis hold is a performance and user-experience layer: it stops most collisions before anyone pays. The database transaction is the correctness layer. This split, a fast, availability-friendly hint in front of a small consistent core, is one of the most reusable patterns in system design.

Worked example: paying for the held seat#

Payment is where consistency meets an external system you do not control. A safe flow has five steps.

  1. Open the booking. When the hold succeeds, the Booking Service inserts a bookings row with status = 'in_progress' and a unique booking ID.
  2. Keep card numbers off your servers. The browser collects card details with the payment provider's own script, such as Stripe.js. This keeps you out of most of the scope of PCI DSS, the card industry's security standard.
  3. Create the payment. The server creates a payment intent with the provider, tagged with the booking ID, and the browser confirms it.
  4. Commit on the webhook. When the payment succeeds, the provider calls your webhook. The handler runs one database transaction: it marks the ticket sold (with the optimistic check) and the booking confirmed.
  5. Make the webhook idempotent. The webhook may be delivered more than once. Because the handler is keyed on the booking ID, a second delivery finds the booking already confirmed and does nothing.

Edge cases decide whether the design is really safe:

  • The hold expires during payment. Either extend the hold when payment starts, or accept that the final optimistic check may fail and refund automatically.
    • To extend safely, use a Lua script that resets the TTL only if the value is still this user's ID.
    • Extending is friendlier to users, but the refund path must exist anyway.
  • The webhook never arrives. A reconciliation job asks the provider about bookings that have been stuck in_progress for longer than, say, 30 minutes.
  • The database is shared. Booking rows and ticket rows live in the same database even if two services own the logic, because "sold" and "confirmed" must commit atomically.
    • Sharing a database between services is acceptable when the data is this tightly coupled.
    • Splitting it would force a distributed transaction onto the most critical operation in the system.

Protecting the consistent core: the virtual waiting queue#

CP systems pay for correctness with coordination, so their throughput has a ceiling. Sometimes demand exceeds it by orders of magnitude, as when a superstar's tour goes on sale. Then the question is no longer "CP or AP" but "how do we stop the CP core from melting?"

A first step: push seat-map updates. Send seat-map changes to browsers over Server-Sent Events, so users stop clicking seats that are already gone. This helps at normal scale.

At extreme scale it fails. When 1 million people watch a map of 50,000 seats, the map turns grey within seconds, and every remaining seat receives thousands of simultaneous hold attempts. The UX is miserable and the hold store is hammered.

The robust answer: admission control. Put a virtual waiting queue in front of the booking flow, and let administrators switch it on for high-demand events.

  • Join. On arrival, a user joins a queue, for example a Redis sorted set scored by arrival time.
  • Wait with feedback. The browser holds a WebSocket or SSE connection that reports the user's position and an estimated wait.
  • Admit at a controlled rate. A dequeuer admits users either at a fixed number per second, or as many as just finished or abandoned checkout. Admitted users get a short-lived admission token, or an entry in a set such as admitted:event901 with a TTL.
  • Enforce on every call. The Booking Service checks admission on every reserve call, so nobody can skip the queue by calling the API directly.

A worked example. Say 2 million users arrive for 60,000 seats.

  • Each checkout takes about 3 minutes, and the booking core comfortably handles 500 reservations per second.
  • Admitting 5,000 users per minute keeps about 15,000 people in checkout at once (5,000 per minute × 3 minutes).
  • If each makes one to three hold attempts, the core sees roughly 80-250 reservation calls per second, well under its limit.
  • With an average of 2 tickets per buyer, 30,000 admitted buyers exhaust the inventory. That takes 6 minutes of admissions, plus about 3 minutes of checkout.
  • The queue stops admitting when inventory reaches zero. The other 1.97 million users learn within minutes that the event has sold out, instead of fighting a broken page for an hour.

The queue itself can be availability-oriented. Losing a few positions during a Redis failover is annoying but harmless, and the queue's state is cheap to rebuild. Its job is to shield the strongly consistent core.

That is the general lesson: put cheap, availability-oriented machinery at the edge, and keep the expensive consistent part small and protected.

Inside a real store: how DynamoDB chooses per read#

Looking inside one managed database shows CAP choices as mechanisms rather than labels. Amazon's 2022 USENIX ATC paper, "Amazon DynamoDB: A Scalable, Predictably Performant, and Fully Managed NoSQL Database Service" (Elhemali et al.), describes the design.

  • Partitions and replicas. A table is split into partitions by the hash of the partition key. Each partition is stored by a replication group of three replicas in three different Availability Zones. Customers cannot change the replica count.
  • Writes. Each replication group runs Multi-Paxos to elect a leader, and only the leader accepts writes. The leader appends the write to its write-ahead log and sends it to its peers. It acknowledges the client once a quorum, 2 of 3, has durably logged the write.
  • Strongly consistent reads are served by the leader. The leader holds a lease, so it knows it is still the leader and has every acknowledged write.
  • Eventually consistent reads, the default, may be served by any replica. A follower may be a few milliseconds behind, so a read right after a write can miss it.
  • Leader failure. When a leader fails or is partitioned away, the remaining replicas elect a new one after the old leader's lease expires. During that window, writes and strong reads for that partition stall, but eventual reads from the surviving replicas continue.
  • Log replicas. If a storage replica fails, the group can quickly add a log replica, which stores only recent log entries, to restore durability while a full replica is rebuilt.

Within one region, then, DynamoDB is PC/EC for writes and strong reads, and PA/EL for default reads. The client picks per request with ConsistentRead=true. AWS even prices the difference: a strongly consistent read consumes twice the read capacity of an eventually consistent one. That is PACELC's cost of consistency, made visible on the bill.

Across regions, Global Tables replicate asynchronously between regional tables, and concurrent writes to the same item in different regions are resolved by last-writer-wins. That is PA/EL across regions.

AWS announced a multi-Region strong consistency option for Global Tables in late 2024. As PACELC predicts, it raises write latency, because each write must reach another region before it is acknowledged.

Fail-open or fail-closed: CAP for infrastructure components#

The same choice appears in infrastructure that is not a database: any component that depends on shared state and might lose contact with it.

A distributed rate limiter is a clean example. API servers check and increment counters in a shared Redis cluster. If Redis becomes unreachable, each API server must decide what to do.

  • Fail open: allow requests through without limiting. This is the availability choice. Users keep being served, but the protection the limiter provides disappears.
  • Fail closed: reject requests (HTTP 429 or 503) until the limiter is back. This is the consistency choice. Limits are enforced exactly, at the cost of refusing legitimate traffic.

Neither is universally right.

  • A large social platform may well fail closed. Redis outages tend to coincide with traffic spikes; the spike is often why Redis is struggling. Failing open at that moment lets the whole spike hit the backend services, which turns a limiter outage into a site-wide outage.
  • A payment API serving paying merchants may prefer to fail open for a few minutes rather than reject every payment.
  • A middle path is degraded local limiting. Each server falls back to an in-memory limiter that allows its fair share: the global limit divided by the number of servers. That is approximately right, and needs no coordination.

Making the limiter's store highly available.

  • Redis needs replicas with automatic failover (Redis Cluster or Sentinel), and monitoring of failover events.
  • Asynchronous replication means a failover can lose a few recent increments. For a rate limiter that is harmless: a user gets a few extra requests.
  • This is a conscious "neither CP nor AP, and that is fine" choice.

The same reasoning applies to other shared-state dependencies:

  • Authentication and authorisation caches. If the permission service is unreachable, either serve cached decisions for a bounded time (availability) or deny (consistency). Banks deny; content sites often serve the cached decision.
  • Feature flags. Fall back to the last known flag values. This is almost always the right call.
  • Service discovery. Keep using the last known endpoints rather than emptying the routing table. A stale list is better than no list.
  • Distributed locks guarding exclusive jobs. Fail closed, or two workers will run the job at the same time.

Making partitions matter less: ownership and geography#

A partition forces a choice only for data that is written on both sides of it. If each piece of data has a single home, most of the conflict disappears.

Geo-sharding. A ride-hailing service matches riders with nearby drivers; a rider in Paris never needs a driver in Tokyo. So shard driver locations and trip state by geographic region, with each region's data in data centres near it.

  • Local and consistent. Reads and writes for a city stay local. They are fast (PACELC's L) and can be strongly consistent within the shard (PACELC's C) without crossing oceans.
  • Partitions stay local. A partition between continents does not affect matching inside either continent.
  • Boundaries are the only cross-shard case. Only queries near a shard boundary, such as a rider at the edge of a region, need to scatter-gather across two shards.
  • Rebalancing. Within a region, read replicas carry read-heavy traffic, and consistent hashing spreads geographic cells across nodes so shards can be rebalanced. Uber open-sourced H3, a hexagonal grid system it built to divide areas into cells, which is a natural unit for this kind of partitioning.

Scaling vertically, with one giant database, does not solve this. It does not reduce the distance to users, and it remains a single point of failure.

Home regions for users. A global chat or email service can assign every user a home region.

  • The user's mailbox has exactly one writer, the home region, so that user's writes are consistent and local.
  • Other regions hold asynchronous read copies.
  • During a partition, users in their home region are unaffected. Only cross-region interactions, such as sending to a user homed elsewhere, are delayed, and those are naturally asynchronous anyway.

The general lesson: design the data so that partitions cut through as few invariants as possible. Choosing a partition key is often a more powerful CAP decision than choosing a database.

Partition mode: handling a partition on purpose#

Brewer's 2012 article recommends treating a partition as an explicit mode of operation rather than an accident. It has three steps.

  1. Detect the partition, usually with timeouts.
  2. Enter partition mode. The system deliberately limits some operations and records everything it does.
  3. Recover. When the link heals, merge the state, restore the invariants, and compensate for any mistakes made during the partition.

Brewer's example is the ATM. A networked ATM normally checks the balance with the bank, which is consistency. If it loses its connection, it could refuse service (CP) or keep dispensing (AP). Real ATMs take a middle path:

  • In partition mode they allow withdrawals only up to a bounded amount, which caps the worst-case damage.
  • When the connection returns, the transactions are reconciled. Any overdraft is compensated with a fee or a collections process.
  • The invariant "balance never negative" is temporarily relaxed to "balance never more than X below zero". The bound is what makes the risk acceptable.

The pattern generalises:

  • an online shop in partition mode may accept orders but delay charging and shipping until recovery;
  • a booking system may sell from a pre-allocated local quota (escrow) and stop when the quota runs out;
  • a collaborative editor accepts local edits and merges them later with CRDTs.

Quorum arithmetic: availability and tail latency#

Numbers make quorum choices concrete. Assume each replica is independently up 99.9% of the time. In reality failures are correlated; more on that below.

Write availability with N = 3 replicas:

Write quorumSucceeds whenAvailability
W = 1any replica is up1 − 0.001³ ≈ 99.9999999%
W = 2 (majority)at least 2 of 3 are up0.999³ + 3 × 0.999² × 0.001 ≈ 0.997003 + 0.002994 = 99.9997%
W = 3 (all)all 3 are up0.999³ ≈ 99.7%

W = 3 is worse than a single replica's 99.9%, because any one failure blocks writes.

With N = 5 and W = 3, a write fails only if 3 or more replicas are down at once: about 10 × 0.001³, roughly one in 100 million. This is why consensus systems use 3 or 5 members:

  • 3 members tolerate one failure, and 5 tolerate two;
  • even numbers add cost without adding tolerance. Four nodes still tolerate only one failure, because a majority of 4 is 3.

Tail latency tells the same story. Suppose each replica answers within 10 ms 99% of the time (its p99 is 10 ms), independently of the others.

  • W = 2 of 3: the write waits for the second-fastest replica. It takes longer than 10 ms only if at least two replicas are slow: 3 × 0.01² × 0.99 + 0.01³ ≈ 0.03%. A majority quorum hides one slow replica, so its p99 is better than any single replica's.
  • W = 3 of 3: the write waits for the slowest replica. It takes longer than 10 ms if any replica is slow: 1 − 0.99³ ≈ 3%. The 10 ms mark is now only the write's p97.

The lesson: waiting for all replicas hurts both availability and tail latency. Majority quorums are the sweet spot, which is why Raft, Paxos and Dynamo-style systems all use them.

Correlation breaks the arithmetic. The numbers above assume failures are independent.

  • Three replicas in one rack share a switch and a power feed; three in one zone share a building.
  • If two of the three replicas share a zone, a single zone outage stops majority writes completely.
  • So production placement spreads replicas across failure domains, ideally three Availability Zones, so that one power or network event takes out at most one replica.

How stale is "eventually"? Putting numbers on it#

"Eventually consistent" says nothing about how long. In a healthy system the answer is usually milliseconds, and you can measure it and reason about it.

Replication lag. With a primary and asynchronous replicas, lag is the time between a commit on the primary and its apply on the replica.

  • Within one region, it is typically a few milliseconds at p50 and tens of milliseconds at p99.
  • It can jump to seconds or minutes under heavy write load, long-running queries on the replica, or a replica restart.
  • Monitor it and alert on it: pg_stat_replication in PostgreSQL, or Seconds_Behind_Source in MySQL.

Stale-read probability. Suppose lag has a p50 of 5 ms and a p99 of 80 ms.

  • A user who reads from a replica 1 ms after their own write almost certainly sees old data. That is the "my change did not save" bug.
  • A different user who reads the same item 500 ms later almost certainly sees the new value.
  • So the anomalies concentrate on the writer's own reads, which is exactly what read-your-writes routing fixes cheaply.

Bailis and colleagues formalised this as probabilistically bounded staleness (PBS) in "Probabilistically Bounded Staleness for Practical Partial Quorums" (VLDB 2012). Given measured write and replication latencies, PBS predicts the probability that a read made a time t after a write returns the latest value, for any choice of N, R and W.

Their analysis showed that, with realistic latencies, partial quorums (R + W ≤ N) usually return fresh data shortly after a write. That explains why many systems run happily with weak settings, even though those settings promise nothing.

The data-loss window. Lag also sets how much you can lose.

  • If the primary commits 2,000 writes per second and the replica is 100 ms behind, about 200 acknowledged writes exist only on the primary at any moment.
  • If the primary dies and the replica is promoted, those 200 writes are gone. That is a recovery point objective (RPO) of 100 ms.
  • This is why "async replica plus automatic failover" is neither CP nor AP. It can lose acknowledged writes, so it is not consistent, and it cannot accept writes on the side without the primary, so it is not CAP-available.
  • Synchronous replication to at least one standby sets the RPO to zero, at the price of one extra round trip per commit: PACELC again.

The sequence below shows the standard read-your-writes fix: the session remembers the log position of the user's last write.

When to Use It#

  • During non-functional

  • During non-functional requirements: ask "does every read need the latest write?" for each core operation.

  • When choosing a database and its replication mode, or its per-request consistency level.

  • When designing multi-region systems, where PACELC's latency cost is large.

  • When deciding what a component does during a network failure: refuse, wait, or serve stale.

  • When explaining why a cache, search index or replica may be behind, and whether that is acceptable.

When NOT to Use It#

  • Do not use CAP to describe single-node systems; there is nothing to partition.
  • Do not label whole products "CP" or "AP"; specify per operation.
  • Do not use CAP to reason about latency, durability or transactions; use PACELC, durability models and isolation levels.
  • Do not spend interview time on CAP theory for a system whose consistency needs are obvious and simple; state the choice and move on.

How to Implement It#

  1. List the core operations (read profile, post, book seat, pay) and ask for each: "Would stale or conflicting data be harmful?"
  2. Classify each as strong (CP/EC), session-level (read-your-writes, monotonic) or eventual (AP/EL), and write the expected staleness bound ("feeds may lag up to 5 seconds").
  3. Pick storage and settings per class: a consensus or single-leader store for strong operations; replicas, caches and CDC for eventual ones.
  4. Configure consistency per request where the store allows it.
  5. Define partition behaviour: which side keeps serving, which operations are rejected, and what the user sees.
  6. Handle reconciliation for AP writes: last-writer-wins only where losing updates is acceptable; otherwise version vectors or CRDTs, or partition ownership so each key has one writer.
  7. Test it: inject partitions and clock skew (Jepsen-style tests, chaos tools) to verify the guarantees you rely on.
Per-operation consistency settings (illustrative)
  DynamoDB:   GetItem(..., ConsistentRead=true)          # strong read from leader
              GetItem(...)                               # default: eventually consistent
  Cassandra:  SELECT ... USING CONSISTENCY LOCAL_QUORUM   # (set per statement in drivers)
              INSERT ... at consistency ONE              # fastest, AP
  MongoDB:    writeConcern { w: "majority" }             # survives primary failover
              readConcern  "linearizable" / "majority" / "local"
  PostgreSQL: synchronous_commit = on + synchronous_standby_names   # RPO 0
              read from primary for read-after-write; replicas for the rest
TechnologyFits when
PostgreSQL / MySQL single primaryStrong consistency in one region; replicas for eventual reads
Google Spanner, CockroachDB, YugabyteDBStrong consistency across zones or regions, accepting write latency
etcd, ZooKeeper, ConsulSmall, critical metadata: leader election, locks, config
Cassandra, ScyllaDB, RiakAlways-writable, high-throughput, tunable per query
DynamoDBManaged key-value with per-read choice of strong or eventual
Redis replicas, CDNs, search indexes via CDCFast, eventually consistent read paths

Trade-offs#

ChoiceGainCostPick when
CP (refuse on minority side)One agreed truth, no conflictsErrors or waiting during partitionsMoney, inventory, bookings, locks
AP (answer locally)Always answersStale reads, conflicts to resolveFeeds, profiles, carts, counters, DNS
EC (sync coordination)Latest data on every readHigher latency, especially cross-regionCorrectness-critical operations
EL (local reads, async replication)Fast responsesStaleness windowRead-heavy, latency-sensitive features
Quorum reads and writes (R + W > N)Usually latest data, tolerates a replica down~2x the replica round trips; not full linearizabilityTunable stores needing stronger reads
Per-feature mixRight guarantee per operationMore design and testing effortAlmost every real product
Fast hold (Redis TTL) in front of a DB checkFew collisions reach payment, no cron jobsTwo stores to keep in step; Redis is only a hintReservations, carts, ticket holds
Virtual waiting queueProtects the consistent core at extreme demandUsers wait; extra infrastructureFlash sales, high-demand on-sales
Fail openService keeps workingProtection or checks disappear during the outageFeature flags, discovery, some limiters
Fail closedInvariants and limits holdLegitimate requests rejectedLocks, money movement, safety checks
Single home per key (geo-sharding, home regions)Local, consistent writes; partitions stay localCross-shard queries and moves are harderLocation data, mailboxes, per-user data

Common Pitfalls#

  • Saying "we'll pick CA" for a distributed system.
  • Labelling the whole system AP and then using eventually consistent reads for a balance check or seat booking.
  • Assuming a cache or replica is consistent with the primary immediately after a write.
  • Using last-writer-wins with unsynchronised clocks and silently losing updates.
  • Reading from a replica right after a write and showing users that their change "did not save".
  • Holding database locks for minutes during user interaction instead of using short transactions with reservations or expiries.
  • Believing a database's marketing claims without checking its documented behaviour under partitions; independent testing has found many systems violating their claimed guarantees.
  • Relying on a cron job for correctness: if the cleanup of expired holds stops, inventory silently disappears.
  • Using a Redis lock with a TTL as the only guard on money or inventory, with no fencing token or final database check.
  • Treating a timeout as a failure and retrying a non-idempotent operation, which produces double charges.
  • Waiting for every replica (W = N) "to be safe", which lowers both availability and tail latency.
  • Placing two of three consensus replicas in the same zone, so one zone outage stops all writes.

Real-World Examples#

Amazon's Dynamo paper (DeCandia et al., SOSP 2007) describes a deliberately always-writable shopping cart. During failures, it accepts writes on any reachable replica and later merges divergent cart versions, preferring that an item occasionally reappear over customers being unable to add items.

Google's Spanner paper (Corbett et al., OSDI 2012) describes a globally distributed database with externally consistent transactions, using Paxos replication and TrueTime, which bounds clock uncertainty with GPS and atomic clocks. Brewer's 2017 note explains why Spanner is formally CP, yet available enough in practice that users treat it as both.

Kyle Kingsbury's Jepsen project has tested many distributed databases under network partitions and published cases where systems lost acknowledged writes or returned stale reads despite their documentation. It is a reminder to verify guarantees rather than assume them.

DNS is a large-scale AP system: resolvers cache records for their TTL and keep answering even when authoritative servers are unreachable, accepting staleness for availability.

Amazon's DynamoDB paper (Elhemali et al., USENIX ATC 2022) shows a per-request CAP choice inside one product. Each partition is a three-replica Multi-Paxos group across three zones; writes and strong reads go through the leader, and default reads may come from any replica. Strong reads cost twice the read capacity of eventual ones.

Brewer's "CAP Twelve Years Later" (IEEE Computer, 2012) uses ATMs to illustrate partition mode. A disconnected ATM may allow withdrawals up to a fixed limit, and the bank reconciles and compensates afterwards. This bounds the risk instead of choosing purely between refusing and paying out.

In the Interview#

Walking through CAP in an interview#

CAP is usually the first non-functional requirement you state, because it shapes almost every later choice. Here is a five-step script, applied to a dating app that has swiping and matching.

  1. Name the operations. "The core operations are viewing profiles, swiping, and creating a match when two people both swipe right."
  2. Apply the harm test to each one.
    • "If a profile photo is a few seconds old, nobody is hurt, so profile viewing and recommendations favour availability."
    • "A match must be seen consistently: if Alice sees 'it's a match' and Bob never does, the product is broken. So match creation needs a single atomic decision."
  3. Say how each choice is implemented.
    • Profiles: served from caches and replicas.
    • Swipes: written to a store keyed by the pair of user IDs (smaller ID first), so both swipes for a pair land in one place. One atomic operation records the swipe and checks for the reverse swipe: a conditional write, a transaction, or a Redis Lua script on one shard.
  4. Say what happens in a partition.
    • "If the swipe store's partition is unavailable, we queue the swipe on the client and retry. We never create half a match."
    • "Profile reads keep working from replicas."
  5. Quantify the staleness. "Profile and recommendation data may lag by a few seconds. Each user's own edits are read from the primary for 10 seconds after they write."

This takes under a minute. It shows that you understand CAP as a per-operation decision with concrete mechanisms, and that is what the interviewer is listening for. Come back to it when you pick databases ("Postgres for swipes, because we need the atomic check"), caches ("profiles are cached with a 60-second TTL; staleness is acceptable"), and replication ("async replicas for profile reads").

Deep Dive: The proof, linearizability and harvest/yieldShow

Linearizability, defined by Maurice Herlihy and Jeannette Wing in 1990, is the strongest single-object consistency model. Each operation appears to take effect atomically at some point between its invocation and its response, and all clients agree on the resulting order. Once any read returns a new value, no later read anywhere may return the old one.

The Gilbert-Lynch proof ("Brewer's Conjecture and the Feasibility of Consistent, Available, Partition-Tolerant Web Services", ACM SIGACT News, 2002) models an asynchronous network, with no bound on message delay, where messages can be lost.

  • The argument. Split the nodes into two non-empty groups G1 and G2 and drop all messages between them. A write in G1 must complete, by availability, without G2 hearing of it. A later read in G2 must return, also by availability, and can only return the old value, which violates linearizability.
  • Partially synchronous networks. Even if messages are eventually delivered within bounds, the same argument holds during the window when they are lost.
  • What is achievable. You can provide eventual consistency with availability, or "delayed-t" consistency (consistent once the network has been healthy for some time t).

What CAP does not say. It does not say partitions are common, that you must choose once, or that weaker models are useless. Many weaker models remain achievable with full availability:

  • causal consistency and its variants: Mahajan, Alvisi and Dahlin showed in 2011 that a causal model called "real-time causal" is the strongest achievable in an always-available, one-way convergent system;
  • read-your-writes, for sticky clients;
  • monotonic reads.

Harvest and yield. Before CAP was formalised, Armando Fox and Eric Brewer ("Harvest, Yield, and Scalable Tolerant Systems", HotOS 1999) offered a more practical lens. Yield is the fraction of requests answered. Harvest is the fraction of the data reflected in each answer. A search engine with one of 100 index shards down can answer every query (100% yield) with 99% of the data (99% harvest), instead of failing queries. Many real systems degrade harvest rather than yield. This is a third option the binary CAP framing hides, and it is often what users actually prefer.

Deep Dive: Partitions in practice and how systems behaveShow

How common are partitions? Peter Bailis and Kyle Kingsbury's "The Network is Reliable" (ACM Queue, 2014) collected public reports from many organisations: switch failures, misconfigurations, NIC bugs, long GC pauses and cloud network events. Their conclusion: partitions are not theoretical. They happen within data centers as well as between them, and they often cause software that was never tested against them to misbehave. Large operators have reported multi-minute partitions occurring several times a year in some environments.

What CP systems actually do.

  • Raft (Ongaro and Ousterhout, 2014) and Multi-Paxos groups elect a leader that needs a majority. On the minority side, the old leader can no longer commit writes, because it cannot gather acknowledgements, and it steps down when its lease or term expires. Reads that must be linearizable either go through the log or use leader leases with bounded clock drift.
  • The majority side elects a new leader within an election timeout, often 1-10 seconds in production configurations, and continues serving.
  • Clients connected to the minority side see timeouts and must retry against the majority.

What AP systems do.

  • Dynamo-style stores accept writes on whichever replicas are reachable. Sloppy quorums may even write to temporary substitute nodes and hand the data back later (hinted handoff).
  • After healing, anti-entropy (Merkle-tree comparison) and read repair converge the replicas.
  • Conflicting concurrent updates are resolved by last-writer-wins, by application-level merge of "siblings" detected with version vectors, or automatically by CRDTs (Shapiro, Preguiça, Baquero and Zawirski, 2011). Examples are grow-only sets, observed-remove sets, and counters that sum per-replica increments.

Systems that are neither.

  • Redis with asynchronous replication and automatic failover can lose acknowledged writes during failover. Its documentation states that Redis Cluster does not guarantee strong consistency.
  • MySQL or PostgreSQL with asynchronous replicas and automated promotion can do the same.

These systems are designed for performance and simplicity, which is a perfectly valid choice, but you must not rely on them for linearizable operations such as locks guarding money unless you add fencing at the storage that enforces correctness.

Clocks complicate everything. Last-writer-wins depends on timestamps, and clocks drift and jump. Leader leases depend on bounded drift. Spanner makes uncertainty explicit with TrueTime intervals and waits out the uncertainty, a few milliseconds, before committing. Other systems use hybrid logical clocks (HLC) to order events without trusting wall clocks completely. See Distributed Systems Fundamentals.

Deep Dive: The cost of consistency across regionsShow

Suppose a service runs in three regions (US-East, US-West, EU-West) and wants strongly consistent writes. Approximate round trips between them:

  • US-East to US-West: ~65 ms;
  • US-East to EU-West: ~80 ms;
  • US-West to EU-West: ~140 ms.

Consensus write with the leader in US-East. The leader needs one other replica's acknowledgement for a majority of 3, and the nearest is US-West at ~65 ms. Every committed write therefore costs at least ~65 ms plus local work. A client in EU-West first travels ~80 ms to reach the leader, so its writes cost about 145 ms or more.

Linearizable reads.

  • If reads go through the leader, an EU reader pays ~80 ms.
  • With leader leases, the leader can answer reads locally, but the reader still pays the trip to the leader.
  • Follower reads at a timestamp (Spanner and CockroachDB offer these) serve a slightly stale but consistent snapshot from the local replica in ~1 ms. This is PACELC's "L" chosen per query.

Options that reduce the cost:

  • Home regions / partitioned ownership: each user's data has a primary region near the user. Writes are consistent and local for that user; only cross-user operations pay cross-region latency.
  • Asynchronous geo-replication for everything that can be eventually consistent, keeping one consistent region for critical operations.
  • Commutative operations (CRDT counters, append-only logs) that never need coordination.
  • Escrow or reservations: give each region a share of a limited resource (say, 1,000 of the 10,000 tickets) to sell locally without coordination, and rebalance shares occasionally. Coordination is needed only when a region runs out.

The general rule: coordinate only where invariants demand it. Bailis and colleagues formalised this in "Coordination Avoidance in Database Systems" (VLDB 2015). They showed that many application invariants can be maintained without coordination, while some, such as uniqueness and "balance never negative", require it.

Deep Dive: Resolving conflicts in AP systemsShow

Choosing availability means two sides of a partition may both accept writes to the same key. When the link heals, the system holds two versions and must produce one. There are four main strategies, from simplest to most robust.

1. Last-writer-wins (LWW). Keep the version with the highest timestamp and drop the other. Cassandra does this per column.

  • It is simple and needs no application code.
  • It silently loses data. If two users each add an item to a shared list at nearly the same time, one item disappears.
  • It depends on clocks. A node whose clock runs 2 seconds fast wins every conflict for 2 seconds, even against later writes.

Use LWW only where a lost update is truly harmless, such as "last seen" timestamps or cache-like data.

2. Version vectors plus application merge. Each replica keeps a counter per node. Comparing two vectors shows whether one version descends from the other, so the newer one wins, or whether they are concurrent, in which case both are kept as siblings.

  • Amazon's Dynamo returned all siblings to the application, which merged them. For the shopping cart, the merge was a union of items.
  • Riak exposes the same model.
  • It never loses writes silently, but every reader must handle siblings. That code is easy to get wrong, and a union-based merge can resurrect deleted items. The Dynamo paper notes that deleted cart items occasionally reappeared.

3. CRDTs (conflict-free replicated data types). These are data structures whose merge function is commutative, associative and idempotent. Replicas can therefore exchange states or operations in any order, any number of times, and still converge to the same value. Shapiro and colleagues formalised them in 2011.

  • G-Counter: each replica increments its own slot, and the value is the sum of all slots. Two sides counting 120 and 80 likes during a partition merge to exactly 200, with nothing lost.
  • PN-Counter: two G-Counters, one for increments and one for decrements. It suits stock levels that may go up and down, but it cannot by itself enforce "never below zero".
  • OR-Set (observed-remove set): each add is tagged with a unique ID, and a remove deletes only the tags it has observed. A concurrent add therefore survives a remove, which avoids the resurrect-or-lose dilemma of naive sets.
  • LWW-Register and multi-value registers handle single values.
  • Sequence CRDTs, such as RGA, or the related operational-transformation approach, power collaborative text editors.

Redis Enterprise's active-active databases, Riak's data types and Automerge or Yjs in collaborative apps all rely on CRDTs.

4. Avoid conflicts by design. Give each key a single writer:

  • shard by user so each user's data has one home region;
  • route all writes for a document through one leader;
  • use append-only event logs, where two appends never conflict.

This is often the most practical answer. Many "AP" multi-region systems are really "single writer per key, many readers everywhere".

The limit of all four. No merge function can enforce an invariant that spans replicas, such as "at most 500 tickets sold", "balance never below zero" or "username is unique". Two sides can each sell the last ticket, and no merge can unsell one. Such invariants need coordination: consensus, a single owner, or escrow that pre-splits the resource. Otherwise you need compensation afterwards, such as cancelling the later order and apologising. Pat Helland and Dave Campbell called this style "memories, guesses and apologies" in "Building on Quicksand" (CIDR 2009). That is the deepest reason ticket booking is CP and like counts are AP.

Deep Dive: Locks, leases and fencing tokensShow

In a distributed system, a lock is really a lease: a permission that expires after a set time. It has to expire, because a holder that crashes must not block everyone forever. But leases create a subtle failure: the holder may believe it still holds the lease after the lease has expired.

The failure.

  1. Worker A acquires a 10-second lock.
  2. A then pauses for 15 seconds, perhaps in a GC pause, a VM migration, or a stalled disk.
  3. The lock expires. Worker B acquires it and writes to storage.
  4. A wakes up, still believes it holds the lock, and also writes.

Both workers wrote "exclusively". No amount of care inside the lock service can prevent this, because the problem is A's stale belief, not the lock service's state.

The fix: a fencing token.

  • Every time the lock service grants the lock, it also returns a number that only ever increases: 33, then 34.
  • The holder sends its token with every write.
  • The storage rejects any write carrying a token lower than one it has already seen.

In the failure above, A's late write carries token 33 and arrives after B's write with token 34, so it is rejected.

The Redlock debate. Martin Kleppmann's 2016 essay "How to do distributed locking" used this argument against relying on Redis's Redlock algorithm for correctness-critical locks. Redlock does not produce fencing tokens, and it depends on timing assumptions. Salvatore Sanfilippo, the creator of Redis, published a rebuttal. Practitioners have broadly settled on the following:

  • Efficiency locks, which avoid duplicate work where an occasional double execution is harmless: a Redis lock with a TTL is fine.
  • Correctness locks, which guard money, inventory or exclusive leadership: use a consensus-backed service such as etcd, ZooKeeper or Consul.
    • It can supply monotonic numbers to use as tokens, such as etcd revision numbers or ZooKeeper sequential node numbers.
    • The storage must check those tokens.
    • Alternatively, as in the ticketing example, let the database's own conditional update be the final arbiter.

This is the ticketing design's reasoning in general form. The Redis hold is an efficiency lock, and the optimistic check in the database plays the role of the fence.

Leases and fast reads. Leases also explain how CP leaders serve fast reads.

  • Lease reads. A Raft or Multi-Paxos leader holding a lease of, say, 10 seconds knows that no other leader can be elected before the lease expires. It can therefore answer reads locally, with no quorum round trip. This is safe only if clocks drift by less than the safety margin built into the lease.
  • Read index. Systems that do not want to trust clocks use a read index instead. The leader records its current commit index and confirms with a quorum heartbeat that it is still the leader. It then serves the read once its state machine has applied entries up to that index.
  • etcd uses the read-index approach for its linearizable reads.
Deep Dive: What a consensus write actually costsShow

Step through a Raft write in a three-node group (a leader L and followers F1 and F2) to see where the latency of "C" comes from.

  1. The client sends the write to L. If it reached a follower instead, it is redirected, costing one extra hop.
  2. L appends the entry to its log and fsyncs it. An fsync costs from tens of microseconds to about a millisecond on an NVMe SSD, and often 1-5 ms on network-attached cloud disks.
  3. L replicates in parallel. It sends AppendEntries to F1 and F2 at the same time. Each follower appends the entry, fsyncs it, and replies.
  4. The entry commits. As soon as one follower has replied, the entry is committed, because L plus one follower is a majority of 3. L applies the entry to its state machine and replies to the client.
  5. Followers catch up. They learn the new commit index on the next heartbeat or append, and apply the entry.

So latency ≈ the client-to-leader hop + the leader's fsync + one round trip to the faster follower + that follower's fsync.

DeploymentRough arithmeticWrite latency
One zone0.5 + 1 + 0.5 + 1 ms~3 ms
Three zones in one region0.5 + 1 + 1.5 + 1 ms~4 ms
Three regions, nearest follower 65 ms away0.5 + 1 + 65 + 1 ms~70 ms

Raising throughput. Two techniques help:

  • Group commit: batch many writes into one log append and one fsync.
  • Pipelining: send the next appends without waiting for earlier acknowledgements.

Together they raise throughput to tens of thousands of writes per second per group. Neither removes the round trip from each write's latency.

Why this is CP. A minority leader cannot reach a majority, so it cannot commit, and its uncommitted entries are overwritten when it rejoins. Raft's election restriction says a candidate wins only if its log is at least as up to date as the logs of a majority. That guarantees the new leader holds every committed entry. Committed writes are therefore never lost and never seen out of order. The price is that the minority side cannot write.

Why throughput is bounded. Every write goes through the group's single leader. To scale, systems run many groups: DynamoDB, CockroachDB, TiKV and YugabyteDB split the data into partitions or ranges, each with its own consensus group, and spread the leaders across nodes. A cross-partition transaction then needs an extra protocol on top, such as two-phase commit across groups, which is where much of the complexity of distributed SQL lives.

Paxos and Raft. Raft (Ongaro and Ousterhout, "In Search of an Understandable Consensus Algorithm", USENIX ATC 2014) is essentially a specific, carefully specified form of Multi-Paxos with a strong leader.

  • Leslie Lamport's original Paxos ("The Part-Time Parliament", ACM TOCS 1998) agrees on a single value.
  • Multi-Paxos runs a sequence of Paxos instances with a stable leader, so that each write skips the first phase.
  • Once a leader is established, both cost one round trip to a majority per write.

Variants trade differently:

  • EPaxos (Moraru, Andersen and Kaminsky, SOSP 2013) is leaderless. Any replica can commit non-conflicting commands in one round trip to a nearby quorum, which helps geo-distributed deployments.
  • Flexible Paxos (Howard, Malkhi and Spiegelman, 2016) showed that only the leader-election quorum and the replication quorum need to intersect, not every pair of quorums. That allows a small replication quorum paired with a large election quorum.
  • Log-only or witness replicas store the log but not the full data, so quorum can be restored quickly and cheaply after a failure. DynamoDB's log replicas are an example.
Deep Dive: CAP, FLP and the limits of agreementShow

CAP is one of several impossibility results. Knowing its neighbours stops you over-applying or under-applying it.

FLP. "Impossibility of Distributed Consensus with One Faulty Process" (Fischer, Lynch and Paterson, JACM 1985) proved this: in a fully asynchronous system, with no bound on message delay, no deterministic algorithm can guarantee that consensus always terminates if even one process may crash.

  • The reason mirrors CAP: a process cannot tell "crashed" from "slow".
  • Practical consensus algorithms sidestep FLP by guaranteeing safety always and liveness only when the network behaves, meaning timeouts eventually work.
  • Raft never commits conflicting values, but it may fail to elect a leader during prolonged instability. That is "CP" in practice.

CAP places a stronger demand: every non-failing node must respond, even when messages are lost. FLP says you cannot always decide. CAP says you cannot always both answer and be linearizable.

Latency lower bounds are the formal relatives of PACELC. Lipton and Sandberg (1988), and Attiya and Welch ("Sequential Consistency versus Linearizability", ACM TOCS 1994), proved that for sequentially consistent or linearizable shared memory, the time of a read plus the time of a write must be at least the network delay between replicas.

  • With replicas 80 ms apart, no algorithm can make both reads and writes fast.
  • You can make reads local and writes slow, or the reverse, but not both.
  • This is why consistent systems often offer fast local reads (leases, follower reads at a timestamp) paired with slower writes.

Commit wait. Spanner's TrueTime exposes the clock uncertainty ε, typically a few milliseconds, and waits it out before making a commit visible. A clock uncertainty is turned into a latency cost. The cost of consistency appears once again, this time as waiting rather than messaging.

The CALM theorem. "Keeping CALM: When Distributed Consistency Is Easy" (Hellerstein and Alvaro, CACM 2020) states that programs which are monotonic, meaning they only add facts and never retract them, can be computed consistently without coordination.

  • Monotonic: set union, counters that only grow, and "has anyone ever flagged this post?".
  • Not monotonic: "is this seat still free?" and "is the balance above zero?". New information can invalidate an earlier answer to these.

This is the formal version of the rule "coordinate only where invariants demand it", and it gives a clean test for which features can be AP without losing correctness.

Putting it together: coordination is needed exactly where an answer can be invalidated by information you have not seen yet. CAP says that during a partition you cannot get that information. CALM says which questions do not need it.

Deep Dive: Verifying guarantees under failureShow

Documentation describes intended behaviour; testing under faults reveals actual behaviour. Kyle Kingsbury's Jepsen project popularised a four-step method.

  1. Run the system and concurrent clients. Start a cluster of the system under test, plus several clients issuing operations concurrently: reads, writes, compare-and-set, and transactions.
  2. Record a history. For each operation, record its invocation time, completion time and result. Timeouts are recorded as "unknown".
  3. Inject faults with a nemesis. Meanwhile, a nemesis injects faults:
    • network partitions, through firewall rules;
    • process kills, and pauses with SIGSTOP;
    • clock skew;
    • disk faults.
  4. Check the history. Afterwards, a checker decides whether the history is consistent with the claimed model.
    • Linearizability. Knossos (Jepsen's checker) or Porcupine searches for a valid sequential order. This is NP-complete in general, so histories are kept modest or split by key.
    • Transactional isolation. Elle (Kingsbury and Alvaro, VLDB 2020) infers dependency cycles from histories of list-append operations, and efficiently reports anomalies such as lost updates and write skew.

The indeterminate result. A crucial subtlety is the operation whose outcome is unknown. If a write times out, it may or may not have happened.

  • A correct checker must consider both possibilities.
  • A correct client must treat a timeout as "unknown", never as "failed". It should use idempotency keys, or a follow-up read, to find out what happened.
  • Many application bugs, especially double charges, come from treating a timeout as a failure and retrying a non-idempotent operation.

Over the years, such testing has found acknowledged writes lost during leader elections, stale reads from "strongly consistent" modes, and split-brain during partitions, all in widely used databases. Vendors have generally fixed the reported issues.

For your own systems:

  • write down the guarantee each critical operation relies on, for example "seat booking: never two confirmed bookings for one seat";
  • turn it into an invariant check that runs in tests and in production, such as a nightly query for seats with two confirmed bookings;
  • run fault-injection drills in staging and, carefully, in production: partition a zone, or kill the primary mid-transaction;
  • measure failover duration and data loss, and compare them with your stated recovery time objective (RTO) and recovery point objective (RPO).

Key Takeaways#

  • CAP: during a network partition, a replicated system must choose, per operation, between consistency (latest data or error) and availability (always answer, maybe stale).
  • Partition tolerance is not optional in distributed systems; "CA" only exists on a single node.
  • CAP's C means linearizability, not ACID's C; CAP's A is strict and differs from uptime percentages.
  • PACELC adds the everyday cost: without partitions, stronger consistency means more coordination and higher latency, especially across regions.
  • Choose per feature: strong consistency for bookings, inventory, payments and locks; availability and low latency for feeds, profiles, browsing and counters.
  • Use session guarantees (read-your-writes, monotonic reads) and CDC-fed caches and indexes to make AP paths feel consistent to users.
  • Many databases are tunable per request; state the setting, not just the product name, and verify guarantees under real failures.
  • Put a fast, expiring hint (a Redis hold) in front of a small consistent core (a conditional database update), and protect that core with admission control when demand spikes.
  • Majority quorums beat "wait for all" on both availability and tail latency, but only if replicas sit in separate failure domains.
  • Fail open or fail closed is a CAP choice for infrastructure; decide it per dependency by comparing the harm of stale state with the harm of refusing.
  • Locks are leases: guard correctness with fencing tokens or a final conditional write, and treat timeouts as "unknown", not "failed".