📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

What do the CAP theorem and PACELC actually say? Explain what they don't say, why "pick two of three" is misleading, and how real databases such as SQL Server, Cosmos DB and Redis make the trade-off.

CAP and PACELC explained precisely: consistency (linearisability) vs availability during a network partition, the latency vs consistency trade-off when there is no partition, common misreadings, and how SQL Server, Cosmos DB and Redis position themselves.

Intermediate Theory Intermediate cap-theorem consistency cosmos-db distributed-systems pacelc sql-server

🎯 Key points

  • CAP: during a network Partition, a replicated store must choose Consistency or Availability (every non-failed node answers)
  • Partitions are not optional in real networks, so "CA" isn't a real choice for a distributed store
  • CAP's C is linearisability, the strongest model; real databases offer a range of weaker models depending on configuration, and it is not the C in ACID
  • PACELC: if Partition choose A or C; Else (normal operation) choose Latency or Consistency
  • The Else half matters most day to day: synchronous replication costs latency
  • Systems handle partitions with majority quorums and consensus (Raft, Paxos), automatic failover with fencing, or multi-master with conflict resolution
  • SQL Server Always On synchronous vs asynchronous commit; Cosmos DB's five consistency levels; Redis asynchronous replication
  • Choose per use case and express it to the business as RPO/RTO and staleness limits

⏱ 30-second answer

CAP says that when a network partition splits a replicated data store, it must choose between consistency (every read sees the latest write, strictly linearisability) and availability (every working node still answers). Because partitions happen in any real network, "pick two of three" is misleading: the real choice is C or A during a partition. PACELC adds the part that matters every day: Else, when there's no partition, you trade latency against consistency, because keeping replicas in sync means waiting for them. Real systems sit at different points: SQL Server Always On with synchronous commit favours consistency at the cost of latency; Cosmos DB lets you choose one of five consistency levels; Redis replication is asynchronous and can lose acknowledged writes on failover. The trade-off is per use case, not per company.

🗣 Full answer (senior)

How I would answer this in an interview

"CAP is narrower than people think. It says that if data is replicated across nodes and the network partitions, so some nodes can't talk to others, a node that receives a request has two options: refuse or wait until it can confirm the latest value, which keeps consistency but loses availability, or answer with what it has, which keeps availability but may return stale data. The C is linearisability, meaning the system behaves as if there's one copy of the data. It's not the C in ACID. And because partitions aren't something you can opt out of, 'CA' isn't really a choice for a distributed store.

PACELC, from Daniel Abadi, is more useful in practice: if there's a Partition, choose A or C; Else, choose Latency or Consistency. Most of the time there's no partition, but every synchronous replica you wait for adds latency. SQL Server Always On with synchronous-commit replicas waits for the secondary to harden the log before committing, so it's consistent but each commit pays the round trip; asynchronous replicas are faster but you can lose recent commits on failover. Cosmos DB makes the trade-off explicit with five consistency levels: Strong, Bounded Staleness, Session, Consistent Prefix and Eventual. Session is the default and gives a user read-your-own-writes without global coordination.

The mistake I see is people labelling a whole system 'AP' or 'CP' and stopping there. I decide per piece of data: an account balance or stock count needs consistency; a product catalogue or activity feed can be stale for a few seconds."


CAP in one table

Term Precise meaning
Consistency (C) Linearisability: every read returns the most recent completed write, as if there were one copy
Availability (A) Every request to a non-failed node gets a non-error response
Partition tolerance (P) The system keeps operating despite lost messages between nodes

PACELC: the everyday trade-off

System / setting During partition (P) Normal operation (E)
SQL Server Always On, synchronous commit C (commits wait or fail) C, paying replica round-trip latency
SQL Server Always On, asynchronous commit A on the primary, possible data loss on failover L
Cosmos DB, Strong C C (writes wait for a quorum; multi-region writes can't use Strong)
Cosmos DB, Session (default) A L, with read-your-writes per session
Redis with replicas A (async replication) L; acknowledged writes can be lost on failover
ZooKeeper / etcd C (minority side stops serving) C

Production example

A team put a stock-reservation counter in a multi-region Cosmos DB account with Eventual consistency to cut latency. During a regional failover drill, two regions sold the last 30 units of a promoted product twice over. Moving reservations to a single-write-region container with Strong consistency (and keeping the catalogue on Session) added about 8 ms per reservation and removed the oversells.

🔍 What the interviewer is checking

Checks whether the candidate can state CAP precisely, knows its limits, and uses PACELC to reason about real database settings.

Green flags

  • Defines C as linearisability and frames CAP as a choice during a partition.
  • Brings up PACELC and the latency cost of consistency.
  • Gives concrete settings: synchronous vs asynchronous commit, Cosmos DB consistency levels.
  • Chooses per data set.

Red flags

  • "Pick two of three" with a "CA" database.
  • Mixes up ACID and CAP consistency.
  • No mention of latency or real products.

📚 Learn in depth

1. The setting CAP describes

   Client A                         Client B
      |                                 |
  [ Node 1 ]  ====== X ======  [ Node 2 ]
   x = 2           partition        x = 1 (stale)

Client A writes x = 2 to Node 1. The link to Node 2 is broken. Client B reads x from Node 2. Node 2 can:

  • refuse or block until it can confirm the latest value → consistent, not available;
  • answer x = 1 → available, not consistent.

That's the whole theorem (Brewer's conjecture, proved by Gilbert and Lynch in 2002). It is about one specific failure, not about everyday design.

