Distributed systems: interview drills¶
How to use this lesson¶
This is an interview-drill set for distributed systems: 11 topics (scaling, load balancing, caching, replication, partitioning, queues and streams, delivery guarantees, retries and timeouts, failover and DR, consensus, distributed transactions) plus 23 hand-drawn diagrams and 7 interactive figures you can drag. A companion lesson, Sharding infrastructure drills, goes deep on Cassandra, CockroachDB, Vitess and Redis.
Every topic has at least 5 questions, ordered from easy to hard: question 1 is a fundamental, question 5 is usually the interviewer's follow-up. Topics 3, 4 and 5 carry a few extra questions (CDN and PoP, CAP, eventual consistency, ticket booking, DynamoDB hotspots). Each question has an italic line of ideas to cover so you can grade yourself.
- Read the question and answer out loud for 1 to 2 minutes before opening the answer.
- Open the answer and compare it with the ideas to cover line. Note what you missed.
- With the interactive figures, predict what will happen, then press the buttons or drag the sliders.
Numbers such as throughput limits and defaults change between versions, so check the docs before using them in a real design. You can switch the language of this lesson with the EN / VI buttons in the header.
Contents
Jump to a topic.
- 1 · Scaling: up, out and stateless (diagrams + interactive figure)
- 2 · Load balancing (diagrams)
- 3 · Caching and CDNs (diagrams + interactive figure)
- 4 · Replication and consistency (diagrams + interactive figure)
- 5 · Partitioning and consistent hashing (diagrams)
- 6 · Queues, pub/sub and streams (diagrams + interactive figure)
- 7 · Delivery guarantees and idempotency (diagrams)
- 8 · Timeouts, retries and circuit breakers (diagrams + interactive figure)
- 9 · Availability, failover and disaster recovery (diagrams + interactive figure)
- 10 · Consensus and leader election (diagrams + interactive figure)
- 11 · Distributed transactions and sagas (diagrams)
- Bonus · Sharding infrastructure
- Quick technology guide
1 · Scaling: up, out and stateless¶
One machine only grows so far. Scaling out (adding machines) needs stateless app servers so any server can replace any other. But adding machines is not free: every time you replicate a tier, the bottleneck moves to the next tier, usually the database.
1.1 Why does adding machines not scale throughput linearly, and sometimes make it worse?
Ideas to cover: Amdahl's law, Universal Scalability Law (contention and coherency), the serial part of a system.
Two models to know:
- Amdahl's law:
speedup = 1 / ((1-p) + p/N), wherepis the parallel fraction. If 5% of the work is serial (a global lock, one DB primary), the maximum speedup is 20x no matter how many machines you add. - Universal Scalability Law:
C(N) = N / (1 + a(N-1) + b*N(N-1)). The coefficientais contention (fighting over a shared resource such as a lock or a single queue). The coefficientbis coherency (the cost of keeping nodes in sync: invalidation broadcasts, O(N^2) gossip, distributed locks).
Because b is quadratic, the curve peaks and then falls: past the peak, more machines make the system slower.
The fix is to shrink what is shared and what must be synchronized: shard the data, avoid global locks, use eventual consistency where it is tolerable.
1.2 What does "stateless" really mean? Where does the state go when you remove it from the app server?
Ideas to cover: external session store, sticky sessions and their cost, JWT and revocation, state is moved down a tier, not removed.
Stateless means an instance keeps nothing the next request needs, so any instance can replace any other. State does not disappear, it moves:
| Where state lives | Cost |
|---|---|
| External session store (Redis) | One more hop, and the store itself needs HA |
| Database | Slower than memory |
| Client (cookie, JWT) | A JWT is hard to revoke: you need a blacklist, which is state again. The usual answer is short-lived access tokens plus a refresh token |
| Sticky sessions (the LB pins a user to one instance) | Uneven load, session lost when the instance dies, painful rolling deploys and scale-in |
Things that quietly make an app stateful: in-process caches, uploads stored on local disk, WebSocket connections, cron jobs that run on every instance.
1.3 You scale the app from 10 to 200 instances and the DB falls over even though its CPU is low. What happened?
Ideas to cover: connection pool times instance count, Postgres uses a process per connection, PgBouncer, Little's Law.
The cause is connection count: 200 instances times a pool of 20 is 4,000 connections. Postgres uses one process per connection (each costs RAM and context switches) and max_connections is usually a few hundred. The DB is limited by connections and memory, not CPU.
Little's Law: concurrency = throughput x latency. At 10,000 queries/s with 5 ms per query you only need about 50 queries in flight. Past a few times the core count, more connections do not add throughput, only contention.
Fixes:
- PgBouncer (transaction pooling) or a similar proxy: multiplex thousands of client connections onto a few dozen server connections.
- Cap the pool per instance.
- Caveat: transaction pooling breaks features tied to a session, such as session-level
SET, advisory locks and (depending on version) prepared statements.
1.4 Why does autoscaling on CPU often fail to save you in a traffic spike?
Ideas to cover: metric delay, startup and warm-up time, cold caches, scaling on queue depth or RPS, deliberate over-provisioning.
- The metric is slow: scrape, evaluate, then cooldown takes minutes.
- New instances need time: boot, pull the image, JIT warm-up, build connection pools, cold caches. Meanwhile the old instances are overloaded, latency rises, timeouts fire, retries start, and it gets worse.
- CPU is a poor signal for I/O-heavy services: threads are waiting, so CPU is low while the service is already saturated.
- New instances get a full share of traffic the moment they join, with cold caches.
Better: scale on leading indicators (in-flight requests, RPS per instance, queue depth), keep headroom (target 50 to 60% utilization), scale on a schedule for known events, use LB slow-start and warm pools, and shed load to survive the wait.
1.5 When is scaling a DB up the right answer, and what should you try before sharding?
Ideas to cover: read replicas, cache, indexes and queries, real limits of one node, operational cost of sharding.
Scale up is right when the data still fits one machine (modern machines have terabytes of RAM and tens of TB of NVMe), the workload needs joins and transactions, and the team is small. Sharding costs you joins, cross-shard transactions, resharding and operational complexity.
Order of things to try:
- Indexes and query tuning.
- Connection pooling.
- A cache.
- Read replicas (they only fix reads).
- Vertical split by function (each group of tables gets its own DB).
- Archive old data, partition tables inside one node.
- Shard, when writes or storage exceed one node.
2 · Load balancing¶
The load balancer decides where each request goes. Choose the wrong layer (L4 or L7) or the wrong algorithm and load is lopsided however many servers you have. The figure below has one client holding a single HTTP/2 connection and firing requests down it.
2.1 How do L4 and L7 load balancers differ, and why does gRPC over HTTP/2 often make an L4 balancer uneven?
Ideas to cover: balancing per connection versus per request, multiplexing many requests on one long connection, TLS termination.
- L4 works on TCP/UDP: it forwards by IP and port and does not read the payload. Fast, cheap, works for any protocol.
- L7 terminates HTTP and can read headers, paths and cookies. That enables routing by path or host, retries, rate limits, auth and balancing per request, at a higher CPU cost.
gRPC runs on HTTP/2, which multiplexes many requests over one long-lived TCP connection. L4 picks a backend once per connection, so a client with one connection sends every request to one backend, and a newly added backend gets nothing (exactly what the figure shows).
Fixes: an L7 LB (Envoy) that balances per request or stream, client-side load balancing with several connections, or a max connection age that forces connections to be re-established.
2.2 Why can "least connections" be worse than "power of two choices" when several load balancers run in parallel?
Ideas to cover: stale load information, herd effect, P2C samples only two machines.
With several LBs running in parallel, each one's view of load is stale. They all see "backend X is least busy" and all pile onto X, which overloads, and then they all move to another backend (the herd effect).
Power of two choices (P2C): pick two backends at random and send to the less loaded one.
- Pure random: the heaviest backend carries about
log n / log log ntimes the average. - P2C: about
log log n, exponentially better. - Because each LB samples different random pairs, they do not all converge on the same machine. Envoy's "least request" uses two choices.
2.3 You use consistent hashing at the LB to raise cache hit rate. What about a very hot key?
Ideas to cover: hash by key, hot key, bounded-load consistent hashing, the trade-off between locality and balance.
Hashing by key (user_id, URL) sends the same key to the same backend so its local cache hits more. But a hot key now lands entirely on one backend.
Options:
- Bounded-load consistent hashing: each backend has a cap of
(1+e) x average load; overflow spills to the next backend on the ring.eis the knob between locality and balance. - Replicate hot keys (hash with a salt to spread them over a few backends).
- Add a local L1 cache with request coalescing.
2.4 Shallow and deep health checks can both cause incidents. How does each one fail?
Ideas to cover: liveness versus readiness, a deep check can remove the whole fleet at once, panic threshold, hysteresis.
- Shallow (
/healthreturns 200 if the process is up): an instance with a broken DB connection, a deadlock or no memory keeps receiving traffic and returns errors. - Deep (checks the DB, cache, downstreams): when the DB slows down, every instance fails the check at once, the LB removes the whole fleet and you have a full outage where you could have had a partial degradation. Deep checks also add load.
Good practice:
- Separate liveness ("restart me") from readiness ("send me traffic").
- Readiness checks only what is local and essential; do not fail because a shared dependency is sick.
- Have a panic or fail-open threshold (Envoy defaults to 50%): if too many backends look unhealthy, ignore health checks.
- Use hysteresis (N consecutive failures to eject, N passes to re-add) and a cap on the percentage you may eject.
2.5 The LB is a single point of failure. How do you make it highly available, and what role does DNS play?
Ideas to cover: VRRP/keepalived, anycast with ECMP, Maglev, DNS TTL and caching, GSLB.
- Active-passive: VRRP/keepalived with a floating IP, failover in seconds.
- Active-active: routers hash the 5-tuple with ECMP across several LBs. If the set of LBs changes, live connections may move, so you need consistent hashing and connection tracking (Google's Maglev).
- Anycast: the same IP is advertised by BGP from many places.
- Managed services (ELB/NLB) are distributed for you.
- DNS: return several IPs or use GSLB by geography and health. The weakness is TTL and caching: resolvers and clients often ignore TTLs so failover is slow, and DNS does not know real load.
Layers are usually stacked: DNS/anycast, then L4, then L7, then the service.
3 · Caching and CDNs¶
A cache is a copy used for speed, not a source of truth. The design question is not "do we cache?" but who holds the copy, for how long, and how do we know it has gone stale. The figure shows one PoP with three cache servers that can each hold only 2 of 6 objects.
3.1 Cache-aside: what sequence of events leaves the cache stale forever, even though you "delete the cache after updating the DB"?
Ideas to cover: race between a read miss and a write, delete versus update, TTL as a safety net, CDC to invalidate.
T1 (read): cache miss, reads DB, sees v1 (old)
T2 (write): updates DB to v2, deletes cache (nothing to delete yet)
T1: sets cache = v1 <- the cache holds v1 until the TTL expires
It is unlikely (the read must be slower than the write plus the delete) but it happens at scale. Variants have races too: updating the cache instead of deleting it can be reordered between two writers, and deleting the cache before writing the DB is worse.
Mitigations:
- A TTL as a safety net (always).
- Version or CAS: only set if the version is newer.
- Lease tokens (Facebook's Memcached paper): a miss returns a token, and you may only set if no invalidation happened since.
- Invalidate through CDC (Debezium reading the binlog) so ordering matches the DB.
Never promise strong consistency from a cache.
3.2 Distinguish cache stampede, cache penetration and cache avalanche. How do you fix each?
Ideas to cover: singleflight, stale-while-revalidate, TTL jitter, Bloom filter, negative caching.
| Problem | What it is | Fix |
|---|---|---|
| Stampede | A hot key expires and thousands of requests miss together and hit the DB | singleflight / request coalescing, a short mutex during rebuild, stale-while-revalidate, probabilistic early refresh |
| Avalanche | Many keys expire at once (or a whole cache node dies) and the DB is flooded | TTL jitter, multi-tier caches, rate limits and circuit breakers in front of the DB |
| Penetration | Queries for keys that do not exist always miss | Cache nulls with a short TTL (negative caching), a Bloom filter of valid keys, input validation, rate limits |
3.3 What happens to DB load when the hit rate drops from 99% to 98%, and what does it mean for capacity design?
Ideas to cover: miss rate doubles, the cache is part of system capacity, cold start.
The miss rate goes from 1% to 2%, so DB load doubles. At 100k req/s that is 1,000 req/s reaching the DB at 99% and 2,000 at 98%.
Design consequences:
- Size the DB for the miss traffic; the cache is part of the system's capacity, not an optional optimization.
- A dead or cold cache (a mass restart) sends the DB many times its normal load, so plan warm-up, staggered restarts and rate limiting while it refills.
- If the working set is larger than the cache, the hit rate can fall off a cliff.
3.4 Why does LRU do badly under a full-table scan job? What does LFU/TinyLFU fix?
Ideas to cover: scan pollution, admission policy, count-min sketch, W-TinyLFU.
A scan touches every item exactly once and pushes the hot items out (scan pollution). Those freshly loaded items will never be used again.
Pure LFU keeps frequently used items but needs a counter per key and keeps items that were hot and have gone cold.
TinyLFU is an admission filter: when the cache is full, a new item is only admitted if its estimated frequency is higher than the victim's. Frequencies live in a compact count-min sketch that is periodically halved so it ages. W-TinyLFU (Caffeine) adds a small LRU window for items that are bursting.
3.5 Why is purging the CDN a poor design, and what is the right approach for static assets and changing content?
Ideas to cover: versioned URLs, Cache-Control (max-age, s-maxage, stale-while-revalidate), Vary exploding the cache key, origin shield.
A purge has to reach hundreds of PoPs, it is not atomic, and it takes seconds to minutes. Browser caches cannot be purged at all. A mass purge also stampedes the origin.
The right approach:
- Static assets: name files by content hash (
app.3f9a2c.js) withCache-Control: public, max-age=31536000, immutable. To change, change the name. - HTML: short TTL or
no-cachewith an ETag, pointing at the new hashed assets. - Slowly changing content:
s-maxage(CDN) different frommax-age(browser),stale-while-revalidate,stale-if-error, surrogate keys for selective purges. Vary(for exampleCookie,User-Agent) splits the cache key into countless variants and the hit rate falls toward 0. Normalize it.- Personalized content: do not cache it publicly.
- An origin shield collapses misses from many PoPs into one request to the origin.
Extra: CDNs and PoPs¶
3.6 What is a PoP, and how does a CDN partition data compared with other services?
Ideas to cover: PoP, two levels of partitioning (geography then URL hash), a CDN is not the source of truth.
A PoP (Point of Presence) is a CDN location in one geographic area, holding many cache servers that serve nearby users.
A CDN partitions at two levels:
- By geography: users are steered to the nearest PoP by Anycast (BGP chooses the path) or GeoDNS.
- By URL hash: inside the PoP, consistent or rendezvous hashing on the
cache_keyassigns each object to a few servers, so the PoP acts as one big cache.
The difference from other services: a CDN is never the source of truth, so losing a node is just a miss, not lost data; it needs no consensus, quorum or transactions. PoPs do not sync with each other and only expire by TTL or purge, which makes a CDN an extreme example of eventual consistency.
| CDN | DB sharding | Redis/Memcached | Object storage | |
|---|---|---|---|---|
| Source of truth? | No | Yes | No | Yes |
| When a node dies | A miss, refill from origin | Data loss without replicas | A miss, the DB takes more load | Nothing lost (replicated) |
| Who invalidates | HTTP headers and the purge API | Not applicable | The application | Not applicable |
| Scope | Global | Usually one region | Usually one region | Per region |
3.7 Why does hashing the URL inside a PoP raise hit rate compared with independent caches per server?
Ideas to cover: effective capacity equals the sum of servers, each object misses once per PoP, trade-offs.
With independent caches, the same object misses once on every server and every server slowly holds the same set of popular objects. The PoP's effective capacity is only one server's.
With hashing on cache_key, each object lives on exactly one server: one miss for the whole PoP, no duplication, effective capacity equal to the sum of all servers. Example: 10 servers of 10 TB and a 50 TB working set; independent caches hold only a slice, hashing fits everything. The 3D figure above runs exactly this experiment (44% versus 93% hit rate).
The cost: an extra routing step, very hot objects concentrate on one machine (question 3.8), and a dead server makes its share of keys miss (consistent hashing limits that to about 1/N).
3.8 A viral video overloads one server. How do you handle it without wrecking the hit rate of other objects?
Ideas to cover: replicate only hot objects, cache by segment, bounded-load hashing, RAM tier.
Principle: replicate only the hot object and keep everything else single-copy.
- Detect hot objects with a top-k sketch or a requests-per-second threshold.
- Replicate by heat: map the object to
kservers (rendezvous top-k orkey#0..k-1) and let the LB choose among them with P2C. The hot set is tiny, so other objects' hit rates do not change. - Bounded-load hashing: a server above
(1+e)times the average spills to the next one. - Cache small pieces: split video into few-second segments (HLS/DASH); the segments hash to many servers so load spreads on its own. Often the strongest fix for video.
- Put hot objects in RAM, use request coalescing, and shift traffic to a neighbouring PoP if the whole PoP is overloaded.
Do not replicate every object or lower the admission threshold: effective capacity shrinks and the hit rate follows.
3.9 The origin changed a file, but some countries still see the old one. List the cache layers that could be holding it.
Ideas to cover: at least 5 or 6 layers, how to diagnose with headers.
- Browser / service worker:
max-agestill valid; a CDN purge cannot reach it. - ISP, corporate or mobile-carrier proxies.
- PoP edge: TTL not expired (each PoP filled at a different time, which is why only some countries are affected), the purge has not propagated, or you purged one URL variant but others remain (query strings,
Vary). - Parent / regional tier: the edge was purged but refetches from a parent that is still stale.
- Origin shield holding an old copy.
- Origin side: the PoP in that region pulls from a lagging storage replica (cross-region replication).
- Deliberate staleness:
stale-while-revalidateorstale-if-error. - Multi-CDN or DNS: users are sent to another CDN or PoP that has not been purged.
Diagnose with curl -I from several locations and read Age, X-Cache, Via, Cache-Control, ETag. Prevent with versioned URLs and purging by surrogate key through every tier.
3.10 Why should personalized content not be cached publicly at a CDN, and how can you still benefit from a CDN?
Ideas to cover: data leaks, web cache deception, split the shell from the data, segment-based caching, signed URLs.
The risk: if the cache key does not include identity, user A's page is served to user B. In web cache deception an attacker lures a victim to /account/profile/x.css; the origin still returns the account page, but the CDN sees .css and caches it as a static file. And putting cookies or the user ID into the cache key gives every user their own copy and a hit rate near 0.
Rule: do not publicly cache responses with Set-Cookie or Authorization; use Cache-Control: private to allow browser-only caching.
Ways to still use a CDN:
- Split shell from data: cache the HTML skeleton, JS and CSS at the edge; load personal data from an API afterwards.
- ESI or edge compute to assemble shared fragments with personal ones.
- Segment-based caching (country, language, logged-in or not) instead of per user.
- Signed URLs or tokens: the content is identical for everyone allowed, so it is cacheable; the token is removed from the cache key.
- Microcaching for 1 to 5 seconds with request coalescing.
- Even uncacheable traffic benefits from TLS near the user, persistent connections to the origin, and WAF/DDoS protection.
4 · Replication and consistency¶
Replication buys availability, read capacity and latency, but the copies can disagree. Almost every question in this topic is: how far can they disagree, and what does the application see? The figure is a 3-replica quorum: a client writes v2 and then reads, and the outcome depends on W, R and the network.
4.1 How do sync, async and semi-sync replication differ in durability and latency? What happens when the sync replica dies?
Ideas to cover: whether RPO is 0, writes block when the sync replica dies, one sync plus several async.
| Mode | Behaviour | Trade-off |
|---|---|---|
| Async | The leader acks right after the local write | Fast, but if the leader dies the unreplicated writes are lost (RPO above 0) |
| Sync | Waits for the follower's ack | No data loss, but latency follows the slowest follower, and if the sync follower dies, writes hang |
| Semi-sync | Waits for at least one follower, the rest async | A balance; MySQL semi-sync times out and falls back to async, so the guarantee is only "soft" |
A common setup: keep one sync replica and the rest async, and automatically promote another replica to sync if it dies. Cross-region is almost always async because the RTT is too large.
4.2 A user posts, refreshes and the post is gone, refreshes again and it is back. Which anomalies are these, and how do you fix them?
Ideas to cover: read-your-writes, monotonic reads, consistent prefix, read from the leader for a window after a write, track the LSN.
The first refresh hit a lagging replica that did not have the post yet. Later refreshes hit replicas that had caught up. Three anomalies:
- Read-your-writes violated: the user cannot see what they just wrote.
- Monotonic reads violated: you see the new version and then an older one (bouncing between fast and slow replicas).
- Consistent prefix violated: you see the answer before the question (causally related writes landed on different partitions).
Fixes:
- RYW: read the user's own recent changes from the leader for N seconds, or have the client remember the LSN/GTID of its last write and read only from replicas that have applied it.
- Monotonic: sticky replica per user (hash the user_id).
- Consistent prefix: put causally related writes on the same partition.
4.3 What does the quorum rule R + W > N guarantee and what does it NOT guarantee?
Ideas to cover: sloppy quorum, hinted handoff, concurrent writes, partial write failures, LWW and clock skew, not linearizable.
Guarantees: the read set and write set share at least one replica, so a read sees the latest acknowledged write (if everything works).
Does not guarantee:
- Sloppy quorum plus hinted handoff: the write is accepted by nodes outside the N "home" nodes, so the overlap is gone.
- Concurrent writes: LWW picks by timestamp, and skewed clocks pick wrongly.
- Partial write failure: the client sees an error (fewer than W acks) but some replicas took the write, and that "failed" write can still be read later.
- Not linearizable: a write has reached only A. Reader 1 reads (A, C) and sees the new value; reader 2 reads (B, C) later and sees the old one: "new then old".
- To be linearizable you need a synchronous read repair before answering (the ABD idea) or consensus.
4.4 Distinguish linearizability, serializability, sequential consistency and eventual consistency with one example.
Ideas to cover: linearizable is one object and real time, serializable is transactions without real-time order, strict serializability is both, CAP and PACELC.
Example: Alice writes x=1, tells Bob by phone, and only then Bob reads x.
| Model | Scope | What Bob may read |
|---|---|---|
| Linearizable | One object, respects real time | Must see 1 |
| Serializable | Transactions over many objects, equivalent to some serial order, no real-time constraint | May see 0 |
| Strict serializable | Both (Spanner) | Sees 1 |
| Sequential | All processes see one order that respects each process's order, but not real time | May see 0 |
| Eventual | Replicas converge once writes stop | May see 0 for a while |
CAP: the "C" in CAP is linearizability. Under a partition you pick C or A. PACELC adds: with no partition you still choose between latency and consistency.
4.5 How are multi-leader write conflicts resolved, and why does LWW silently lose data?
Ideas to cover: version vectors, concurrent writes, CRDTs, application-level merge, replication topologies.
Two leaders in two data centres edit the same record. Options:
- Avoid it: route every write for a record to one leader (a "home region").
- LWW: simple, but it silently drops one write and depends on clocks. For example two people edit different fields of one document and one write overwrites the whole other.
- Version vectors: detect that two writes are concurrent and keep both (siblings) for the application to merge (Riak).
- CRDTs: data structures that merge themselves (G-counter, OR-set, sequence CRDTs for text).
A unique constraint cannot be enforced across multiple leaders.
Extra: CAP and eventual consistency¶
4.6 Can you design a "CA" system, and does every operation fall under CAP?
Ideas to cover: true CA only on one node, the trade-off only matters during a partition, the escape routes (local operations, home region, CRDTs, weaker models).
There is no CA distributed system when the network can partition: the theorem says during a partition you cannot have both C (linearizable) and A (every live node answers). "CA" only makes sense in three cases: a single node; while the network is healthy (CAP only constrains you during a partition); and "effectively CA" like Spanner (technically CP, but a private network makes partitions very rare).
Not every operation is blocked. The escape routes:
| Escape | Idea | Cost |
|---|---|---|
| Local operations | No other node is needed | Does not apply to shared data |
| Home region | Each entity has exactly one owner | If the owner is down the entity is unavailable |
| CRDTs, monotonic operations (CALM) | All replicas converge without coordination | You weaken "C" to eventual; cannot protect constraints like a non-negative balance |
| Weaker models | Causal, read-your-writes and monotonic reads are achievable together with availability | No linearizability |
Real systems mix: a small CP core (reserving a ticket, charging money), a large AP area (feeds, profiles), joined by events.
4.7 What is eventual consistency, and how do replicas actually converge?
Ideas to cover: a promise to converge without a promise about when, anti-entropy, read repair, hinted handoff, LWW, version vectors, CRDTs.
If you stop writing, then after some time all replicas converge to the same value.
The system does not promise that a read right after a write sees it, and does not say how long "eventually" is. In exchange you get low latency and high availability, even during a partition.
Convergence needs mechanisms, because two replicas can receive two different writes for the same key:
- Anti-entropy / repair (Merkle trees), read repair, hinted handoff (time-limited, Cassandra defaults to 3 hours).
- LWW (simple but drops writes), version vectors (keep both for the app to merge), CRDTs.
Fine for view counts, feeds, profiles, caches, DNS. Not fine for reserving tickets, decrementing stock, balances, unique constraints.
4.8 Ticket booking: one ticket left, two people book. What do you use to keep it ACID?
Ideas to cover: an atomic conditional UPDATE, shard by event to avoid 2PC, synchronous replication, idempotency keys, a saga for payment, caches only for display.
Conclusion: one source of truth for inventory, written with an atomic conditional operation inside a strongly consistent DB.
The naive code is wrong: both SELECT remaining and see 1, then both UPDATE remaining = 0 (a lost update). The right way:
UPDATE inventory
SET remaining = remaining - 1
WHERE event_id = :e AND remaining > 0;
-- rows affected = 1: you got the ticket; = 0: sold out
The check and the decrement are one atomic statement; two requests are queued by the row lock, and the second re-evaluates the condition on the new value and gets 0 rows. For numbered seats use a conditional state change (AVAILABLE to HELD with a TTL) and UNIQUE (event_id, seat_id) as the last safety net.
| Option | Use it for booking? |
|---|---|
One Postgres/MySQL node, sharded by event_id |
Yes, the main choice: full ACID, no 2PC needed |
| Spanner, CockroachDB, TiDB | Yes, when you need several regions; higher write latency |
DynamoDB ConditionExpression / TransactWriteItems |
Yes, if you are on AWS |
| Cassandra LWT | Only with low contention |
| 2PC | Avoid for the reserve step |
| Redis cluster | Not as the source of truth (failover can lose acknowledged commands) |
| Async replica plus CDC | For display only |
Where you can still oversell despite transactions: failover losing data (use synchronous replication), split brain, client retries (use an idempotency key), reading from a replica and then writing.
Full flow: show the event from a cache (AP); hold the ticket with a conditional UPDATE (CP) with a 10-minute TTL; pay through a gateway with an idempotency key; confirm HELD to SOLD; on expiry release the ticket (a saga); outbox then CDC to update caches and send email. When 100,000 people chase one event: per-seat rows, split the inventory into buckets, a waiting room, and Redis as a fast gate with the DB as the final judge.
5 · Partitioning and consistent hashing¶
Partitioning (sharding) splits data across machines. The splitting algorithm decides two things: how much data moves when you add or remove a machine, and whether load is even. The figure compares hash % N with a hash ring.
5.1 Why is hash(key) % N bad when you add or remove nodes, and how few keys does consistent hashing move?
Ideas to cover: nearly all keys move versus about K/N, the hash ring.
Changing N to N+1 moves N/(N+1) of the keys (10 to 11 nodes is about 91%). For a cache that wipes almost everything; for storage it means moving almost all the data.
Consistent hashing: hash both nodes and keys onto a ring; a key belongs to the first node clockwise. Adding a node only takes keys from the next node, so about K/N keys move. Removing a node sends its keys to the next node.
5.2 What problem do virtual nodes solve in consistent hashing? What is the downside of too many?
Ideas to cover: uneven arcs with few nodes, nodes of different power, a dead node spreads its load, metadata and repair cost.
- With few nodes, random positions create arcs of very different sizes, so load is uneven. Giving each physical node many tokens (say 128 to 256) makes load even by the law of large numbers.
- A stronger node gets more vnodes.
- When a node dies its load is spread over many nodes, not dumped on one neighbour (avoiding a cascade).
- A new node streams from many nodes in parallel.
Too many vnodes hurts: more metadata and gossip, fragmented repair and streaming, and with dense vnodes any two failed nodes almost certainly share some token range, so some ranges lose quorum. That is why Cassandra 4.0 reduced the default num_tokens from 256 to 16.
5.3 Compare consistent hashing, rendezvous (HRW) hashing, jump hash and fixed slots like Redis Cluster's 16384.
Ideas to cover: jump hash only works with consecutively numbered nodes, fixed slots decouple key-to-slot from slot-to-node.
| Technique | How | Strength | Weakness |
|---|---|---|---|
| Consistent hashing (ring plus vnodes) | Key goes to the first node on the ring | Minimal movement, add or remove any node | Needs ring state; uneven with few vnodes |
| Rendezvous (HRW) | Compute hash(key, node) for every node, take the largest |
No ring, easy weights | O(N) lookup |
| Jump hash | Arithmetic function (key, N) to a bucket |
O(log N), no memory, very even | Nodes must be numbered 0..N-1, only add or remove at the end |
| Fixed slots (Redis 16384) | CRC16(key) % 16384 gives a slot, a slot maps to a node |
Rebalance by moving slots | You must choose the slot count up front |
5.4 Secondary indexes on partitioned data: how do local and global indexes differ in read and write cost?
Ideas to cover: document-partitioned (scatter-gather reads) versus term-partitioned (writes touch many partitions, usually async).
| Local (document-partitioned) | Global (term-partitioned) | |
|---|---|---|
| Where the index lives | Each partition indexes its own data | The index itself is partitioned by the indexed value |
| Writes | Cheap, touch one partition | Touch several partitions (a distributed transaction or async, so the index can lag) |
| Reads by the secondary attribute | Scatter-gather over every partition, poor tail latency | Go to one index partition, then fetch the documents |
| Examples | MongoDB, Cassandra, Elasticsearch | DynamoDB GSI (eventually consistent) |
Choose local when most queries carry the partition key; choose global when reads by the secondary key dominate and writes are fewer.
5.5 How are replicas placed so they do not share a machine, rack or AZ? How is a request routed to the right partition, and what is the risk of auto-rebalancing?
Ideas to cover: preference list skipping vnodes on the same physical node, rack and AZ awareness, client-side, proxy or gossip routing, a cascade on false failure detection.
- Placement: walk the ring and choose N distinct physical nodes, preferring different racks and AZs (Cassandra
NetworkTopologyStrategy) so losing one AZ still leaves a quorum. - Routing: (a) the client knows the ring (token-aware drivers, Redis clients handling
MOVED/ASK), (b) a proxy layer (mongos, vtgate), or © send to any node and it forwards. Metadata spreads by gossip or a consensus store (ZooKeeper/etcd). - Risk: a node in a GC pause looks dead, the system starts re-replicating terabytes, load rises, more nodes look dead: a cascade. Delay re-replication, use hinted handoff for short outages, and throttle streaming.
5.6 Does DynamoDB have adaptive rebalancing for hotspots when it uses consistent hashing with virtual nodes?
Ideas to cover: the DynamoDB service does not use vnodes like the Dynamo paper, burst, adaptive capacity, split for heat, per-partition limits.
First a correction: the DynamoDB service does not use consistent hashing with virtual nodes; that is Dynamo (the 2007 paper). DynamoDB partitions by hash range of the partition key, a metadata service holds the partition map, and each partition is a 3-replica group across 3 AZs with Multi-Paxos.
The layers that handle hotspots (from the ATC 2022 paper and AWS docs):
- Throughput split evenly across partitions (the original design), causing throughput dilution.
- Burst capacity (banked unused capacity).
- Adaptive capacity: give a hot partition more throughput borrowed from the table's unused share.
- Split for heat: split a hot partition and isolate frequently accessed items.
- Global Admission Control at table level, plus on-demand mode.
What they cannot fix: a single very hot item (limit about 3,000 RCU / 1,000 WCU per partition), sequential access patterns, and item collections with an LSI (about 10 GB, cannot split). So hot keys remain a design problem: write sharding, caching (DAX), high-cardinality keys.
Versus vnodes: vnodes fix uneven token ownership, not load from hot keys; Cassandra does not automatically split a hot partition.
6 · Queues, pub/sub and streams¶
Async decouples sender and receiver in time and speed. The design questions: how long does a message live, who holds the read position, how strong is the ordering, and what happens when the consumer is slow?
6.1 How do a traditional queue (SQS, RabbitMQ) and a distributed log (Kafka) differ fundamentally?
Ideas to cover: deleted after processing versus retained, replay, several consumer groups, ordering, the ack model.
| Queue (SQS, RabbitMQ) | Log (Kafka) | |
|---|---|---|
| After processing | The message is deleted | The message is kept for the retention period |
| Who tracks position | The broker tracks each message | The consumer keeps an offset |
| Several readers of the same data | They compete for messages | Independent consumer groups, replayable |
| Strong at | Task distribution, delay, priority, per-message retry | Event streaming, stream processing, event sourcing, CDC |
| Weak at | No replay, weak ordering | Head-of-line blocking per partition, parallelism equals partition count |
6.2 What ordering does Kafka guarantee? What happens to ordering when you add partitions?
Ideas to cover: only within a partition, choosing the key, hash(key) % partitions changes, maximum parallelism, consumer group rebalance.
Ordering is guaranteed only within one partition. The producer picks hash(key) % partition_count, so the same key goes to the same partition and stays ordered. Choose the key as the entity that needs ordering (order_id, user_id) and watch for hot keys.
Adding partitions changes hash(key) % P: new events for a key go to a different partition while old unconsumed events are still in the old one, so a consumer can process a new event before an older one. Avoid it by provisioning enough partitions up front, draining before the change, or creating a new topic and migrating.
A consumer group's maximum parallelism equals the partition count. When consumers join or leave there is a rebalance; the eager protocol stops the whole group, so prefer cooperative-sticky and static membership.
6.3 Consumer lag keeps growing. How do you diagnose and handle it? What are a poison message and head-of-line blocking?
Ideas to cover: processing rate versus arrival rate, DLQ, retry topic, backoff, backpressure.
Diagnose by comparing arrival rate with processing rate, then look for causes:
- A slow downstream (DB, API).
- Rebalance storm: consumers exceed
max.poll.interval.ms, get kicked out, trigger a rebalance, and nobody makes progress. - A poison message that crashes the consumer repeatedly at one offset.
- One hot partition (skew), GC.
Handle it by scaling consumers (up to the partition count), batching, fixing the downstream, and backpressure. For poison messages and head-of-line blocking, use a retry topic with backoff plus a DLQ so the bad message does not block the whole partition (at the price of losing order for that message). Alert on lag measured in time, and remember that lag beyond retention means data loss.
6.4 Why is Kafka fast even though it writes to disk? How do acks=all, min.insync.replicas and unclean leader election relate to data loss?
Ideas to cover: sequential writes, page cache, zero-copy, batching; ISR; acks=all with a one-replica ISR still loses data without min.insync.replicas.
Fast because of: sequential appends, the OS page cache, zero-copy (sendfile), batching and compression per batch, partitions for parallelism.
Durability:
acks=1: the leader acks after its own write; if it dies before followers fetch, the write is lost.acks=all: waits for every replica in the ISR (replicas caught up withinreplica.lag.time.max.ms).- If the ISR shrinks to just the leader,
acks=allis equivalent toacks=1. So setmin.insync.replicas=2(with RF=3): with fewer than 2 in the ISR the producer gets an error, choosing consistency over availability. - Unclean leader election (off by default): if the whole ISR dies, allow a lagging replica to lead; the system returns but committed messages are lost.
- Kafka does not
fsyncevery message; durability rests on replication.
6.5 How does the SQS visibility timeout work, and why does it cause duplicate processing? How does SQS FIFO preserve order?
Ideas to cover: the message is hidden temporarily then redelivered, MessageGroupId, parallelism per group.
Standard: at-least-once, best-effort ordering. When a consumer receives a message it is hidden for the visibility timeout (default 30 seconds). The consumer must delete it when done. If it does not delete in time (slow, crash) the message reappears and goes to another consumer, so you get duplicate and even concurrent processing.
Hence: idempotent consumers, a timeout above your p99 processing time, extend with ChangeMessageVisibility, and maxReceiveCount to send to a DLQ.
FIFO: ordering per MessageGroupId. While a message of a group is in flight, later messages of the same group are not delivered, so parallelism lives in the number of groups. There is dedup by MessageDeduplicationId in a 5-minute window, and throughput is lower than standard.
7 · Delivery guarantees and idempotency¶
Over an unreliable network you cannot tell "the packet was lost" from "the ack was lost". So every system picks one of two: it may lose (at-most-once) or it may duplicate (at-least-once). "Exactly-once" is really at-least-once plus idempotent processing.
7.1 Why is "exactly-once delivery" impossible over an unreliable network, and what is Kafka's "exactly-once" really?
Ideas to cover: Two Generals, idempotent producer, transactions, read_committed, the scope is Kafka only.
This is the Two Generals problem: after sending a message with no ack, the sender cannot tell "message lost" from "ack lost". Retry and you may duplicate; do not retry and you may lose. You can only choose at-most-once or at-least-once.
"Exactly-once" really means exactly-once processing: at-least-once plus deduplication or idempotency so the effect happens once.
Kafka EOS consists of:
- Idempotent producer: a producer ID plus per-partition sequence numbers; the broker drops retried duplicates.
- Transactions: atomic writes to several partitions together with the consumer offset commit (the consume-process-produce pattern).
- Consumers use
isolation.level=read_committedto skip messages of aborted transactions. transactional.idwith an epoch fences zombie producers.
The scope is Kafka to Kafka only. If processing has side effects on a DB, email or HTTP, EOS does not cover them.
7.2 Committing the offset before or after processing gives which guarantee? Which do you choose and how do you compensate?
Ideas to cover: at-most-once versus at-least-once, replays, idempotent consumers.
- Process, then commit: a crash between the two steps means reprocessing: at-least-once.
- Commit, then process: a crash between the two steps loses the message: at-most-once.
Most business logic chooses at-least-once with idempotent processing. At-most-once suits logs and metrics that may be lost. You can get an exactly-once effect into one DB by storing the offset in the same transaction as the result and seeking to it on startup. Beware of auto-commit: it commits the offsets of messages just polled, not necessarily processed.
7.3 You implement an idempotent consumer with a dedup table. What goes wrong if the "already processed?" check and the side effect are not in one transaction?
Ideas to cover: a crash between the two steps, a race between two consumers, insert the key and the side effect atomically, external side effects need the other side's idempotency key.
The right way, in one transaction:
BEGIN;
INSERT INTO processed(msg_id) VALUES (?); -- UNIQUE: a duplicate skips the whole message
-- apply the side effect to the same DB
COMMIT;
Split apart, it fails three ways:
- Check "not processed", apply the side effect, crash before marking: the message is redelivered and the effect happens twice (a double charge).
- Mark first, crash before the side effect: marked as done but never done, so the effect is lost.
- Two consumers check at once (because a visibility timeout expired), both see "not processed", and both run. You need a unique constraint or an atomic claim.
If the side effect is in an external system (a payment gateway, email) it cannot share your transaction: pass an idempotency key to them. Prefer naturally idempotent operations (SET status='paid' rather than balance += x, upserts), and use versions to ignore late duplicates.
7.4 Design the idempotency key for a Stripe-style payment API: what if the key repeats with a different payload? What if two identical requests run at once?
Ideas to cover: store a request fingerprint, replay the stored response, an in-progress state, TTL, 409 and 422.
- The client generates a unique key per logical operation (a UUID) and sends the
Idempotency-Keyheader. - The server inserts
(key, request fingerprint, status=in_progress)under a unique constraint, performs the operation, then stores the response and marks itdone. - On a retry with the same key: done returns the stored response (no second charge); in_progress returns 409 (or waits); same key but different payload (fingerprint mismatch) returns 422, a client bug.
- Keys are scoped per account and have a TTL (Stripe about 24 hours).
- Concurrent duplicates are serialized by the unique insert or a row lock.
- A crash mid-way: the in-progress row has a lock expiry, and the operation inside must be recoverable (call the provider with a derived key).
7.5 What is the dual-write problem and how does the transactional outbox solve it? Why can messages still be duplicated or reordered?
Ideas to cover: writing the DB and sending a message is not atomic, outbox in the same transaction plus relay or CDC, at-least-once, ordering by aggregate key, inbox.
Dual write: a service writes the DB and then sends a Kafka message. The two systems share no transaction, so a crash in between loses the event (DB changed, no event) or creates a ghost event (event sent, DB not changed). Swapping the order does not help.
Outbox: in one local transaction write the business row and a row in an outbox table. A relay (polling, or CDC such as Debezium reading the WAL) reads the outbox, publishes to Kafka and marks it sent.
What remains:
- Duplicates: the relay publishes and crashes before marking, so it publishes again. The receiver must be idempotent (use the outbox id as the message id), meaning you need an inbox on the consumer side.
- Reordering: if you poll by an auto-increment id, a transaction with a smaller id can commit after one with a larger id and be missed or swapped. CDC reads in commit order and avoids that. Use the aggregate id as the partition key to keep per-entity order.
8 · Timeouts, retries and circuit breakers¶
Failures in distributed systems are rarely "broken", more often "slow". Retries and timeouts are how we react to slow, and when done wrong the reaction itself kills the system. The figure shows how one user click turns into many requests against the database.
8.1 Three service tiers, each retrying up to 3 times. When the DB at the bottom is slow, how many requests does it receive? How do you contain it?
Ideas to cover: multiplication (3 cubed is 27), retry budget, retry at one layer only, do not retry non-retryable errors.
Each tier tries 3 times (1 original plus 2 retries), so the bottom tier receives 3 x 3 x 3 = 27 requests per user request when everything fails. Retries are worst exactly when the downstream is overloaded: they add load when the system is weakest and turn a local failure into a total outage (a retry storm).
Containment:
- Retry at one layer only.
- A retry budget: retries capped at about 10% of total requests (a token bucket; Envoy and gRPC have it built in).
- Do not retry errors that cannot succeed (4xx, an expired deadline).
- Backoff plus jitter.
- The downstream signals "I am overloaded, do not retry".
- Circuit breakers.
8.2 Why is exponential backoff not enough, and why add jitter? What is the "full jitter" formula?
Ideas to cover: clients synchronize into waves, sleep = random(0, min(cap, base times 2 to the attempt)).
When an incident hits, all clients fail at the same moment so they retry in lockstep at T+1, T+2, T+4... Every wave is a load spike against a server that is trying to recover.
Jitter de-synchronizes them. The "full jitter" formula (AWS): sleep = random(0, min(cap, base * 2^attempt)). Combine it with a cap on wait time, a maximum number of attempts and an overall deadline.
8.3 What happens without timeouts? How do you choose a timeout value? What is deadline propagation?
Ideas to cover: threads and connections held, Little's Law, choose from p99 or p99.9, the outer timeout exceeds the sum of inner ones, propagate the remaining deadline.
Without a timeout a call hangs (a half-open TCP connection, dropped packets) and holds a thread or connection. By Little's Law in-flight = arrival rate x latency; as latency goes to infinity the in-flight count grows until the pool is exhausted, the service stops answering even unrelated endpoints, and the failure propagates upward.
Choosing a value: use the measured latency distribution of the downstream (around p99 to p99.9 plus margin) tied to your SLO. Separate a short connect timeout from the read or overall timeout. Too short gives false errors and retries; too long holds resources.
Deadline propagation: the client sets one absolute deadline for the whole request. Each hop subtracts the time spent and passes the remainder down. A downstream stops work once the deadline has passed. Without it, the upper tier gives up while the lower tier keeps working: wasted effort and more retries.
8.4 What are the 3 states of a circuit breaker? How does it differ from a rate limiter and a bulkhead? How does a bad configuration hurt?
Ideas to cover: closed/open/half-open, error threshold and window, per-instance breakers, bulkhead, flapping, fallback.
- Closed: requests pass, errors are counted in a sliding window. When the error rate crosses a threshold (say 50% over at least 20 calls) it goes Open.
- Open: fail fast for a period, never touching the downstream, freeing your threads and letting the downstream breathe.
- Half-open: let a few probe requests through. Success closes it, failure reopens it.
Differences:
- A rate limiter protects the callee by request volume, regardless of health.
- A circuit breaker reacts to the observed health of the dependency.
- A bulkhead isolates resource pools (threads or semaphores per dependency) so one slow dependency cannot eat all threads.
Bad configuration hurts: a threshold that is too sensitive or a minimum volume that is too low (tripping on a few errors); counting client 4xx errors; a global breaker when only one instance is bad (use per-host); an Open duration that is too short (flapping) or too long (prolonging the outage); and no fallback, so the breaker only turns slow errors into fast errors.
8.5 The system recovered from an incident yet stays overloaded and will not heal itself. That is a metastable failure; what is the mechanism and how do you get out?
Ideas to cover: a positive feedback loop, load shedding, shed traffic deliberately, hedged requests only with spare capacity.
A trigger (a traffic spike, a brief slowdown) pushes the system into overload, and a positive feedback loop (retries, cache misses caused by timeouts, queues full of requests the clients have abandoned, GC) keeps the load high even after the trigger is gone. The system is stuck in a bad equilibrium with goodput near 0 and does not recover on its own.
Ways out:
- Aggressive load shedding: reject early, drop requests already past their deadline (CoDel, LIFO or adaptive queues).
- Reduce traffic at the edge on purpose, turn off retries.
- Add capacity, warm the caches, then ramp traffic back in.
Prevention: retry budgets, deadlines, breakers, bounded queue length, headroom, and load tests that include the recovery phase. Hedged requests (sending a second copy after the p95 mark to cut tail latency) are only for idempotent operations and when there is spare capacity; under overload they make things worse.
9 · Availability, failover and disaster recovery¶
Availability is a number you promise (the SLA) and a design you must be able to defend. Two things are routinely underestimated: correlated failures (your redundant parts fail together for the same reason) and failover that has never been rehearsed.
9.1 SLA arithmetic: how many minutes a year is 99.99%? What do five dependencies in series at 99.9% each give? Why is parallel redundancy not as good as the math?
Ideas to cover: 52.6 minutes a year; 0.999 to the 5th is about 99.5%; correlated failures (same deploy, same config, same AZ, hidden shared dependencies).
| SLA | Downtime per year |
|---|---|
| 99.9% | about 8.76 hours (about 43.8 minutes a month) |
| 99.99% | about 52.6 minutes |
| 99.999% | about 5.26 minutes |
- In series: multiply the probabilities. Five dependencies at 99.9% each give
0.999^5about 99.5%, roughly 1.8 days a year. That is why non-essential dependencies must degrade gracefully. - In parallel:
1-(1-a)^n. Two independent 99% copies give 99.99%.
But that holds only when failures are independent. In reality failures are correlated: the same deploy or bad config pushed to every replica, the same AZ, power or network, the same dependency (DNS, auth, control plane), the same bug triggered by one poison request on every replica, human error, and cascades. Reduce them with canary and staged rollouts, a cell-based architecture, a limited blast radius and AZ separation.
9.2 Distinguish RTO and RPO, then compare backup and restore, pilot light, warm standby and active-active.
Ideas to cover: each step lowers RTO but raises cost and complexity, choose per service by business value.
- RTO (Recovery Time Objective): the maximum acceptable downtime.
- RPO (Recovery Point Objective): the maximum acceptable data loss, measured in time.
| Strategy | RTO | RPO | Cost |
|---|---|---|---|
| Backup and restore | Hours | From hours (or minutes with PITR) | Lowest |
| Pilot light (core such as the DB always replicated, app off but images ready) | Tens of minutes | Seconds to minutes | Low |
| Warm standby (a scaled-down copy already running) | Minutes | Seconds | Medium |
| Active-active (several regions serving at once) | Near 0 | Near 0 | Highest, most complex |
Choose by the business value of each service: the payments core is not an internal tool.
9.3 Why is multi-region active-active hard for writes, not for compute?
Ideas to cover: conflicting writes or home regions, inter-region latency, routing, DNS TTL, split brain between regions.
Stateless compute replicates easily. Data needs one source of truth for each write. The options:
- One primary region: other regions are read-only. Failover has an RPO above 0 if async.
- Multi-primary: you must resolve conflicts (LWW, CRDTs, the app), and you cannot guarantee constraints such as uniqueness or a non-negative balance.
- Home region per data item: each user has a "home" region that takes writes.
- A globally consistent DB (Spanner or Cockroach multi-region): strong consistency, write latency equal to inter-region RTT.
Plus: routing (Route 53, anycast, GSLB), DNS TTL and caching slowing failover, split brain between regions (needs a witness or quorum in a third region and fencing), and failback is hard too.
9.4 A failover that was never rehearsed can cause a bigger incident than the original failure. Where does it break? What is "static stability"?
Ideas to cover: too little capacity at the standby, cold caches, thundering herd, config drift, the control plane also fails; designing to run without the control plane; game days.
Failover breaks because: not enough capacity at the standby (quotas, not scaled), cold caches and connection pools, a thundering herd when every client reconnects, missing config, secrets, IAM or certificates in the standby region, version or schema drift, a DNS TTL longer than assumed, replica lag losing data, stale runbooks, and nobody has ever practiced it. Automatic failover can also fire on a single network blip, or lead to split brain.
Static stability (AWS): the system keeps working during a failure without taking any action on the control plane (launching instances, changing config, updating DNS). Example: pre-provision spare capacity across 3 AZs so losing one AZ still works, instead of waiting to launch new instances while the AZ is down, when the control plane may also be failing. The data plane is simpler and more available than the control plane. Verify with game days and chaos engineering.
9.5 Why is replication not a backup? What if you have a backup that you cannot restore?
Ideas to cover: DROP TABLE replicates instantly, PITR, restore testing, immutable copies against ransomware.
Replication copies every change, including mistakes: a DROP TABLE, a broken migration, a corrupting bug or ransomware reach every replica within seconds. Replicas protect against hardware failure; backups protect against logical errors and need history.
- PITR: periodic base backups plus continuous WAL/binlog archiving, so you can restore to any moment (say 1 second before the bad
DELETE). - A backup you never restored is not a backup: regularly restore into a test environment, run integrity checks, measure restore time (10 TB can take hours, so your real RTO is usually longer than planned), and verify permissions and encryption keys.
- Protect backups: immutability or WORM (S3 Object Lock), separate account and credentials, copies outside the region, and a delayed replica (about 1 hour behind) as a cheap safety net. The 3-2-1 rule.
10 · Consensus and leader election¶
Consensus is how a group of machines agrees on one value (who is the leader, which log entry is committed) even when machines die and the network splits. You do not need to implement Raft, but you must understand why a majority is needed, why terms exist, and why an old leader cannot do harm. The figure is a 5-node cluster.
10.1 What does FLP impossibility say? How do Raft and Paxos get around it?
Ideas to cover: in an asynchronous network you cannot guarantee both safety and liveness if one node can fail; always keep safety, liveness only when the network is stable enough.
FLP (Fischer, Lynch, Paterson, 1985): in a fully asynchronous system (no bound on message delay or clocks), no deterministic consensus protocol can guarantee termination if even one process may crash, because you cannot tell a dead node from a slow one. It does not say consensus is impossible, only that you cannot guarantee safety and liveness together in every case.
Raft/Paxos:
- Safety always holds, regardless of timing: two different values are never chosen.
- Liveness only when the network is stable enough (partial synchrony): timeouts detect failures, randomized election timeouts break symmetry, and a stable leader avoids livelock.
Result: when the network is bad the cluster may become unavailable but never wrong.
10.2 In Raft, why must a leader not conclude that an entry from an older term is committed just by counting replicas that hold it? (Figure 8)
Ideas to cover: an old entry can be overwritten even though it is on a majority; commit indirectly through an entry of the current term; the election rule "log at least as up to date as a majority's".
The scenario (Raft paper section 5.4.2), 5 nodes:
- S1 is leader in term 2, has just replicated the entry at index 2 to S2, and crashes.
- S5 becomes leader in term 3 (votes from S3, S4, S5) and takes a different entry at index 2.
- S5 crashes, S1 restarts, becomes leader in term 4 and keeps replicating the term-2 entry, now to S3. It is on a majority (S1, S2, S3).
- If S1 treats it as committed and then crashes, S5 can still be elected again (its last log term 3 is newer than 2) and overwrite the entry. An entry that was "on a majority" is lost.
So the rule is: a leader only commits entries of its current term by counting replicas. When an entry of the current term is committed, all earlier entries are committed indirectly (Log Matching).
It comes with the election restriction: voters refuse a candidate whose log is less up to date. Because a committed entry is on a majority, every majority of votes overlaps it, so a new leader always has every committed entry. In practice a new leader often appends a no-op entry in its new term at once.
10.3 A service takes a distributed lock with a 30 second lease, hits a 40 second GC pause, then still writes to storage. What happens and how does a fencing token fix it?
Ideas to cover: the lease expired but the client does not know, two "leaders" write, an increasing token, storage rejects stale tokens, why Redlock is criticized.
P takes the lock (30s lease), then pauses for 40s (GC)
the lease expires, the lock service gives the lock to Q, Q writes to storage
P wakes up, still believes it holds the lock, writes to storage <- both write, data corrupted
A lease is not enough because the client cannot know it was frozen, and "check the lease then act" is not atomic.
Fencing token: each time the lock is granted the lock service issues a monotonically increasing number (P gets 33, Q gets 34). Every write carries the token; storage remembers the highest token seen and rejects lower ones (P's 33 is refused after 34 was seen). The condition: storage must cooperate by checking.
Kleppmann's criticism of Redlock: it depends on timing assumptions (clocks, bounded pause lengths) and has no fencing token, so it is only suitable for locks that avoid duplicate work, not for correctness. For correctness use a consensus-based lock (ZooKeeper's zxid or etcd's revision as the token). Same idea as a Raft term or a Kafka producer epoch.
10.4 Why do consensus clusters usually have 3 or 5 nodes, not 4 or 2? What does a 7th node buy and cost?
Ideas to cover: tolerating f failures needs 2f+1 nodes, even counts add no tolerance, more nodes slow commits, safe membership change.
Tolerating f failures needs 2f+1 nodes (a majority of f+1 must stay alive). 3 nodes tolerate 1 failure, 5 tolerate 2.
- 4 nodes: the majority is 3, so it still tolerates only 1 failure like 3 nodes but has more machines to fail, and a 2-2 split leaves neither side with a majority.
- 2 nodes: the majority is 2, tolerating 0 failures, worse than 1 node.
- 7 nodes: tolerates 3 failures but each commit needs 4 acks, the leader carries more load and elections need more votes. Wide clusters are slower; etcd recommends no more than about 7.
- For more read capacity use non-voting learners or observers.
Membership change: jumping straight from the old to the new configuration can create two disjoint majorities and two leaders. Raft uses joint consensus or changes one server at a time.
10.5 Is reading from etcd/ZooKeeper always linearizable? How does leader election with ZooKeeper ephemeral nodes work, and what does a badly chosen session timeout do?
Ideas to cover: reads from a follower can be stale, ReadIndex and lease reads, ephemeral plus sequential nodes and watches, session timeout.
Not always.
- etcd: reads are linearizable by default (via ReadIndex: the leader confirms it is still leader with a heartbeat to a majority, then waits for the applied index). Serializable reads are served locally by any member: fast but possibly stale.
- ZooKeeper: writes are linearizable, but reads are served by the server the client is connected to, so they may be stale; call
sync()before reading to get the latest. - Lease reads in Raft: the leader assumes it is still leader for a lease period based on clocks. Fast but relies on bounded clock drift.
Election with ZooKeeper: each candidate creates an ephemeral and sequential znode under /election. The lowest number is the leader. Other candidates watch the node just before theirs (not the leader, to avoid a herd effect). The leader dies, its session expires, the ephemeral znode disappears, and the next candidate is notified.
A bad session timeout: too short and a GC pause or network blip expires the session so leadership flaps; too long and failover is slow. The leader must also stop acting the moment it sees it is disconnected and use a fencing token (zxid) for external side effects.
11 · Distributed transactions and sagas¶
When a business operation touches several databases or services, "all or nothing" is no longer free. There are two families of answers: coordinated atomic commit (2PC, Spanner) and a chain of steps with compensation (a saga). Both are expensive, so the best answer is often to redesign to avoid them.
11.1 Where does 2PC block? What happens if the coordinator dies after every participant answered "prepared"?
Ideas to cover: the in-doubt state, participants hold locks waiting for the coordinator, the coordinator must be durable, 3PC does not solve it in real networks.
Phase 1 (prepare): the coordinator asks "can you commit?"
participants durably log the prepare, hold locks, answer yes/no
Phase 2 (commit): all yes: the coordinator durably logs the commit decision and sends commit
any no: abort
A participant that has answered "yes" cannot decide on its own to commit or abort, because it does not know what the others said. It must wait for the coordinator.
If the coordinator crashes after collecting all the "yes" answers but before sending the decision, participants are in doubt and hold their locks on those rows indefinitely; other transactions touching them block until the coordinator recovers and reads its log.
Mitigations: replicate the coordinator with Paxos/Raft (Spanner), or manual heuristic commit or rollback in XA (with a risk of inconsistency). 3PC adds a pre-commit phase to avoid blocking, but it assumes a synchronous network, so in a real network it can lose safety and is not used in practice. The everyday cost of 2PC: 2 round trips, forced log writes, and locks held across network latency, so throughput drops sharply under contention.
11.2 Why is Spanner's use of 2PC acceptable when ordinary 2PC is avoided?
Ideas to cover: every participant is a Paxos group, the coordinator is replicated too, TrueTime and commit wait for external consistency.
Each data split is a Paxos group. A transaction spanning splits runs 2PC where both participants and coordinator are Paxos groups, and every state change (prepare, commit) is written through Paxos. If a machine dies, the group elects a new leader, reads the replicated state and carries on, so a single node failure causes no in-doubt state. It only blocks if a group loses its majority.
TrueTime: the API returns an interval [earliest, latest] with a small error bound (a few ms) thanks to GPS and atomic clocks. Spanner picks a commit timestamp and then does a commit wait: it waits until that timestamp is definitely in the past before releasing locks and acking. That gives external consistency (strict serializability). Read-only transactions read at a timestamp and need no locks.
Still costly: several Paxos rounds, commit wait, and high latency across regions. Good designs still try to keep the hot path inside one split.
11.3 Sagas lack isolation. List the anomalies and the countermeasures.
Ideas to cover: lost update, dirty read, non-repeatable read; semantic lock, commutative updates, pessimistic view, reread value.
A saga is a chain of local transactions T1..Tn, each with a compensation C; if Tk fails, run Ck-1..C1. A saga has ACD but no I: intermediate state is visible.
Anomalies:
- Lost update: another saga overwrites a change of the first saga before it completes or is compensated.
- Dirty read: reading data of a saga that is later compensated.
- Non-repeatable read: two steps of one saga read different values.
Countermeasures (after Richardson):
- Semantic lock: a flag such as
PENDINGon the record; another saga that sees it waits or rejects. - Commutative updates: design operations so order does not matter.
- Pessimistic view: reorder steps so the hardest-to-undo step comes last.
- Reread value: re-read and check the value is unchanged before writing (optimistic).
- For high-risk cases use a distributed transaction instead of a saga.
11.4 What if a compensation fails? Why order steps as compensable, pivot, retriable?
Ideas to cover: a compensation must be idempotent and retried until it succeeds, the pivot is the point of no return, irreversible work calls for redesign.
A failed compensation cannot be abandoned: it must be retried until it succeeds, so it must be idempotent and tolerate reordering. If it truly cannot succeed, alert and handle manually (a DLQ). The orchestrator stores durable state (Temporal) so it can resume after a crash.
Three kinds of steps:
- Compensable: can be undone (reserve stock, hold funds).
- Pivot: the point of no return. If it succeeds the saga is bound to finish; if it fails, undo all earlier steps (for example charging the card).
- Retriable: after the pivot, must be retried until it succeeds (shipping, a confirmation message).
Order compensable first, pivot in the middle, retriable last: a failure before the pivot rolls back cleanly, a failure after the pivot only moves forward. Work that cannot be undone (an email already sent, money already sent out) goes after the pivot, or you treat the "compensation" as a new business action (a refund, a reversing ledger entry rather than a delete).
11.5 Orchestration versus choreography: how do they differ in debugging, coupling and error handling? When would you redesign to avoid a distributed transaction?
Ideas to cover: an orchestrator holds state, choreography is event-driven, co-locate data in one aggregate, TCC.
| Orchestration (Temporal, Step Functions, Camunda) | Choreography (via events) | |
|---|---|---|
| Flow | One orchestrator drives the flow and holds state | Each service reacts to events |
| Pros | The flow is visible in one place, easy to debug, timeouts and compensation centralized | Loosely coupled, no central component |
| Cons | One more component, can turn into a "smart monolith" | The business flow is hidden between services, hard to trace, changing the flow is painful |
| Fits | Long processes, many steps, many compensations | Simple flows of 2 to 4 steps |
When to redesign to avoid a distributed transaction:
- Put the data of one invariant in one aggregate or DB (the aggregate boundary is the transaction boundary).
- Relax the invariant to eventual (allow overselling and reconcile later).
- A single writer for hot data.
- TCC (Try-Confirm-Cancel): Try reserves resources in each service, Confirm finalizes, Cancel releases. Each phase is a local transaction and must be idempotent, with handling for "empty cancel" (Cancel arriving before Try). TCC gives better isolation than a plain saga because resources are reserved, at the price of more implementation work.
Bonus · Sharding infrastructure¶
Deep dives into specific technologies (Cassandra Paxos, CockroachDB Raft, range versus hash hot spots, partition bucketing, Vitess cutover, Redis failover, top-k across shards) live in their own lesson with diagrams and four more interactive figures:
Sharding infrastructure drills: Cassandra, CockroachDB, Vitess, Redis
Quick technology guide¶
| Group | Technology | Pros | Cons | Fits when |
|---|---|---|---|---|
| Shard layer over an RDBMS | Vitess (MySQL) | Keeps MySQL, online resharding, proven at large scale | Weak cross-shard transactions, heavy to operate | You already have MySQL and very large OLTP traffic |
| Citus (Postgres) | Postgres ecosystem, co-location, multi-tenant | Cross-shard uses 2PC, the coordinator can bottleneck | Multi-tenant SaaS on Postgres | |
| NewSQL | Spanner, CockroachDB, TiDB | ACID across shards, automatic split and rebalance | Higher write latency, hot ranges with increasing keys, cost | You need cross-shard ACID and do not want to shard yourself |
| Wide-column / KV | Cassandra, ScyllaDB | Very high write throughput, multi-DC, no SPOF | No joins, no multi-partition transactions | Write-heavy, time-series, feeds |
| DynamoDB | Managed, auto-scaling, adaptive capacity | AWS lock-in, cost at scale, per-partition limits | Small team on AWS | |
| Document | MongoDB sharded | Flexible schema, online resharding | A wrong shard key hurts a lot | Document-shaped data |
| In-memory | Redis Cluster | Very fast, sorted sets, Lua | RAM cost, weak durability, can lose acknowledged writes | Cache, counters, leaderboards |
| Infrastructure | Kafka, Debezium, Flink | Durable log, CDC, stream processing | Ordering only per partition, operations | Events, outbox, read models |
| etcd, ZooKeeper | Consensus for metadata, election | Not for large data | Shard maps, leader election, locks |
Need cross-shard ACID and no DIY sharding? NewSQL (Spanner/Cockroach/TiDB)
Already on MySQL with huge OLTP traffic? Vitess
Postgres and multi-tenant SaaS? Citus
Very write-heavy, can live without joins/ACID? Cassandra/Scylla
Small team on AWS, want zero-ops? DynamoDB
Counters, leaderboards, read models? Redis
Flexible search and indexes? Elasticsearch via CDC
Analytics, time-windowed top-k? ClickHouse/Pinot plus Kafka/Flink