2. What CAP doesn't say

  • It doesn't say you give up one property all the time; only during a partition.
  • It doesn't cover latency, which is what users feel most.
  • "Consistency" here is linearisability, a much stronger guarantee than "constraints hold" (ACID's C).
  • "Availability" means every non-failed node answers; a system that serves from the majority side only is not "available" in CAP's sense, yet may be highly available in practice.

3. PACELC and why latency is the real cost

Keeping replicas consistent means a write must reach several nodes before it's acknowledged. Across Azure Australia East and Australia Southeast that is roughly 10–15 ms per round trip; across continents 150 ms or more. So even with no failures you choose: wait (consistency) or acknowledge locally and replicate later (latency).

4. How real systems choose

  • SQL Server Always On availability groups: synchronous-commit secondaries harden the log before the primary commits (no data loss on automatic failover); asynchronous-commit secondaries don't (possible data loss, lower latency). Readable secondaries can lag behind even in synchronous mode, because redo runs asynchronously.
  • Azure SQL geo-replication / failover groups: asynchronous; a forced failover can lose recent transactions.
  • Cosmos DB: five levels from Strong to Eventual, set per account and relaxable per request. Strong isn't available with multiple write regions.
  • Redis: replication is asynchronous; WAIT can reduce but not eliminate loss.
  • Consensus stores (etcd, ZooKeeper, Raft-based systems): a majority quorum is needed for writes; the minority side stops serving writes during a partition.

5. Making the decision per use case

Data Stale for 5 s acceptable? Choice
Account balance, stock reservation No Strong / single writer
User profile seen by its owner Owner must see own edits Session / read-your-writes
Product catalogue, feeds Yes Eventual / cache

Try it yourself

  1. Create a Cosmos DB account (or the emulator), write with Session consistency from one client and read from another client without the session token; observe that read-your-writes is per session.
  2. In a SQL Server availability group lab, compare commit latency with synchronous vs asynchronous commit using a small insert loop.
  3. Run two Redis containers with replication, write to the primary, kill it before replication and promote the replica; check what was lost.
  4. Draw your current system's data stores and label each with its PACELC choice.

💻 Code

Choosing consistency per request in Cosmos DB: the account default stays Session, a stock check asks for the strongest read the account allows, and a feed read accepts Eventual.

using Microsoft.Azure.Cosmos;

namespace Catalogue;

public sealed record StockItem(string id, string Sku, int Available);

public sealed class StockReader(CosmosClient client)
{
    private readonly Container _container = client.GetContainer("shop", "stock");

    // Strong reads need an account configured as Strong; you can only RELAX
    // consistency per request, never strengthen it beyond the account level.
    public async Task<StockItem> ReadForReservationAsync(string sku, CancellationToken ct)
    {
        var response = await _container.ReadItemAsync<StockItem>(
            sku, new PartitionKey(sku), cancellationToken: ct);
        return response.Resource;
    }

    // A product page can accept slightly stale data for lower latency and cost
    public async Task<StockItem> ReadForDisplayAsync(string sku, CancellationToken ct)
    {
        var options = new ItemRequestOptions { ConsistencyLevel = ConsistencyLevel.Eventual };
        var response = await _container.ReadItemAsync<StockItem>(
            sku, new PartitionKey(sku), options, ct);
        return response.Resource;
    }
}
-- SQL Server Always On: see how far each secondary lags (consistency vs latency in numbers)
SELECT ar.replica_server_name,
       drs.synchronization_state_desc,
       drs.log_send_queue_size,   -- KB not yet sent
       drs.redo_queue_size        -- KB received but not yet redone (readable-secondary lag)
FROM sys.dm_hadr_database_replica_states AS drs
JOIN sys.availability_replicas AS ar ON ar.replica_id = drs.replica_id;

⚠ Common mistakes

  • Mistake: Saying "pick any two of C, A and P". Why it is wrong: partitions happen anyway, so the real choice is C or A during a partition. Instead: explain CAP as a choice forced by a partition, then talk PACELC.
  • Mistake: Confusing CAP's consistency with ACID's consistency. Why it is wrong: CAP's C is linearisability across replicas; ACID's C is about constraints within a transaction. Instead: say "linearisable" when you mean CAP's C.
  • Mistake: Labelling a whole product "AP" or "CP". Why it is wrong: most databases are configurable, and the right choice differs per data set. Instead: state the setting (synchronous commit, consistency level) and the data it protects.
  • Mistake: Ignoring latency. Why it is wrong: partitions are rare, but replica round trips cost latency on every write. Instead: use PACELC's Else branch to reason about everyday performance.
  • Mistake: Assuming a readable secondary is up to date because commit is synchronous. Why it is wrong: redo on the secondary is asynchronous, so reads can lag. Instead: read from the primary when you need the latest value.
  • Mistake: Choosing Eventual consistency for counters such as stock or balances to save latency. Why it is wrong: concurrent writers in different regions oversell or overdraw. Instead: use a single writer or strong consistency for invariants that matter.

🏛 Senior insight: trade-offs

CAP is a good opening line and a poor design tool. In design reviews I move quickly to PACELC and to concrete questions: what happens to this data during a regional failover, how stale can a read be before a user or the business is hurt, and how many milliseconds are we willing to pay per write to avoid that.

How real systems handle a partition. Partitions can't be prevented, only handled:

  • Majority quorums and consensus (Raft in etcd, Paxos-style protocols in Cosmos DB's replica sets): only the side with a majority accepts writes, so the minority becomes unavailable but never diverges.
  • Single primary with automatic failover and fencing (SQL Server availability groups, Azure SQL failover groups): a witness or cluster quorum decides which node is primary, and the old primary is fenced so two primaries can't both accept writes.
  • Multi-master with conflict resolution (Cosmos DB multi-region writes with last-writer-wins or custom merge): stays available on both sides and reconciles afterwards, which only works for data where merging is acceptable.
  • Sharding limits the blast radius: a partition affects only the shards whose replicas are split.

Explaining it to non-engineers. Product owners don't need the theorem; they need the consequence in their terms. I translate it into RPO (how much recent data we could lose in a failover: zero with synchronous commit, seconds with asynchronous geo-replication), RTO (how long we're down), and staleness ("a customer may see a stock count up to 5 seconds old"). Then the business picks, per feature, and the choice goes into an ADR.

Option When it fits Cost When not to
Strong / synchronous replication Money, stock, uniqueness Write latency, lower availability in a partition High-volume, low-value data
Session / read-your-writes Users editing their own data Session token handling Data shared and updated by many users at once
Eventual / multi-master Catalogues, feeds, analytics Stale reads, conflict handling Invariants such as "never below zero"

🔗 Follow-ups the interviewer may ask

  1. When: Candidate describes what a node does when it can't reach its replica. Why: Checks that the candidate links partitions to the unknown outcome of a remote call.
    How to answer

    Partial failure means part of a distributed system fails while the rest keeps running, and no single node can see the whole picture. The sharpest example is a timeout: when your call to the payments service times out, the request might have been lost, the service might have crashed before or after charging the card, the response might have been lost, or it might still be running. A timeout means the outcome is unknown, not that it failed. So calling code must be written for the unknown: make the operation idempotent (or send an idempotency key) so a retry can't do the work twice, or look up the outcome by a client-generated id before retrying, and run reconciliation for anything left in doubt. The trade-off is extra design work on every write that crosses the network.

  2. When: Candidate says a read model or replica can be stale. Why: Checks how eventual consistency surfaces in application design and the UI.
    How to answer

    CQRS splits the model that changes state (commands) from the model that reads it (queries). It grows out of Meyer's CQS (a method either changes state or returns data), applied to whole models.

    • Write side: aggregates with invariants, loaded through repositories, committed by the unit of work.
    • Read side: flat DTOs shaped per screen, projected with Select/AsNoTracking or Dapper.

    There are levels. Separate handlers on one database is cheap and often enough. Denormalised read tables updated in the same transaction stay consistent. A separate read store fed by events scales reads but is eventually consistent, so the UI needs read-your-writes or "processing" states.

    CQRS doesn't need MediatR or event sourcing. It's overkill for CRUD where reads and writes have the same shape. The trade-off is optimised, simple models on each side against more moving parts and, at the top level, stale reads.

↩ Usually asked after

More in Distributed Systems Core Concepts

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me