Try
↑ ↓ move↵ openesc close

Interview prep

336 questions across 30 topics. Draft your answer first, then check it against the worked answer and the papers behind it. They are written for practice and none is attributed to a company.

10k req/swhat if it dies?

Showing 336 of 336 questions

Load balancing

13 questions · Read the lesson

Q1JuniorA backend crashes in the middle of a busy afternoon. How does the load balancer find out, and how fast can it react?

There are two mechanisms, and sound setups use both.

Active health checks are probes. The balancer sends each backend a cheap request on a schedule, for example an HTTP GET to a health path every 5 seconds. After a set number of failures in a row the backend is taken out of rotation, and after a set number of successes it is let back in. Probing every 5 seconds and requiring 3 failures means up to about 15 seconds during which real requests still reach a dead machine.

Passive checks watch real traffic. If a backend returns a run of errors or resets connections, the balancer stops using it after those few requests, without waiting for the next probe. That is fast, but it needs traffic to learn from, and it spends a few real requests to find out.

Two details matter in practice. The health path should test what the backend needs to serve traffic, such as its connection to its database, not only that the process is alive. And there should be a limit on how much of the pool can be removed at once, so a failure in a shared dependency cannot empty the pool and turn a partial outage into a total one.

Sources

Practise it in the Load balancing lab, or open this question on its own page.

Q2JuniorRequests for /api should go to one pool of servers and requests for /images to another, and TLS must end at the edge. Which kind of load balancer do you need?

You need a layer 7 balancer, one that understands the application protocol. A layer 4 balancer works on connections and sees only addresses, ports and the transport protocol. It can pick a backend for each connection, but it cannot read the URL path, so it cannot split /api from /images.

A layer 7 proxy ends the client connection, parses the HTTP request, and chooses a backend for each request using the path, host, headers or cookies. That also lets it terminate TLS, retry idempotent requests on another backend, and spread the many requests that arrive on one HTTP/2 connection across several servers. A layer 4 balancer would pin the whole connection to one backend.

The cost is CPU. Parsing, and often re-encrypting, every request takes far more work than forwarding packets, so a layer 7 tier needs more machines for the same traffic.

Large sites combine the two. A thin layer 4 tier spreads connections over a fleet of layer 7 proxies, and the proxies make the per-request decisions. For a small service, one layer 7 proxy pair is simpler. Plain layer 4 is the right pick for protocols the proxy does not understand.

Sources

Practise it in the Load balancing lab, or open this question on its own page.

Q3JuniorHow does a least-connections load balancer decide, and what does it need to know?

For each new request it picks the server with the fewest requests in flight. It is a rough proxy for the shortest queue, so it adapts when some servers are slower or some requests are expensive.

It needs a current count per server. A single balancer can keep that count itself by incrementing when it forwards and decrementing when the response returns. With several balancers, each only sees its own traffic unless counts are shared, so each has an incomplete picture.

It treats every connection as equal weight, which is wrong when some connections are idle keep-alives and others are heavy. A newly added server with zero connections can be flooded until its queue catches up, so many implementations add a slow-start period.

Power of two choices asks only two servers and gets much of the same benefit, which is the usual follow-up question.

Sources

Practise it in the Load balancing lab, or open this question on its own page.

Q4JuniorWhat is the difference between round robin and random load balancing, and when does round robin fall short?

Round robin sends request after request to the next server in a fixed order. Random picks a server uniformly for each request. Neither looks at how busy a server is.

Round robin gives every server the same number of requests, which is more even than random over short windows. Random can send several requests in a row to the same server by chance.

Round robin falls short when equal request counts are not equal work. If requests differ in cost, or servers differ in speed, one server accumulates a queue while another idles. It also has no way to react when a server slows down or fails, unless health checks remove it from the rotation.

Round robin ignores current queue length, request cost, and server speed. That is why the usual next step is a strategy that looks at queues, such as least connections or power of two choices.

Sources

Practise it in the Load balancing lab, or open this question on its own page.

Q5JuniorWhat is tail latency, and why do teams watch p99 instead of the average?

Tail latency is the slow end of the latency distribution. The p99 is the value that one request in a hundred exceeds. The average hides it: a handful of very slow requests barely move the mean.

The tail matters because users notice slow requests, and because a single user action often triggers several backend calls. If the page waits for the slowest call, the user experiences something close to the tail of each backend, not its average.

Tails come from queueing behind a long request, garbage collection pauses, noisy neighbours, retries, and uneven load across servers. Load balancing affects the tail directly, since a balancer that lets one server build a queue makes everything waiting on that server slow.

A p99 with no measurement window is incomplete. The same service reports different values over ten seconds and over a day.

Sources

Practise it in the Load balancing lab, or open this question on its own page.

Q6MidYour backends are not identical. Some machines are faster than others. How do you balance load across them?

Start by naming the problem with even splitting. Round robin and random give each server the same share, so a slower server receives more than it can finish and its queue grows.

Options:

  • Weighted round robin or weighted random. Give each server a share proportional to its capacity. This is simple and works when capacity is known and stable.
  • Queue-aware strategies such as least connections or power of two choices. A slow server's queue is longer, so it loses comparisons and gets fewer requests without anyone configuring a weight.
  • Latency-aware routing, where the balancer prefers backends that have been answering quickly.

Static weights go stale when machines are shared or throttled. Adaptive schemes handle change but need a trustworthy signal. Heterogeneity is also one source of the tail latency variation that large services have to design around.

Sources

Practise it in the Load balancing lab, or open this question on its own page.

Q7MidOne of twelve backends has started answering slowly after a disk problem, yet it still passes its health check. What do you do at the balancer?

The health check passes because a probe is a cheap request that does not touch the slow disk. The signal has to come from real traffic, which is what outlier detection does. The balancer tracks each backend's errors and timeouts and temporarily ejects one that stands out, either after a run of consecutive failures or because its success rate is a statistical outlier compared with its peers.

A queue-aware strategy such as least connections or power of two choices helps already. The slow backend's queue is longer, so it loses comparisons and receives less. It does not remove the backend, though, and the requests it still receives are slow.

Ejection needs guard rails. Cap the share of the pool that can be ejected at once, because if the cause is a shared database, every backend looks bad and a naive rule would eject them all. Grow the ejection time each time the same host is ejected again, so a flapping host spends longer out and the pool does not oscillate. Return a host with a gentle slow start, not at full share.

Judge the host against its peers, not against a fixed number. If all twelve are slow, that is not an outlier and ejecting anything will not help.

Sources

Practise it in the Load balancing lab, or open this question on its own page.

Q8MidExplain the power of two choices. Why does asking just two servers help so much?

Choose two servers uniformly at random, compare their current load, and send the request to the lighter one.

The intuition comes from balls and bins. With one random choice, the heaviest bin ends up noticeably above average because of random clumping. With two choices, any bin that is already heavy tends to lose the comparison, so the heaviest bin grows much more slowly. The improvement from one choice to two is large. Further choices add comparatively little.

The practical value is cost. It needs two probes per decision rather than a scan of all servers, so it scales to large pools and works with many independent balancers, each picking its own random pair.

Its limits are real. It relies on a reasonably current load signal, it cannot help when total load exceeds capacity, and when requests differ in cost the signal should reflect work rather than raw connection count.

Sources

Practise it in the Load balancing lab, or open this question on its own page.

Q9MidA backend running at 80 percent load has a short blip and fails a fifth of its requests. Clients retry every failure up to three times. What happens to the load, and how do you stop it from spiralling?

Work out the attempts per request. With failure rate f and up to three retries, each request makes 1 + f + f² + f³ attempts on average. At f = 0.2 that is about 1.25, so the 80 percent load becomes 100 percent. The backend is now at capacity, queues build, more requests fail, and f rises. At f = 0.5 the multiplier is 1.9 and the offered load is 150 percent of capacity. A blip has become an outage that outlasts the original cause.

It gets worse across layers. If a frontend retries 3 times against a service that retries 3 times against a database, one user action can become 4 × 4 × 4 = 64 database attempts.

The defences:

  • A retry budget per client, such as retries may not exceed 10 percent of requests, so extra load is bounded.
  • Randomized exponential backoff, so retries do not arrive in synchronised waves.
  • Retries at one layer only, and a cap on attempts per request.
  • Deadlines that travel with the request, so nobody retries work whose answer is no longer wanted.
  • Server-side shedding, so a struggling backend rejects cheaply rather than slowly.

Sources

Practise it in the Load balancing lab, or open this question on its own page.

Q10MidSeveral independent load balancers all route to the least-loaded backend using load numbers that are a little out of date. What can go wrong, and how would you reduce it?

The failure is herding. If a backend looks idle in the stale data, every balancer sends its next requests there at once. By the time fresh numbers arrive, that backend is the most loaded. Then they all avoid it and a different backend is flooded. Load oscillates instead of settling.

Ways to reduce it:

  • Randomize. Pick two or a few candidates at random and choose the best of those, so balancers do not all converge on the same server.
  • Count your own recent sends as part of the load estimate instead of relying only on reported numbers.
  • Report load more often, or piggyback it on responses so it is fresh on the next decision.
  • Use a smoother signal, such as an exponentially weighted latency, rather than an instantaneous count.

A single balancer with exact counts does not have this problem. The risk grows with the number of balancers and the age of the data.

Sources

Practise it in the Load balancing lab, or open this question on its own page.

Q11SeniorDesign the load balancing tier in front of a large service. What layers do you use, and how do you handle failures and scale?

A common shape has two layers. A network-level layer (layer 4) spreads connections across a fleet of application-level proxies (layer 7), and those proxies route individual requests to backends.

Points to cover:

  • Layer 4 is cheap per packet and can spread flows with consistent hashing, so the same connection keeps landing on the same proxy, and adding a proxy disturbs few flows.
  • Layer 7 proxies can inspect requests, terminate TLS, retry, and apply request-level strategies such as power of two choices.
  • Health checks, with both active probes and passive observation of errors, to remove sick backends quickly and bring them back gradually.
  • Draining for deploys, so in-flight requests finish.
  • Overload behaviour: limits, load shedding, and retry budgets so retries do not amplify an outage.
  • No single balancer is a single point of failure, so use redundancy and spreading by anycast or equivalent routing.

Before drawing boxes, pin down the traffic shape and the failure domains, and decide what you would measure to know the tier is healthy.

Sources

Practise it in the Load balancing lab, or open this question on its own page.

Q12SeniorA request fans out to many backends and waits for all of them. The service is slow even though each backend looks healthy on average. How do you diagnose and fix it?

The effect is that the response time of the whole request is the maximum over the fan-out. The more backends involved, the more likely at least one is in its slow tail on any given request. So the tail of each backend, not its average, sets the user's experience.

Diagnose by looking at per-backend percentiles and at which backend was slowest for each slow request. Look for common causes: queueing behind long requests, background maintenance, garbage collection, shared-resource contention, and uneven load.

Fixes in roughly increasing complexity:

  • Reduce variance at the source: smaller units of work, priority for short requests, throttling background jobs.
  • Better load balancing so no backend runs a longer queue than its peers.
  • Hedged requests: send a duplicate to a second replica after waiting a short time, and take the first answer. Costs a small amount of extra load for a large cut in the tail.
  • Tied requests, where duplicates cancel each other once one starts.
  • Reduce the fan-out width, or accept partial results with a deadline.

Every fix has a price. Hedging adds load and only suits idempotent requests, so it is a poor first move.

Sources

Practise it in the Load balancing lab, or open this question on its own page.

Q13SeniorA sale starts and traffic hits twice your service's capacity for ten minutes. What should the system do, and in what order?

Left alone, an overloaded server queues everything. Latency passes the clients' timeouts, so the server spends its capacity on requests whose callers have already given up, and useful throughput falls toward zero even though the machines are busy. The aim is to keep goodput at capacity, which at 2x load means turning away about half of the work, deliberately.

In order of effect:

  1. Shed at the edge, cheaply. Reject when in-flight requests or queue time pass a limit. A fast rejection costs a fraction of serving a request.
  2. Choose what to shed. Tag requests by importance, so checkout survives and recommendations or prefetches are dropped first.
  3. Drop requests whose deadline has already passed instead of starting them.
  4. Throttle on the client side. Once a client sees most of its recent requests rejected, it rejects some locally before sending, which stops wasted round trips. A published rule rejects with probability max(0, (requests − K × accepts) / (requests + 1)), with K = 2.
  5. Degrade gracefully: serve cached or partial results for the shed-able parts.
  6. Autoscale, but do not rely on it. New instances take minutes and start cold.

Say what you will measure: goodput, reject rate by class, and queue time.

Sources

Practise it in the Load balancing lab, or open this question on its own page.

Caching

14 questions · Read the lesson

Q1JuniorWhat is a cache hit rate, and how does it relate to the average time a request takes?

Hit rate is the share of requests the cache answers itself. A hit is served from fast memory. A miss goes to the slower source and usually fills the cache on the way back.

Average time is a blend of the two: hit rate times hit time, plus miss rate times miss time. That is linear in hit rate, so each extra point of hit rate saves the same amount of time per request. What changes near the top is the load on the backing store, which is proportional to the miss rate: going from a very high hit rate to a slightly higher one cuts backend traffic by a large fraction.

Hit rate depends on three things: how skewed the request popularity is, how big the cache is compared with the set of hot keys, and how good the eviction policy is at keeping the hot keys. If requests are uniform over the keyspace, no policy can beat cache size over keyspace size.

The average also hides the misses. The slow tail is the misses, so the miss path still has to be fast enough.

Sources

Practise it in the Caching lab, or open this question on its own page.

Q2JuniorHow do LRU and FIFO eviction differ, and why is LRU usually better?

Both evict one key when the cache is full. FIFO evicts the key that was inserted earliest. LRU evicts the key that was used least recently.

The difference shows up on a hit. In LRU a hit moves the key to the most recent end, so keys that keep getting requested stay. In FIFO a hit changes nothing, so a popular key is eventually evicted just because it arrived early, and then immediately missed again.

Real request streams show temporal locality: a key used recently is likely to be used again soon. LRU bets on that and FIFO ignores it. Hence LRU usually wins on skewed workloads.

LRU pays for reordering on every hit, which takes work and, in a concurrent cache, coordination. FIFO is simpler and cheaper. LRU also has a weakness of its own: a long scan over cold keys pushes out the hot ones.

Sources

Practise it in the Caching lab, or open this question on its own page.

Q3JuniorA crawler requests thousands of product ids that do not exist. Each request misses the cache and reaches the database. What can you do?

Cache the answer "not found" as well. This is called negative caching, and DNS standardised it long ago. The next request for the same missing id is answered from memory.

The details need care:

  • Store an explicit marker, distinct from a cached null, so a reader can tell "known missing" from "not cached".
  • Use a short TTL, perhaps 30 to 60 seconds, because the item may be created later. Also delete the marker when the item is created.
  • Bound the damage. A crawler walking an unbounded id space will insert a marker for each id, fill the cache with entries nobody will read twice, and evict useful data. An admission policy that ignores one-off keys prevents that.

If most missing ids are invalid by construction, go one step earlier. A Bloom filter of existing ids, kept in memory in front of the cache, answers "definitely not present" without any lookup, at the cost of a small chance of a false "maybe present", which just falls through to the normal path.

Finally, rate-limit the offending client. Caching makes the abuse cheaper to absorb but does not stop it.

Sources

Practise it in the Caching lab, or open this question on its own page.

Q4JuniorYou are caching a user's profile page. How do you pick a time-to-live, and what goes wrong if it is too short or too long?

The TTL is the longest time you are willing to show out-of-date data, so start from the product, not from the cache. Ask what harm a change that appears 30 seconds late would cause. For a display name, none. For a permission change, possibly a lot.

Too short and the cache stops helping. If a key is requested at random about once a minute and the TTL is 60 seconds, the hit fraction is about r × T / (1 + r × T) = 1 / 2, so half of the requests miss. A 10-minute TTL for the same key gives 10 / 11, about 91 percent.

Too long and users see stale or deleted data. Dead entries also hold memory until they expire.

The usual pattern pairs a moderate TTL with explicit invalidation on write. The invalidation keeps data fresh in the normal case, and the TTL is the backstop for the invalidations that get lost. Add a little random jitter to each TTL so a batch of keys written together does not all expire together.

Different data deserves different lifetimes. A profile picture can live for hours, an account balance for seconds or not at all.

Sources

  • Roy T. Fielding, Mark Nottingham, Julian Reschke (2022). HTTP Caching.

Practise it in the Caching lab, or open this question on its own page.

Q5MidCompare cache-aside with write-through caching. When would you choose each?

In cache-aside, the application reads the cache first. On a miss it reads the database and fills the cache. On a write it updates the database and then invalidates or updates the cache key. The cache holds only what has been asked for.

In write-through, the write goes through the cache layer, which updates both the cache and the database as part of the same operation. Reads then find fresh data.

Choose cache-aside when reads dominate, the cache layer is a plain key-value store, and you can tolerate a short window of stale data. It is simple and resilient: if the cache is down, the application still works from the database.

Choose write-through when readers must not see stale values and writes are not too heavy, accepting that every write pays for the extra hop.

Both patterns have races. In cache-aside, a slow reader can fill the cache with an old value after a writer invalidated it. Production systems address this with leases or versions.

Sources

  • Rajesh Nishtala, Hans Fugal, Steven Grimm, Marc Kwiatkowski, Herman Lee, Harry C. Li, Ryan McElroy, Mike Paleczny, Daniel Peek, Paul Saab, David Stafford, Tony Tung, Venkateshwaran Venkataramani (2013). Scaling Memcache at Facebook.

Practise it in the Caching lab, or open this question on its own page.

Q6MidOne key in a 30-node cache cluster receives 150,000 reads a second. A node can serve about 100,000. The cluster is far below capacity on average. What do you do?

Hashing sends every read of that key to the one node that owns it, so adding nodes does nothing. The cluster has spare capacity in the wrong place.

The fix is to spread the reads of that one key, and there are two usual ways.

First, add a tiny cache in the application servers. With 200 app servers each caching the key in process for one second, the cache node sees at most 200 reads a second for it. The price is up to one second of extra staleness.

Second, replicate the key. Store it under several names, such as key#0 to key#7, and have each reader pick one at random. Eight copies turn 150,000 reads into about 19,000 per copy, spread over different nodes. The cost is on the write side: an update or invalidation has to reach every copy, and the copies can briefly disagree.

Neither should be applied to every key. Detect hot keys with sampled counters on the cache nodes or in the clients, and apply the treatment to those only. Production memcache deployments replicate the hottest categories of keys across servers for the same reason.

Do the arithmetic for your own case before choosing. The right number of copies is the peak rate divided by the share one node can give it.

Sources

Practise it in the Caching lab, or open this question on its own page.

Q7MidLFU sounds ideal, since it keeps the most popular keys. What goes wrong with it in practice?

LFU evicts the key with the lowest hit count. If popularity is stable, counts identify the genuinely popular keys and LFU does very well.

Two problems:

  • Staleness. A key that was popular keeps its high count after it stops being requested, so it occupies a slot long after it stopped earning one. When the workload shifts to new keys, those start with low counts and get evicted again before they can build up. The cache can stay full of keys nobody asks for.
  • Cost. Exact counts for every key take memory and bookkeeping, and finding the lowest count needs a suitable data structure.

The usual fixes are aging, where counts decay or are periodically halved, and keeping approximate counts in a compact sketch. TinyLFU does both and uses the counts to decide whether a new key deserves to enter at all.

Contrast with LRU, which forgets quickly and needs no counters, but is easily polluted by scans.

Sources

Practise it in the Caching lab, or open this question on its own page.

Q8MidYour cache budget is 8 GB, objects average 4 KB, and 20 million distinct objects are requested each day. How would you estimate the hit rate before buying hardware?

Start with capacity. 8 GB at 4 KB per object holds about 2 million objects, which is 10 percent of the 20 million. If requests were uniform, the hit rate would be 10 percent, and the purchase would not be worth it.

Real traffic is skewed. Model it as Zipf and sum the popularity of the top 2 million keys. At skew 1.0 that is about ln(2,000,000) over ln(20,000,000), adjusted by the harmonic-number constant, or roughly 87 percent. At skew 0.9 it is about 75 percent, at 0.8 about 62 percent, and at 0.7 about 50 percent. The estimate is very sensitive to a number you have not measured.

So do not buy on the model. Replay a day of real request logs through a cache simulator at several sizes, for example 1, 2, 4 and 8 GB, and plot hit rate against size. The curve shows the knee, where more memory stops paying, and you can choose the cheapest point that meets the database's load target.

Check what the replay hides. Object sizes vary, so object hit rate and byte hit rate differ, and the busiest hour usually matters more than the daily average.

Sources

Practise it in the Caching lab, or open this question on its own page.

Q9MidWhy is the Zipf distribution used to model cache workloads, and what does its skew parameter tell you?

In a Zipf-like distribution the key ranked k is requested with probability proportional to one over k raised to a power. A few keys account for a large share of requests, and there is a long tail of rarely requested keys.

Studies of web request traces found popularity of this shape, which is why Zipf is the standard synthetic workload for cache experiments.

The skew is that power. At zero every key is equally likely, so a cache is no better than its size relative to the keyspace. As skew rises, the same few keys dominate, so a small cache covers a larger share of traffic.

To size a cache with this, estimate the skew from a trace and plot hit rate against cache size. The curve flattens as the cache grows, because the long tail of rare keys adds little.

A caveat: real workloads also change over time, and a static Zipf model will not show how policies cope with that.

Sources

Practise it in the Caching lab, or open this question on its own page.

Q10SeniorYou must replace a cache cluster and the new one starts empty. The database can absorb only 10 percent of normal read traffic. How do you cut over?

A direct cutover sends 100 percent of reads to an empty cache. Every one misses, so the database sees ten times what it can take, and the slowdown makes the misses pile up.

Do the arithmetic for a ramp. If a fraction f of traffic goes to the new cluster, which has hit rate h, the database sees f × (1 − h) of normal traffic from it. At the start h is near 0, so f can be at most 0.1. As h climbs the cluster can take more: at h = 0.5, f can be 0.2, and at h = 0.9 it can take everything. So ramp by share of users or key ranges, watching the hit rate and database load, and widen the share only while the load stays under the limit.

Two things speed up the ramp. Warm the new cluster from the old one: on a miss, the new cache reads from the old cluster instead of the database, and fills itself. Or preload the hottest keys from a recent list of the most requested ones.

Keep the old cluster until the new one reaches its normal hit rate, so you can roll back. And leave the usual protections on: coalesced misses, a cap on concurrent database queries, and shedding.

Sources

  • Rajesh Nishtala, Hans Fugal, Steven Grimm, Marc Kwiatkowski, Herman Lee, Harry C. Li, Ryan McElroy, Mike Paleczny, Daniel Peek, Paul Saab, David Stafford, Tony Tung, Venkateshwaran Venkataramani (2013). Scaling Memcache at Facebook.

Practise it in the Caching lab, or open this question on its own page.

Q11SeniorA service runs in two regions. Writes go to the primary region's database and replicate asynchronously to the second region, where a cache fronts the local replica. Users there sometimes see old data for a long time, not just briefly. How can that happen, and how do you fix it?

The cause is a race between the invalidation and the replication. A write commits in the primary region. The invalidation reaches the second region's cache quickly, and the cache deletes the key. The replica has not applied the write yet. A reader misses, reads the old row from the lagging replica, and puts the old value in the cache. The invalidation has been spent, so the stale value stays until its TTL expires.

Ways to close it:

  • Drive invalidations from the replica's own commit stream. The delete is then issued only after the replica holds the new data, so a refill cannot read the old row. This is the approach used by large memcache deployments.
  • Use a remote marker. Before the write, set a marker for the key in the second region. Readers that see the marker go to the primary region for a fresh value, then the marker is cleared once replication has caught up. Recently written keys cost a cross-region read, which is the price of correctness.
  • Version the values. Store the row version or log position with the cached value and accept a fill only if it is at least as new as what is known.
  • Keep a TTL as a backstop for any invalidation that is lost.

Pick by what stale reads cost. Profile photos can use the TTL alone, while account state needs the marker.

Sources

  • Rajesh Nishtala, Hans Fugal, Steven Grimm, Marc Kwiatkowski, Herman Lee, Harry C. Li, Ryan McElroy, Mike Paleczny, Daniel Peek, Paul Saab, David Stafford, Tony Tung, Venkateshwaran Venkataramani (2013). Scaling Memcache at Facebook.

Practise it in the Caching lab, or open this question on its own page.

Q12SeniorA batch job scans a large table once, and your cache hit rate collapses for everyone else. Why, and what eviction designs resist it?

A scan touches many keys once each. With plain LRU, every one of those keys is inserted as most recently used, so together they push out the genuinely hot keys. When the scan finishes the cache is full of keys that will not be requested again.

The core fix is to stop a single access from earning a long stay.

  • Segmented designs such as SLRU put new keys in a probationary segment and promote only on a second hit.
  • LRU-K bases eviction on the time of the K-th most recent access, so a key touched once looks old.
  • ARC balances recency against frequency adaptively, and keeps ghost entries of recently evicted keys to learn which side needs more room.
  • Admission policies such as TinyLFU admit a new key only if its estimated frequency beats the key it would replace. One-off scan keys lose.

On the operations side, run the scan against a replica, bypass the cache for known scans, or give the batch job its own small cache.

Sources

Practise it in the Caching lab, or open this question on its own page.

Q13SeniorA very popular cached item expires and the database is overwhelmed. What happened, and how do you prevent it?

This is a cache stampede, also called a thundering herd. While the item is cached, thousands of requests are absorbed. When it expires, all of them miss at once and each goes to the database to recompute the same value. The database sees a burst it was never sized for, gets slow, and the slowness makes more requests pile up.

Prevention options:

  • Request coalescing. Only one request recomputes while the others wait for its result or are served the old value.
  • Leases. The cache hands one client a token to refill the key and tells the others to retry shortly. This also prevents some stale-set races.
  • Early or probabilistic refresh. Refresh a hot item shortly before it expires so there is never a gap.
  • Jitter on expiry times, so many keys do not expire together.
  • Serve stale data while revalidating in the background.

A cache restart is the same failure at a larger scale, since every key misses at once. Either way, limits on database concurrency are the last line of defence.

Sources

  • Rajesh Nishtala, Hans Fugal, Steven Grimm, Marc Kwiatkowski, Herman Lee, Harry C. Li, Ryan McElroy, Mike Paleczny, Daniel Peek, Paul Saab, David Stafford, Tony Tung, Venkateshwaran Venkataramani (2013). Scaling Memcache at Facebook.

Practise it in the Caching lab, or open this question on its own page.

Q14SeniorExplain how TinyLFU decides whether a new key may enter a full cache, and what the sketch is for.

TinyLFU is an admission policy. When a missed key arrives at a full cache, the cache identifies a victim, the key its eviction policy would remove. TinyLFU admits the newcomer only if its estimated access frequency is higher than the victim's. Otherwise the newcomer is dropped and the victim stays.

Frequencies come from a count-min sketch: a small table of counters indexed by several hash functions. An estimate is the minimum over the counters for a key. It can overestimate because of collisions but never underestimate, and it uses a small fixed amount of memory no matter how many keys exist. That is what makes it practical to track the frequency of keys that are not in the cache, which exact counting could not afford.

To keep frequencies fresh, the counters are periodically halved. This aging lets new popularity overtake old and addresses the staleness of plain LFU.

Typical deployments pair the admission filter with an LRU-style main area, often segmented, and sometimes a small window in front so that a burst of new items gets a fair chance.

Sources

Practise it in the Caching lab, or open this question on its own page.

Consistent hashing

13 questions · Read the lesson

Q1JuniorA cache cluster uses hash(key) mod 4. One node dies and clients switch to mod 3. What share of keys now map to a different server, and how does that compare with the ideal?

Look at any 12 consecutive hash values, since 12 is the least common multiple of 4 and 3. A key keeps its server only when hash mod 4 equals hash mod 3. That holds for hash values 0, 1 and 2 out of every 12 and fails for the other nine. So 3 in 12, or 25 percent, of keys stay, and 75 percent move.

The ideal is much lower. Only the dead node's keys, a quarter of the total, have to move, because they lost their server. The other three quarters were fine where they were. Mod N therefore moves three times the necessary amount, and half of all keys are shuffled between healthy servers for no reason.

For a cache, that half becomes misses on servers that were doing nothing wrong, and the database takes all of it at once. For a store, it is a huge data transfer after a single failure.

A consistent hash ring moves only the keys the failed node owned, which is about a quarter here, and hands them to the neighbours on the ring. The other keys do not change owner at all.

Sources

Practise it in the Consistent hashing lab, or open this question on its own page.

Q2JuniorHow does a key find its node on a consistent hash ring?

Both nodes and keys are hashed with the same function onto a circle of hash values. To find a key's node, start at the key's position and walk clockwise until you reach the first node point. That node owns the key.

In code the points are kept in a sorted array. Lookup is a binary search for the first point at or after the key's hash, wrapping to the first element if there is none.

Because the rule depends only on positions on the ring, any client holding the same list of nodes computes the same owner, with no central lookup.

When a node joins, it takes over only the arc just before each of its points. Keys in those arcs move to it and no other keys move. When a node leaves, its keys go to the next node clockwise.

This is the idea in the original consistent hashing paper, and the Chord lookup protocol reused it.

Sources

Practise it in the Consistent hashing lab, or open this question on its own page.

Q3JuniorWhat are virtual nodes in consistent hashing, and what problem do they solve?

A virtual node is one of several points a physical node places on the ring, typically by hashing the node's name together with a counter.

With one point per node, the gaps between points are random lengths, so some nodes own long arcs and many keys while others own short arcs and few. Load is uneven by luck alone.

With many points per node, each node owns many small arcs scattered around the ring. Random variation averages out and each node's total share gets closer to fair. A leaving node also hands its keys to many different neighbours instead of one, so no single survivor takes the whole load.

Virtual nodes also let you weight nodes: give a more powerful machine more points.

The cost is a larger ring to store and update, and more work to rebuild after a change.

Sources

Practise it in the Consistent hashing lab, or open this question on its own page.

Q4JuniorWhy is assigning keys to servers with hash(key) mod N a problem when the number of servers changes?

With a fixed N the rule is simple and spreads keys evenly. The trouble is that the answer depends on N itself. Change N and the remainder of almost every key changes, so almost every key maps to a different server.

For a cache, that means a flood of misses at the moment you add or lose a server, all landing on the backing store. For a data store, it means moving most of the data across the network for a small change.

The ideal rule moves only about the share of keys the new server needs, roughly one over the new server count, and nothing else. Consistent hashing achieves this by making a key's owner depend on where the key and the servers sit on a ring, not on how many servers there are.

Mod N is still fine for a cluster whose size almost never changes.

Sources

Practise it in the Consistent hashing lab, or open this question on its own page.

Q5MidFor about a minute after a node is added, two application servers disagree about the ring membership. What goes wrong, and how do real systems limit the damage?

For keys in the arcs the new node took, the two servers compute different owners. Server A, which has not heard of the node, writes or reads at the old owner. Server B goes to the new node. For a cache, B misses on data that A cached, and A may serve values that B has since updated, so staleness appears. For a data store it is worse, because a write through A can be invisible to a read through B.

Consistent hashing keeps the disagreement small. Only keys in the new node's arcs, about one in N + 1, are affected. With hash mod N the two views would disagree about most keys.

The damage is limited in a few ways:

  • Version the membership. Each change gets an epoch number. Requests carry the sender's epoch, and a node that sees an older one rejects or redirects, so the stale server learns immediately.
  • Spread membership by gossip or from a coordination service, so the window of disagreement is seconds, not minutes.
  • For caches, accept brief misses and rely on TTLs. For stores, do a dual read during the transition: ask the new owner, and fall back to the old one.
  • In a Dynamo-style design, every node knows the whole ring and can forward a request to the right replica.

Sources

Practise it in the Consistent hashing lab, or open this question on its own page.

Q6MidYou maintain a group of 12 proxies and must route each client id to one of them. Two proxies have twice the CPU of the others. Would you use a ring with virtual nodes or rendezvous hashing?

For 12 nodes I would choose rendezvous hashing.

Rendezvous scores every node for the key with hash(key, node) and picks the highest. With 12 nodes that is 12 cheap hashes per lookup. It needs no ring and no virtual-node count to tune. When a proxy leaves, only the keys it won move, and each goes to its runner-up.

Weights are exact. Use the score −w / ln(h), where h is the hash scaled to (0, 1) and w is the node's weight. A node then wins with probability proportional to w, so the two big proxies take twice the share of the others, with no rounding.

On a ring, weights are expressed by giving a node proportionally more points. Balance then depends on the point count, since the load of a node varies like one over the square root of its points. To get the weights right within a few percent you need hundreds of points per node, and a ring to store and rebuild.

The ring wins when the node count is large. A lookup that is a binary search over points beats hashing 1,000 nodes for every key. At very high lookup rates, a precomputed table such as Maglev's gives constant-time lookups and near-perfect balance, at the cost of rebuilding it on change.

Sources

Practise it in the Consistent hashing lab, or open this question on its own page.

Q7MidHow do you replicate data on a consistent hash ring, and what do you have to be careful about?

A common scheme stores each key on its owner and on the next few nodes clockwise. A client that hashes a key can compute the whole replica set from the ring.

The main subtlety is virtual nodes. Walking clockwise to the next points may land on points of the same physical node, which would put several replicas on one machine. So the walk skips points of nodes already chosen, until it has enough distinct physical nodes. Systems that care about failure domains extend this to skip nodes in the same rack or zone.

Other points to cover:

  • Which node coordinates a write, and what happens when a replica is down. Dynamo-style designs let a neighbour accept the write temporarily and hand it back later.
  • Reads and writes need agreed rules about how many replicas to contact, which decides consistency and availability trade-offs.
  • When membership changes, replica sets change for the affected ranges, so data has to be streamed to new owners.

Sources

Practise it in the Consistent hashing lab, or open this question on its own page.

Q8MidHow would you choose the number of virtual nodes per server? What do you gain and lose by raising it?

Raising the count improves balance. The busiest node's share gets closer to the average as more points are averaged. Removal is also gentler, because a failed node's keys spread over many neighbours.

The costs are real:

  • Ring size and memory grow with nodes times virtual nodes.
  • Rebuilding or updating the sorted structure after a change takes longer, and replicating the ring metadata to clients takes more bandwidth.
  • When replicas go on the next distinct physical nodes, more points make the walk to find distinct nodes touch more entries.
  • Rebalancing data when a node joins involves many small ranges from many sources, which can be more operationally complicated than a few large transfers.

The returns diminish: past some point the extra balance is not worth the overhead. A defensible approach is to pick the smallest count that keeps imbalance within a target, measured with your key distribution, and to weight by machine capacity.

Balancing keys is not balancing requests, so hot keys stay a separate problem.

Sources

Practise it in the Consistent hashing lab, or open this question on its own page.

Q9SeniorConsistent hashing balances keys, but one server still ends up overloaded in practice. How can the scheme be changed to bound the load?

Plain consistent hashing balances the expected number of keys, not the worst case, and not requests. Random variation and skewed popularity can leave one node well above average even with many virtual nodes.

Consistent hashing with bounded loads adds a capacity limit per node, set slightly above the average load. A key is assigned to the first node clockwise whose current load is below the limit. If its natural owner is full, the key spills to the next node with room.

This gives a provable upper bound on the maximum load relative to the average, while keeping the property that membership changes disturb only a small number of assignments. The trade is that placement now depends on current loads, so lookup needs that state or must replay the assignment, and a spilled key lives away from its natural owner.

The technique suits load balancing of long-lived assignments, such as sticky routing of clients to servers or placement of items on servers. State what it does not fix: a single key whose request rate alone exceeds one node's capacity.

Sources

Practise it in the Consistent hashing lab, or open this question on its own page.

Q10SeniorYou are designing partitioning for a distributed key-value store that must grow and survive node failures without downtime. How do you use consistent hashing, and what else do you need?

Use a ring with virtual nodes so that adding or removing a node moves a small, spread-out share of the data and load stays reasonably even. Weight virtual node counts by machine capacity.

Then cover what the ring does not provide:

  • Replication on the next distinct physical nodes clockwise, respecting racks or zones.
  • Membership and failure detection, so every node has a consistent enough view of the ring. Gossip is a common mechanism.
  • Data movement when membership changes: stream the affected ranges to new owners in the background, throttled so that it does not hurt foreground traffic, and only switch ownership when the data is there.
  • Handling temporary failures separately from permanent ones, so a brief outage does not trigger a full rebalance.
  • Hot keys, which hashing cannot spread. Use caching in front, splitting a key into parts, or special handling.
  • Operational visibility: per-node key counts, request rates, and the imbalance over time.

Pin down the consistency model and how clients find the ring, since the ring alone answers neither.

Sources

Practise it in the Consistent hashing lab, or open this question on its own page.

Q11SeniorA stateful service keeps per-user state in memory on 200 servers, assigned by hashing the user id. A few tenants generate 100 times the traffic of a typical one, and load shifts through the day. Hashing leaves some servers hot. What would you design instead?

Hashing balances keys, not load, and no number of virtual nodes sees the traffic. When load is skewed and moving, move from a fixed function to an assignment service.

Divide the key space into many slices, which are ranges of hash space. A controller maps slices to servers and watches load reports. It splits a slice that is hot, merges cold neighbours, and moves slices off overloaded or unhealthy servers. Clients cache the assignment and route directly, so the controller is off the request path and a controller outage freezes the assignment rather than stopping traffic. A very hot slice can be assigned to several servers if the state allows replication.

There are costs. Ownership must be exact while a slice moves, so that two servers do not both accept writes, which means a handoff protocol. The new owner starts with cold in-memory state. Clients can hold a stale assignment, so servers must reject requests for slices they no longer own. Movement has a cost, so the controller should move as little as possible.

The Slicer sharding service takes this approach, and its authors report that it cut resource use for the median workload by 63 percent compared with static sharding.

A single tenant above the capacity of one server still needs its own answer, such as splitting by sub-key.

Sources

  • Atul Adya, Daniel Myers, Jon Howell, Jeremy Elson, Colin Meek, Vishesh Khemani, Stefan Fulger, Pan Gu, Lakshminath Bhuvanagiri, Jason Hunter, Roberto Peon, Larry Kai, Alexander Shraer, Arif Merchant, Kfir Lev-Ari (2016). Slicer: Auto-Sharding for Datacenter Applications.

Practise it in the Consistent hashing lab, or open this question on its own page.

Q12SeniorWhat is jump consistent hash, and when would you use it instead of a ring?

Jump consistent hash maps a key to one of N numbered buckets using a short loop and a pseudo-random sequence seeded by the key. It needs no stored ring and almost no memory, and it is fast.

It keeps the key property of consistent hashing: when N grows by one, only the keys that move to the new bucket change owner, which is about one over the new count of keys. Balance is very even, without virtual nodes.

The restriction is that buckets are numbered 0 to N-1. You can add or remove buckets only at the end. You cannot remove an arbitrary one in the middle, which is what happens when a server fails. Nor can it express weights directly.

So it fits systems with numbered shards that grow, such as a sharded storage service where a failed shard is replaced rather than removed, or where a separate mapping from bucket to machine handles failures. A ring, or a ring-like structure such as rendezvous hashing, fits clusters where arbitrary members come and go.

State versus flexibility is the whole trade.

Sources

Practise it in the Consistent hashing lab, or open this question on its own page.

Q13SeniorA cache fleet of 1,000 nodes uses a ring with 100 virtual nodes each, and the busiest node holds about 30 percent more keys than average. The team proposes 1,000 virtual nodes. Evaluate the proposal.

First check that the observation matches theory. A node with V points has a relative load spread of about 1 / √V, which is 10 percent for V = 100. Among 1,000 nodes the busiest is about 3.2 standard deviations above the mean, so roughly 1 + 3.2 × 0.10 = 1.32. The 30 percent is expected, not a bug.

At V = 1,000 the spread drops to 3.2 percent and the busiest node to about 10 percent above average. That helps, but the cost grows tenfold. The ring goes from 100,000 to 1,000,000 entries. At 16 bytes an entry that is 16 MB in every client, and every membership change rebuilds it. A node joining takes many tiny ranges from many sources, which is harder to stream and track than a few large ones.

Alternatives to weigh:

  • Provision memory 30 percent above average and accept the imbalance. This is cheap if memory is cheap.
  • Use consistent hashing with bounded loads, which caps every node at a chosen multiple of the average and gives a provable bound.
  • Use a precomputed table such as Maglev's, which balances almost perfectly.

Whichever you choose, remember that this is key balance. Hot keys and request balance are separate problems, so check request rates per node before spending on key balance.

Sources

Practise it in the Consistent hashing lab, or open this question on its own page.

Replication and lag

13 questions · Read the lesson

Q1JuniorCompare synchronous and asynchronous replication. What does each cost and what does each protect?

In asynchronous replication the leader tells the client yes once the write is on its own disk and sends it to followers afterwards. Writes are fast and do not depend on the network. If the leader fails before sending, acknowledged writes are lost, and follower reads can be stale.

In synchronous replication the leader waits for followers before answering. Nothing acknowledged is lost when the leader fails and followers are up to date. But each write now includes a round trip, and one slow or unreachable follower slows or blocks every write.

The trade, in plain terms, is durability and freshness against latency and availability. Semi-synchronous sits between the two: one follower is kept in step, so every acknowledged write is on two machines and only one extra round trip is paid.

Sources

Practise it in the Replication and lag lab, or open this question on its own page.

Q2JuniorWhat is replication lag, and why does a follower fall behind the leader?

Replication lag is the gap between a write being committed on the leader and the same write being visible on a follower. It can be measured in time or as a number of log entries the follower has not applied yet.

Followers fall behind because the log has to travel over a network that takes time and takes a different time on each trip, because a busy follower applies entries slower than they arrive, and because entries are applied in order, so one delayed message holds up everything behind it.

Lag matters because a read from a follower can return data older than a write the client was told succeeded. Lag is a window, not a loss: the follower catches up once the burst passes. It grows with the write rate, with network delay, and with a follower busy on other work.

Sources

Practise it in the Replication and lag lab, or open this question on its own page.

Q3JuniorYour app has one leader and two read replicas that run a few hundred milliseconds behind. Which of these reads can go to a replica: the product catalogue page, the order confirmation page right after checkout, and the account balance shown before a transfer?

The catalogue page can. Products change rarely, and a view that is a few hundred milliseconds old is invisible to a shopper. It is also the highest-volume read, so moving it off the leader gives the most relief.

The order confirmation page should not, at least not straight away. The customer just wrote that order, and a replica may not have it yet, so they would see "order not found" seconds after paying. Read it from the leader, or from a replica only once it has caught up to the position of that order's write.

The balance before a transfer must come from the leader. The decision to debit depends on it, and acting on a stale number can allow an overdraft.

The sorting rule behind these three: reads whose staleness nobody notices go to replicas. Reads that must see the user's own just-written data, or that feed a decision about money or stock, go to the leader. It helps to tag each query in the code with how stale it may be, so the routing is a deliberate setting and not a habit.

Sources

Practise it in the Replication and lag lab, or open this question on its own page.

Q4JuniorWhy do systems replicate a database, and what does replication not give you?

Replication keeps the same data on several machines. It gives availability, because if one machine dies another has the data, and read capacity, because reads can be spread over the copies. It can also place data close to users.

It does not give you more storage, since every replica holds everything. And with a single leader it does not give you more write throughput, since every write still goes through that one machine.

Each limit has a next step. Partitioning adds storage and write capacity. Multi-leader or leaderless designs let writes be accepted in several places.

Sources

Practise it in the Replication and lag lab, or open this question on its own page.

Q5MidThe leader of an asynchronously replicated database fails. Walk through failover and what can go wrong.

First detect the failure, usually with timeouts, which can be wrong if the leader is only slow. Then choose a new leader. The best candidate is the follower that has applied the most of the log. Then reconfigure clients and the other followers to use it, and make sure the old leader, if it returns, becomes a follower and does not keep accepting writes.

What can go wrong: writes the old leader acknowledged but never replicated are lost, and the client was told they succeeded. If the old leader rejoins with writes the new one never saw, they conflict or get discarded. If two nodes both think they are leader, both accept writes and the data diverges. And a timeout set too low triggers needless failovers under load.

How much is lost depends on the replication mode and on the lag at the moment of failure. With semi-synchronous replication an acknowledged write is on at least one follower, so promoting the furthest-ahead survivor loses nothing acknowledged.

Sources

Practise it in the Replication and lag lab, or open this question on its own page.

Q6MidWhat are monotonic reads, how can replication break them, and how do you guarantee them?

Monotonic reads says that once a client has seen a value, later reads by that client never return an older one.

Replication breaks it when successive reads land on different followers with different lag. The first read hits a follower that is current and the second hits one that is behind, so the client appears to go back in time. A comment appears and then vanishes on refresh.

The simple fix is to pin each client or session to a single follower, for example by hashing the client id, because one follower only moves forward. If that follower fails the client moves to another and may see a step back once. A stronger method has the client remember the highest log position it has seen and require followers to be at least that far along.

Pinning does not give read-your-writes, because the pinned follower can still be behind the client's own write. The two guarantees are separate, and a store can offer both.

Sources

Practise it in the Replication and lag lab, or open this question on its own page.

Q7MidEvery night a batch job updates a few million rows on the leader. During it, replica lag climbs from near zero to twenty minutes, and the morning dashboards read stale data until it clears. Why, and what are your options?

The leader runs the batch as a handful of large transactions, quickly. Each replica must apply the same changes in the leader's order, often with far less parallelism than the leader had. If the batch produces row changes faster than the replica can replay them, the backlog grows. When the batch ends the replica still has to work through it, and it only gains on the backlog at the difference between its apply speed and the normal write rate. That is why lag outlasts the job.

A row-based log makes it worse, since one statement touching five million rows becomes five million events to ship and apply.

Options, roughly in order of effort. Run the batch in small chunks, committing every few thousand rows, so replicas apply a steady stream and in-order replay is never stuck behind one giant transaction. Throttle the batch while lag is above a threshold. Schedule it away from the dashboard hours. Enable parallel apply on the replica if the database supports it, which helps when the changes touch independent rows. And take the dashboards off the lagging replica, or make them tolerate a stated staleness.

Whichever you choose, add an alert on lag in seconds, so you learn about the next one before the users do.

Sources

Practise it in the Replication and lag lab, or open this question on its own page.

Q8MidA user submits a form and the next page, served by a follower, does not show it. Explain what happened and how you would fix it.

The write went to the leader and the read went to a follower that had not applied it yet. The user has lost read-your-writes, which says that a client sees its own earlier writes.

There are several fixes. Route reads to the leader for a short time after a user writes, or for data the user is likely to have changed, such as their own profile. Or give the client a token, for example the log position of its last write, and let a follower serve the read only if it has applied at least that position, otherwise wait briefly or send the read to the leader. Or read from a follower only if its measured lag is below a threshold.

All of these cost something. More reads land on the leader, so the followers help less. With several data centres, the token has to travel with a client that moves between them. And none of it makes the data fresh for everybody: it only keeps one user's view consistent with their own actions.

Sources

Practise it in the Replication and lag lab, or open this question on its own page.

Q9MidA team replicates by shipping SQL statements. After a month, a row-count check shows the leader and a follower differ by a few rows, and no errors were logged. What is the likely cause, and what would you change?

Statement shipping replays the same SQL text on each machine, so any statement whose result depends on something other than the data will diverge silently. Typical culprits are UUID() or RAND() in an insert, an UPDATE ... LIMIT 1 with no ORDER BY, which can pick a different row on each machine, and triggers or functions with side effects. A few rows differing, with no errors, fits that pattern: each statement succeeds everywhere, just with different results.

First find which statements are responsible. MySQL flags statements it considers unsafe for statement-based logging in its error log, and that list is a good start. A checksum tool that compares tables chunk by chunk between leader and follower will locate the drifted rows.

The durable fix is to change the log format. Row-based logging records the values the leader actually wrote, so every follower applies the same thing. MySQL has defaulted to row-based since 5.7.7. The cost is larger logs for bulk updates, because one statement touching a million rows becomes a million row events, which can add lag.

After switching, repair the drift by rebuilding the follower from a fresh snapshot of the leader. Patching a few rows by hand leaves you guessing about the ones you missed.

Sources

Practise it in the Replication and lag lab, or open this question on its own page.

Q10SeniorYou are designing storage for two things: a payments ledger and a social feed. How would you choose replication settings for each?

The deciding question is what loss and staleness cost. For the ledger, losing an acknowledged write is unacceptable and a few extra milliseconds per write are fine. Use at least semi-synchronous replication so that every acknowledged write is on two machines, ideally in different failure domains. Accept lower write availability if no follower is reachable. Route reads that must be correct, such as a balance before a debit, to the leader.

For the feed, a stale read is a small blemish and write latency matters more. Asynchronous replication with several followers serving reads is reasonable, with read-your-writes routing so a user sees their own post.

Some details make the design real. Semi-synchronous is usually set up with one acknowledging follower and another ready to take over if it stalls, so a single slow machine cannot block writes. Lag should be monitored and alerted on. A cross-region follower has a long round trip, which makes synchronous replication to it expensive. In each case, be explicit about what is being given up.

Sources

Practise it in the Replication and lag lab, or open this question on its own page.

Q11SeniorYour product has users in Europe and North America, and the single leader is in the US. European users complain that saving anything takes 300 ms. What are your options, and what does each cost?

The 300 ms is the round trip to the leader, which replication cannot remove. Writes must reach the leader, and a synchronous follower in Europe would add its round trip too. So the options are about moving the leader or allowing more than one.

Option one: keep one leader and add European read replicas. Reads become fast, writes stay slow. This often fixes the complaint if reads dominate. Add read-your-writes routing so a user who has just saved is sent to the leader or to a replica that has applied their write.

Option two: partition by user home region. Each user's data has its leader in their own region, so most writes are local. Cross-region operations, such as European users interacting with US data, still pay the trip. Moving a user between regions needs a migration.

Option three: a leader in each region, replicating to each other asynchronously. Writes are fast everywhere. The price is write conflicts when two regions edit the same item, which need a resolution rule, and a harder operational story.

Before the heavy options, check where the time goes. Part of 300 ms may be connection setup, TLS handshakes or several sequential round trips per save, which batching or a regional gateway can cut.

I would start with replicas plus region-homed data for what is naturally per user, and leave multi-leader for data that really is edited from both sides.

Sources

Practise it in the Replication and lag lab, or open this question on its own page.

Q12SeniorOne follower in a three-follower cluster is slow. What does it do under asynchronous, semi-synchronous and fully synchronous replication, and what would you change?

Under asynchronous replication the slow follower falls behind but writes are not affected. Reads sent to it return stale data, and if it falls far behind it may never catch up. Pull it out of the read rotation when its lag crosses a threshold.

Under fully synchronous replication every write waits for it, so write latency is set by the slowest follower and an outage of that follower stops all writes. That is why fully synchronous setups are rare.

Under semi-synchronous replication a write waits for any one acknowledgement, so a slow follower is skipped as long as another is fast. The risk is that if the fast follower goes away the system either blocks or falls back to asynchronous, which is a silent loss of the guarantee.

In-order application matters here: one delayed message holds up the follower's whole log. Report lag both as time and as entries behind. Remedies are removing the follower from the acknowledging set, throttling writes, or rebuilding it from a snapshot.

Sources

Practise it in the Replication and lag lab, or open this question on its own page.

Q13SeniorA leader is partitioned from its followers. Monitoring promotes a follower after 10 seconds. Then the old leader's network heals while some clients still talk to it. What goes wrong, and how do you prevent it?

Now two nodes accept writes, each believing it is the leader. Clients that reached the old leader and clients that reached the new one write different values for the same keys. The followers receive two histories. Without a rule, the data diverges, and some of the writes the old leader acknowledged during the gap will have to be thrown away or merged by hand. This is split brain.

The root problem is that the old leader cannot tell it has been replaced. A node cannot be sure from the inside whether a silence means its peers are down or it is cut off.

Prevention has layers. Give every leadership term a number, an epoch, and make followers and storage refuse writes from a lower number than the highest they have seen. This is fencing, and it turns the old leader's late writes into rejected requests rather than corruption. Have the old leader stop on its own: if it cannot reach a majority, or cannot renew its lease, it steps down and stops accepting writes. Choose the promotion timeout knowing the trade: too short and a slow leader triggers a needless failover, too long and writes are down for longer. Finally, decide beforehand what happens to the old leader's unreplicated writes when it rejoins, since they conflict with the new history.

The robust form of all this is a consensus protocol, which settles who the leader is by majority vote and is covered in a later module.

Sources

Practise it in the Replication and lag lab, or open this question on its own page.

Quorums

13 questions · Read the lesson

Q1JuniorWith three replicas and majority quorums, how many failures can reads and writes survive?

A majority of three is two. Reads and writes each need two replicas, so both keep working with one replica down. With two replicas down, neither can proceed.

A majority quorum also satisfies the overlap rule: two plus two is four, which is more than three. In general a majority quorum tolerates a minority of failures, so N=5 tolerates two, and N=2f+1 tolerates f.

Even numbers buy nothing. Four replicas need a majority of three and still tolerate only one failure, the same as three replicas, while costing more.

Sources

Practise it in the Quorums lab, or open this question on its own page.

Q2JuniorIn a leaderless replicated store, what do N, R and W mean?

N is the number of replicas that store each item. W is how many replicas must acknowledge a write before the client is told it succeeded. R is how many replicas a read waits for before it returns, taking the newest version among the answers.

The coordinator sends each request to all N replicas and waits for the first W or R replies. So W and R are the two dials. Higher values give stronger guarantees and slower, less available operations. Lower values give faster, more available operations that can return old data.

Take N=3 with R=2 and W=2. With one replica down, both reads and writes still find two live replicas.

Sources

Practise it in the Quorums lab, or open this question on its own page.

Q3JuniorWhy does R + W > N mean a read sees the latest acknowledged write?

A write is acknowledged by W replicas, so W replicas hold the new value. A read asks R replicas. If R plus W is greater than N, the two groups cannot be completely separate, since together they would need more than N different replicas. So at least one replica in the read group has the new value.

The reader compares the versions it receives and returns the newest, so that overlapping replica makes the read see the write. This is the argument from Gifford's weighted voting paper.

The guarantee has limits. It holds only for reads that start after the write was acknowledged, and only with strict quorums. If R plus W equals N exactly, the two groups can be disjoint and a read can miss the write.

Sources

Practise it in the Quorums lab, or open this question on its own page.

Q4JuniorA store has N=5, W=3 and R=3. How many replicas can be down while reads still work, and while writes still work? What if the settings are W=5 and R=1?

With W=3 and R=3, either operation needs three live replicas. Five replicas minus three leaves two that may be down. So reads keep working with up to two replicas down, and so do writes. R plus W is six, which is above five, so a read also sees the latest acknowledged write.

With W=5 and R=1, the picture is lopsided. A read needs only one live replica, so it works with four down. A write needs all five, so a single replica being down blocks every write. R plus W is six again, so reads are still fresh, but the writes are now less available than on a single machine, because five things must all be up.

The general rule is that an operation needing k replies tolerates N minus k failures. Choosing R and W is choosing how to split that tolerance between reads and writes, while keeping their sum above N if you need fresh reads.

A quick sanity check is to ask what happens during a routine rolling restart, when one node is down at a time. W=5 would stall writes at every restart, which is a strong argument against it.

Sources

Practise it in the Quorums lab, or open this question on its own page.

Q5JuniorWith N=3 and W=2, a client sends a write and gets a timeout error. One replica stored the value and the other two never received it. What can a later read return, and what should the client do?

The client does not know whether its write happened, and the system cannot say either. The write reached one replica, short of W=2, so it was not acknowledged. But nothing rolls it back. That replica keeps the value.

A later read with R=2 asks two replicas. If it includes the replica with the value, it returns the new value, taking it as the newest version. Read repair may then copy it to the others, so the write that was reported as failed becomes permanent. If the read skips that replica, it returns the old value. Either result is legitimate, and the answer can change between reads.

So the client should treat the timeout as unknown, not as failure. Retrying is safe only if the write is idempotent: setting a key to a value, or carrying a unique request id the store uses to discard duplicates, can be repeated. An increment cannot.

This is one of the ways a quorum store differs from a single database with transactions. A quorum protects reads against missing acknowledged writes. It does not make a failed write disappear.

Sources

Practise it in the Quorums lab, or open this question on its own page.

Q6MidHow does the choice of R and W affect latency, and why does one slow replica matter more as the quorum grows?

The coordinator sends the request to every replica and waits for the first k replies, with k being R or W. The latency of the operation is the arrival time of the k-th fastest reply. Raising k moves you further into the tail of the reply times.

If one replica is slow, a small quorum simply ignores it, because k other replicas answer first. Once k exceeds the number of fast replicas, the operation must wait for a slow one, so latency jumps to that replica's. With k equal to N every operation is as slow as the slowest replica, and the chance that at least one replica is slow on a given request grows with N.

The trade can be tilted to the workload. With R=1 reads are fast, while W=N makes every write pay for the slowest replica. Sending a second request after a short delay, a hedged request, also trims the tail.

Sources

Practise it in the Quorums lab, or open this question on its own page.

Q7MidIn a leaderless store using last-write-wins timestamps, users report items vanishing from their shopping carts, but only when they use the app on a phone and a laptop at the same time. Explain and fix.

Each device reads the cart, adds an item, and writes the whole cart back with a timestamp. Say the phone writes [milk, eggs] and the laptop, having read the old [milk], writes [milk, bread] a moment later. Last-write-wins keeps only the higher timestamp. The replicas converge on one cart and the other item is dropped. Nothing fails, so there is no error to see.

The clocks make it worse. If the phone's clock runs a second ahead, its older write beats the laptop's newer one, so even "the later edit wins" does not hold.

Fixes, from smallest to largest. Stop writing the whole cart: store each item as its own cell or key, so two adds touch different keys and cannot overwrite each other. Or use a store with version vectors, which detects that the two writes are concurrent and returns both versions, then merge them by union in the application. That is how the original Dynamo cart worked, with the known side effect that a removed item can come back, which was chosen over losing an added one. Or use a data type designed to merge, such as a set that tracks additions and removals.

Last-write-wins is fine for values where the newest overwrite is genuinely what you want, such as a profile picture, and a poor fit for collections.

Sources

Practise it in the Quorums lab, or open this question on its own page.

Q8MidExplain read repair and anti-entropy. Why do leaderless stores need both?

A replica that missed a write stays behind until something corrects it. Read repair does this during reads. When a read sees replicas return different versions, it writes the newest value back to the ones that were behind. It is cheap, because the read already has the data, and it heals popular items quickly.

Read repair only heals what is read. An item nobody reads can stay inconsistent for a long time, and a replica that was down for hours misses many writes. Anti-entropy is a background process that compares replicas, often with hash trees to find differences without sending all data, and copies what is missing.

Neither is enough alone: read repair misses cold data, and anti-entropy is too slow for hot data. Both rely on telling which version is newer, by timestamp or version vector.

Sources

Practise it in the Quorums lab, or open this question on its own page.

Q9MidWhat is a sloppy quorum, what is hinted handoff, and what do they give up?

A strict quorum collects replies from the N replicas that own the item. A sloppy quorum accepts replies from other healthy nodes when some owners are unreachable. Those stand-ins hold the write along with a hint naming the intended owner. When the owner returns, the stand-in hands the write over. That is hinted handoff.

The benefit is write availability. Writes succeed during failures that would block a strict quorum.

The cost is that the overlap guarantee goes. The write may sit on stand-ins that a read does not ask, so a read of the owners can miss it even when R plus W exceeds N, until the handoff completes. If the stand-in fails before delivering, the write can be lost. It is a deliberate choice of availability over freshness.

Sources

Practise it in the Quorums lab, or open this question on its own page.

Q10MidA Cassandra-style cluster had one node offline for twelve days. After it returned, rows that had been deleted last week started reappearing. Explain the mechanism and how to avoid it.

A delete in a leaderless store is a write of a marker, a tombstone, since the replicas that missed the delete must be able to learn about it. Tombstones cannot be kept forever, so they are dropped after a grace period. In Cassandra that is gc_grace_seconds, ten days by default.

In this story the node was down when the deletes were made. The other replicas stored the tombstones, and after ten days they discarded them. The returning node still holds the old values. To the cluster, a value with no tombstone anywhere looks like a perfectly valid row that the other replicas somehow missed. Repair or read repair copies it back to them. The deleted rows are resurrected.

Prevention is operational. Run repair on every node more often than the grace period, so tombstones always reach all replicas before they are dropped. A node that has been down for longer than the grace period should not just be started up. Either run a repair before it serves reads, or wipe it and rebuild it from the other replicas. Hints will not help here, since they are only kept for a few hours by default.

Lowering the grace period shrinks the window for tombstones to spread, so it makes the problem worse unless repair runs more often too.

Sources

Practise it in the Quorums lab, or open this question on its own page.

Q11SeniorYou run a five-replica store. Pick R and W for a shopping cart, for a write-heavy event log, and for a configuration store. Defend the choices.

Each workload fixes a different priority. For a shopping cart, availability for writes matters, since a refused add-to-cart loses a sale, and a stale read is tolerable if carts can be merged. Choose a small W, perhaps 1 or 2, a moderate R, and a merge strategy for concurrent versions. The accepted cost is that a read can miss a very recent add.

For a write-heavy event log, writes dominate, so W should be small, such as 1 or 2, with R larger or reads done in the background where staleness is harmless. If readers need completeness, they can read with a higher R when they need it.

For a configuration store, a stale read can cause a wrong action, and writes are rare. Choose R and W with R plus W above N, such as 3 and 3, and accept slower writes. If it must be fully consistent, say a quorum is not enough and move to consensus.

In many systems R and W can be set per request, so one store can serve all three. The final numbers also depend on latency tails, failure rates and whether sloppy quorums are on.

Sources

Practise it in the Quorums lab, or open this question on its own page.

Q12SeniorA leaderless store keeps three replicas in each of two data centres, 80 ms apart. Users read and write in their own region. Compare a global quorum with a per-data-centre quorum for the latency and the guarantees.

There are six replicas, so a global majority is four. Any operation must collect replies from at least one remote replica, since three local ones fall short. Every read and write therefore pays the 80 ms trip, and if the link between the centres is cut, neither side has four nodes, so both stop. In return, a global majority on both reads and writes keeps the usual overlap guarantee across the whole system.

A per-data-centre quorum needs only a majority of the three local replicas, two of them. Operations finish at local speed and keep working during an inter-region cut. The cost is in the guarantees. Within one region, a local read after a local write overlaps and sees it. Across regions, nothing forces the overlap, so a user in the other region can read stale data until asynchronous replication catches up. Two regions can also write the same key at the same time, which needs a conflict rule such as version vectors.

Most deployments choose the local quorum for normal traffic, because 80 ms on every operation is an expensive way to be safe. They keep a global quorum only for the few operations where cross-region freshness matters, and they accept that the data is only eventually consistent across regions.

Also decide how a user is routed. Pinning each user to a region restores read-your-writes for them.

Sources

Practise it in the Quorums lab, or open this question on its own page.

Q13SeniorEven with R + W > N, a quorum store can return surprising results. Give cases and explain what it would take to remove them.

R plus W above N guarantees that a read sees writes acknowledged before it started. It does not make the store behave like one machine. Several cases break that picture.

A read concurrent with a write may return either value, and two reads in a row can return new then old if the write is only partly applied. A write that reaches fewer than W replicas is reported as failed but is not rolled back, so a later read can return it. A sloppy quorum gives the overlap up. If versions are timestamps from unsynchronised clocks, a later write can lose to an earlier one. Concurrent writes to the same key need a policy, such as last write wins, which silently drops one, or version vectors that keep both.

Removing these takes more machinery: a consensus protocol to order writes, or read repair that runs before a read returns, or client-side merge logic. The honest summary is that quorums are tunable and cheap, and they buy bounded staleness in the common case, not a single global order.

Sources

Practise it in the Quorums lab, or open this question on its own page.

Partitioning

14 questions · Read the lesson

Q1JuniorOnce data is split across 30 machines, how does a client know which machine to send a request for a given key to?

Something has to hold the map from key to machine, and there are three usual places.

The client can contact any node. That node checks the map, and if it does not own the key, it forwards the request to the node that does. Nodes keep their copies of the map in sync by gossiping changes to one another. It keeps clients trivial and is how Dynamo-style stores work. The cost is an extra hop for some requests.

A routing tier can sit in front. A small set of proxies holds the map and sends each request to the owner. Clients need no knowledge of the layout, and the proxies are one more service to run.

The client can fetch the map itself and connect directly to the owner. This is the fastest path, but the client's copy goes stale whenever a partition moves, so nodes must reply "not mine, ask over there" and the client must refresh.

Whichever is used, the authoritative map has to be consistent, since two nodes both believing they own one partition would corrupt data. Systems often keep it in a coordination service such as ZooKeeper or etcd, which is built to agree on small, critical state.

Sources

Practise it in the Partitioning lab, or open this question on its own page.

Q2JuniorWhat is a hot partition, and why does it limit a cluster?

A hot partition is one that receives much more traffic than the others. Each partition runs on its own machine or group of machines, so the cluster can only serve a partition's traffic as fast as that machine can. If one partition takes most of the requests, it saturates while the others sit idle.

Adding machines does not help unless the hot data is spread over them. Two common causes are key patterns that concentrate on one range, such as always inserting the newest key, and skew in the traffic, where a few keys are far more popular than the rest.

Finding one takes per-partition request and latency metrics. Comparing the busiest partition against the mean shows it quickly.

Sources

Practise it in the Partitioning lab, or open this question on its own page.

Q3JuniorYou are sharding a users table of 200 million rows. Someone proposes the country as the partition key, because queries are often per country. Another proposes user id. Which would you choose and why?

User id, hashed. A partition key should split data and traffic into many pieces of about equal size, and country does neither. A handful of countries hold most users, so a few partitions would be huge and busy while the rest sit nearly empty. The number of countries, around two hundred, also caps how far the table can ever be spread, however many machines you buy.

Hashing the user id gives hundreds of thousands of distinct values, an even spread, and single-user reads and writes that touch one partition. That covers the most common operations.

The proposal does have a point. "All users in Germany" is now a query across every partition. Whether that matters depends on how often it runs and how fresh it must be. If it is rare, run it as a scatter and gather, or from a replica built for reporting. If it is common, keep a secondary index on country, or maintain a separate table keyed by country that is updated from the main one.

The point is to pick the key for the operations that are both frequent and latency sensitive, and to handle the rest with indexes or copies instead of bending the primary layout around them.

Sources

Practise it in the Partitioning lab, or open this question on its own page.

Q4JuniorWhat is the difference between range partitioning and hash partitioning?

Range partitioning sorts the keys and gives each partition a contiguous stretch of the order. Hash partitioning applies a hash function to the key and uses the result to choose the partition.

Range keeps neighbouring keys together, so a scan over a key range reads from one or two partitions. It can create hot spots when traffic follows the key order, as with timestamps. Hash scatters neighbouring keys, which spreads that kind of traffic evenly, but a scan has to ask many or all partitions.

Rule of thumb: hash when lookups by exact key dominate and even load matters, range when ordered scans matter and the hot ends can be managed.

Sources

Practise it in the Partitioning lab, or open this question on its own page.

Q5JuniorWhy are range queries expensive under hash partitioning?

A range query asks for all keys between two bounds. Under hash partitioning, those keys have unrelated hashes, so they are spread over all the partitions. The query has to be sent to every partition that might hold a match, usually all of them, and the results merged.

The cost is the fan-out, since latency is set by the slowest partition, and the total work is multiplied by the number of partitions. Under range partitioning the same query touches one or two partitions.

Single-key lookups are unaffected. Some stores keep scans affordable by hashing only a prefix of the key and sorting by the rest, so a scan within one prefix stays on one partition.

Sources

Practise it in the Partitioning lab, or open this question on its own page.

Q6MidWhy do many systems create far more partitions than machines, and how does that relate to hash mod N and consistent hashing?

If partition equals hash modulo the number of machines, adding a machine changes the divisor and moves most keys. To avoid that, create many partitions up front, say a few hundred per machine, and assign whole partitions to machines. The key to partition rule never changes. Only the map from partitions to machines does, and adding a machine means moving a few partitions to it.

Consistent hashing with virtual nodes reaches a similar result by a different route. Keys hash onto a ring, the ring is cut into many small arcs, and a joining node takes over some of them. Both limit movement to roughly the new machine's fair share.

The partition count is a real decision. Too few and load cannot be balanced finely or the cluster grown far. Too many and each partition carries overhead. The partition is also the unit of movement, replication and failure.

Sources

Practise it in the Partitioning lab, or open this question on its own page.

Q7MidOne key receives a large share of all requests. Hash partitioning does not help. What do you do?

All requests for a key go to the partition that owns it, whatever the hash function or the number of partitions. So the fix has to spread or absorb the load for that key.

Options: cache the key in front of the database, which works well for reads. Replicate the hot partition more heavily and spread reads over those replicas. For write-heavy hot keys, split the key in the application into several sub-keys, for example by appending a small random number, write to one of them, and combine them when reading. That costs extra reads and some complexity. A hot key can also be given a dedicated partition.

Spotting the key takes metrics at key level, not just per partition. The sub-key approach also needs the application to know which keys to treat that way.

Sources

Practise it in the Partitioning lab, or open this question on its own page.

Q8MidA cache cluster uses hash(key) mod 4 to pick one of four servers. Traffic grows and you add a fifth. Roughly what fraction of keys now map to a different server, and what does that do to the system?

A key stays put only if hash mod 4 equals hash mod 5. Looking at hash mod 20, which covers both, that holds for residues 0 to 3, which is 4 of 20. So about 20 percent of keys stay and 80 percent change servers. In general, going from n to n+1 servers leaves only about 1 in n+1 keys where they were.

For a cache, moved keys are misses. Four fifths of requests fall through to the database at the same moment, which can overload it and turn a scaling step into an outage. For a database or a store of record, 80 percent of the data has to be copied between machines, while serving traffic.

The fix is to separate the two decisions. Use a stable key to partition rule, such as hash mod 1000, with many more partitions than servers, and keep a table assigning partitions to servers. Adding the fifth server then moves about 1000 / 5, or 200, partitions: a fifth of the data, and only to the new machine. Consistent hashing with virtual nodes gets the same effect by placing servers on a ring, so a joining server takes over only the arcs next to its positions.

Either way, add capacity ahead of need, and warm the new node before it takes traffic.

Sources

Practise it in the Partitioning lab, or open this question on its own page.

Q9MidAn orders table is partitioned by customer id. A support tool now needs to find all orders with status 'late'. Compare a local index with a global index for this query and for the write path.

With a local index, each partition indexes its own orders by status. A write touches one partition, updating the row and its index entry together, so it stays cheap and consistent. The support query, though, must ask every partition and merge the answers. Latency is set by the slowest one, and the query's cost grows with the partition count. If each partition has a 1 percent chance of being slow, a query over 32 of them is slow about 28 percent of the time.

With a global index, partitioned by status, the query goes to the one index partition that holds 'late'. It is fast. But every status change now writes to two places, the order's partition and the index partition. Doing that atomically needs a distributed transaction, so most systems update the index asynchronously, and the query can briefly miss a change. DynamoDB's global secondary indexes behave this way. There is another catch: 'late' is a rare, hot value that all queries hit, so its index partition can become the bottleneck.

For a support tool queried a few times a minute, the local index is fine, and the fan-out is acceptable. If it was a customer-facing page hit thousands of times a second, I would use a global index, accept slightly stale results, and consider a separate table that holds only late orders.

Sources

Practise it in the Partitioning lab, or open this question on its own page.

Q10MidA table keyed by timestamp is range partitioned and all the traffic is new inserts. What goes wrong and how do you fix it?

Every new key is larger than every existing key, so all inserts go to the partition holding the highest range. That partition takes all the write traffic while the others only serve reads of old data. Adding machines does not help.

Fixes change the key so that writes spread. Put a prefix in front of the time, such as a hash of an entity id, a shard number, or a bucket number chosen at write time, so concurrent writes land on different partitions. Or hash the whole key, at the cost of ordered scans. Or choose a different primary key, such as a user id first and the time second.

The trade: with a prefix, a time-range query must go to every prefix and be merged. Choose the prefix from the query pattern, so the common queries stay on one partition.

Sources

Practise it in the Partitioning lab, or open this question on its own page.

Q11SeniorDesign the partitioning for a multi-tenant time-series store. Queries are mostly for one tenant over a time window, and ingestion is steady for every tenant.

Let the queries drive the key. A tenant over a time window is a range scan within one tenant. So make the tenant the first part of the key and the time the second. Then a query touches one tenant's range, and ingestion for different tenants is on different parts of the key space.

Consider the failure cases. A very large tenant would make one partition hot and large. Handle that with a bucket component: tenant, then a small bucket number, then time. A big tenant's writes spread over several buckets, and a window query fans out to just those buckets. Small tenants can use a single bucket, so their scans stay on one partition.

Then discuss splits: range partitions must split automatically when they are large or hot, and the split point should reflect load. Cover replication of each partition, secondary indexes, retention by dropping old time buckets, and how you would monitor skew. State the cost: hashing part of the key makes some cross-bucket queries fan out.

Sources

Practise it in the Partitioning lab, or open this question on its own page.

Q12SeniorA single 4 TB database is at its write limit. You must move to 16 shards without downtime. Lay out the migration plan and where it is most likely to go wrong.

First choose the shard key and the key to shard rule. Use many logical shards, for example 256 or 1024 mapped onto the 16 machines, so a later move is a change of assignment and not another rehash. Check the chosen key against real traffic for skew, and find which queries and transactions would cross shards.

Then build the new cluster beside the old one and copy. Take a consistent snapshot and load each shard with its slice of the data, while the old database keeps serving. Keep the new shards in sync by streaming the old database's change log into them, routed by the new rule. Lag falls to seconds.

Verify before cutting over. Compare row counts and checksums per shard, and replay a sample of real reads against the new cluster to compare results. Shift reads first, a percent at a time, using the routing layer, while writes still go to the old database.

Cut the writes over briefly. Stop writes on the old database, wait for the stream to drain, flip routing to the new shards, and resume. This is typically a pause of seconds. Keep the old database in sync in reverse for a while so you can roll back.

Likely failures: cross-shard queries and transactions that assumed one database, auto-increment ids that collide across shards, sequences and unique constraints that were global, a skewed key that still makes a hot shard, and the copy load slowing the live system. Rehearse the whole thing on a copy first.

Sources

Practise it in the Partitioning lab, or open this question on its own page.

Q13SeniorA 12-node sharded cluster has automatic failure detection and automatic rebalancing. During a traffic peak one node slows down, is marked dead, and within ten minutes three more nodes have been marked dead too. Walk through why, and how you would redesign it.

The slow node is the trigger. The detector sees missed heartbeats, which a loaded machine produces, and declares it dead. Rebalancing then copies its partitions to the other nodes. That copying reads, sends and writes a lot of data on machines already at peak, so they slow down. Their heartbeats start to slip, the detector marks another one dead, more partitions move, and the loop feeds itself. It is a classic metastable failure: the recovery action is the load that sustains the outage.

The headroom is also thin. When one of 12 nodes is lost, each survivor takes 12/11 of its old load. At 85 percent utilisation that is 93 percent, before any copying.

Redesign in several places. Make the detector less eager: longer timeouts, require several missed checks, and distinguish slow from dead. Delay rebalancing after a failure. Replication already covers the data, so wait some minutes before copying, since most blips are brief. Rate-limit rebalancing traffic, and prioritise live requests over it. Cap how many nodes can be marked dead at once, and pause automation when too many are suspected, since that usually means a shared cause like the network. Keep the capacity plan honest, with enough headroom to lose a node at peak. And keep a human approval step for large moves.

Sources

Practise it in the Partitioning lab, or open this question on its own page.

Q14SeniorHow and when would you split a hot range partition, what split point do you pick, and where does splitting stop helping?

Split when a partition is too large or too busy, based on size, on request load, or on a sustained imbalance against its neighbours. The split divides one range into two and the halves can move to different machines.

The best split point is where half of the load lies below it, which needs per-key or per-bucket load statistics. Splitting at the middle of the key range or at the median of the stored bytes can leave the traffic lopsided. A split is not free. Data has to move or at least be re-owned, metadata must change atomically, and the partition being split is by definition busy.

It stops helping in two cases. If the hot partition is one key, there is nothing to cut. And with sequential keys, the split only divides old data. Every new key is larger than the split point, so the new upper half takes all the writes and the hot spot simply moves with it. For those, change the key or the partitioning rule.

In practice splits and merges are automated and rate-limited, so a burst of splits does not swamp the cluster.

Sources

Practise it in the Partitioning lab, or open this question on its own page.

Queues as buffers

13 questions · Read the lesson

Q1JuniorWhat is the difference between a burst and sustained overload, and which one can a queue absorb?

A burst is a short stretch where messages arrive faster than the consumers can handle them, but the long-run average is below capacity. The queue grows during the burst and drains afterwards.

Sustained overload means the average arrival rate is above what the consumers can do. There is no quiet time to catch up, so the queue fills and stays full whatever its size.

A queue absorbs bursts. Sustained overload needs more consumers, less work, or load shedding. A bigger buffer only delays the moment the queue fills.

Sources

Practise it in the Queues as buffers lab, or open this question on its own page.

Q2JuniorProducers write 100 messages a second to a queue that holds 1,000. The consumers finish 80 a second. How long until it is full, and what then?

The queue grows by the gap between the two rates: 100 minus 80 is 20 messages a second. Starting empty, it holds 1,000 after 1,000 / 20 = 50 seconds.

After that the queue is full and every extra message needs a decision. Block the producer, refuse the newest, or evict the oldest. None of these makes the consumers faster. The 20 a second that cannot be handled is still there, and it now shows up as blocked callers or dropped messages.

The useful reading is that a bigger queue only buys time. At 10,000 slots the same arithmetic gives 500 seconds, which is a longer warning and a longer wait for every message at the back. The fix is on the rate side: five more messages a second from each consumer, a fifth consumer if each does 20 a second, or less work arriving.

Sources

Practise it in the Queues as buffers lab, or open this question on its own page.

Q3JuniorA bounded queue is full and another message arrives. What are your options?

There are three common choices. Block the producer, so the send waits for room. Drop the newest message, which refuses the arrival. Drop the oldest, which evicts the head to make room.

Blocking loses nothing but moves the delay upstream. Dropping the newest protects the work already accepted. Dropping the oldest keeps the freshest data, which suits readings that are replaced by newer ones.

Fit the choice to the data. Orders cannot be dropped, while a position update can. Returning an error to the caller is a fourth option: it is dropping, but the caller can see it.

Sources

Practise it in the Queues as buffers lab, or open this question on its own page.

Q4JuniorA dashboard shows 10,000 messages in a queue. Should you worry?

Not from that number alone. Depth only becomes meaningful next to the drain rate. If the consumers finish 5,000 a second, 10,000 messages is two seconds of work. If they finish 10 a second, it is more than 16 minutes.

Little's law gives the second view. Divide depth by the arrival rate and you get the average wait in the queue. At 500 arrivals a second, 10,000 waiting means about 20 seconds.

Then check the direction. A depth of 10,000 that was 12,000 an hour ago is draining. The same depth that was 2,000 an hour ago is growing, and growth means arrivals exceed capacity. So I would look at three things together: depth, its trend, and the age of the oldest message, which is what a user actually experiences. Whether 10,000 is fine depends on how long a message can wait before it stops being useful.

Sources

Practise it in the Queues as buffers lab, or open this question on its own page.

Q5JuniorWhy put a queue between a producer and a consumer instead of calling the consumer directly?

A queue decouples the two in time and in speed. The producer hands over the message and moves on. The consumer takes it when it is ready. Bursts that would overwhelm a direct call turn into a short wait.

It also lets the two sides fail and scale on their own. A consumer that is down for a minute does not stop the producer, as long as the queue has room.

The cost is delay, one more component to run, and a decision about what happens when the queue is full. Keep one limit in mind: a queue smooths bursts, and it never creates capacity.

Sources

Practise it in the Queues as buffers lab, or open this question on its own page.

Q6MidYou are setting up an alert on a work queue. Do you alert on depth or on age of the oldest message?

Age, with depth as a supporting graph.

A depth threshold is tied to consumer speed. An alert at 5,000 messages is too late for a queue whose consumers do 10 a second (a 500 second wait) and a false alarm for one that does 5,000 a second. Every scaling change moves the right number.

Age is the delay the caller sees, so the threshold can come from a requirement: for example, page when the oldest message is over 60 seconds, warn at 30. Most hosted brokers publish it, such as the oldest-message age metric in SQS. For others, stamp an enqueue time on each message and compute it.

Age has blind spots. A single stuck message at the head of a strictly ordered queue raises age while the rest flows, so pair it with a throughput graph. And an empty queue has no age, so also alert if consumers stop completing work at all. I would add a separate alarm for the dead-letter queue.

Sources

Practise it in the Queues as buffers lab, or open this question on its own page.

Q7MidProducers send 20 percent more than the consumers can process. A teammate proposes making the queue ten times bigger. What do you say?

It will not raise throughput. The consumers still finish the same number of messages per second, so the excess is lost or held back as before, only later.

What changes is the wait. A full queue holds about its capacity and drains at a fixed rate, so ten times the buffer means roughly ten times the delay. Messages that have waited that long may no longer be useful.

Better proposals are more consumers, cheaper work, or shedding load at the edge. A bigger buffer is right in one case only: a burst longer than today's buffer, with average load below capacity.

Sources

Practise it in the Queues as buffers lab, or open this question on its own page.

Q8MidState Little's law and use it on a queue. Where does it help in practice?

In a stable system, the average number of items inside equals the average arrival rate times the average time each item spends inside: L = λ W.

For a queue, if 40 messages wait on average and messages enter at 20 a second, a message waits about 2 seconds. You can read two of the three numbers from a dashboard and get the third without timing messages.

It holds for any arrival pattern and any service order, but only for averages, so it says nothing about the slowest messages. "Stable" means the queue does not grow without limit. L, λ and W must also describe the same boundary: if L counts only waiting messages, W must be the wait and not the wait plus processing.

Sources

Practise it in the Queues as buffers lab, or open this question on its own page.

Q9MidWhy does latency rise so sharply as utilization approaches 100 percent, even when the average load is below capacity?

Arrivals are random. At low utilization the consumers are idle often enough to clear any clump of arrivals at once. Near full utilization there is almost no idle time, so a small clump leaves a backlog that takes a long time to drain, and the next clump lands on top of it.

In simple queueing models the average wait grows without bound as utilization approaches 1. The curve is flat at first and then bends up steeply, so a system that looks healthy at moderate load can fail with a small increase.

In practice, keep headroom and alarm on queue age, not only on CPU. Variable service times make the curve steeper still.

Sources

Practise it in the Queues as buffers lab, or open this question on its own page.

Q10MidMost jobs take 300 ms, but a few reports take 30 seconds, and they share a queue and three consumers. Users complain that simple actions sometimes hang. Why, and what do you change?

This is head-of-line blocking. When a few report jobs arrive together, they can hold all three consumers for 30 seconds. Every quick job that arrives in that window waits, though it needs a third of a second.

The mean hides it. With 1 report in 100, mean service time is about 0.6 seconds, which looks fine. The 99th percentile of wait is where the pain is.

The cheapest change is separate queues with separate consumers: two for quick work, one for reports. A burst of reports now delays only other reports. The price is some idle capacity, since a spare report consumer cannot help the quick queue.

Priorities inside one queue are the other route, but they only order the waiting line. They do not interrupt a job already running, so a 30 second job still occupies its consumer. They also risk starving low-priority work unless you reserve some share for it.

Sources

Practise it in the Queues as buffers lab, or open this question on its own page.

Q11SeniorAn API accepts uploads, puts a job on a queue and returns 202. During a spike the queue fills and jobs wait over ten minutes. Design the behaviour under overload.

Start with the wait budget. If a result is useless after two minutes, the queue should never hold more than two minutes of work. At a drain rate of 50 jobs a second, that is 6,000 jobs, and anything beyond it only creates stale work.

So bound the queue by that number and make admission explicit. When depth or age passes the threshold, the API should refuse new work quickly, with a 429 or 503 and a Retry-After header, instead of accepting jobs that will expire. Rejecting is cheaper than queueing something that will be discarded later, and it tells clients to slow down.

Then protect what is already accepted. Put a deadline on each job and have consumers skip expired ones. Separate queues or priorities keep paying customers or small jobs from waiting behind bulk ones. Retries from clients need backoff with jitter, or they turn the spike into a sustained overload.

On the capacity side, add autoscaling keyed to queue age, with a ceiling so a spike cannot take down the database the workers hit. Finally, record how many jobs were refused or expired, so the capacity discussion is based on numbers.

Sources

Practise it in the Queues as buffers lab, or open this question on its own page.

Q12SeniorA downstream outage ends, and the queue in front of it takes hours to recover even though capacity is back. What could be going on, and what do you change?

Likely causes are a large backlog drained at a rate only slightly above the arrival rate, retries that add load while the service is struggling, and stale messages that are processed although nobody wants the result any more.

The drain time of a backlog is its size divided by the spare capacity, which is the consumer speed minus the arrival rate. If spare capacity is small, recovery is slow. Near full load that stretch gets very long.

Fixes include temporary extra consumers, expiring messages older than a deadline, retries with backoff and a cap, and priorities so fresh work does not wait behind old work. Recovery capacity needs planning in advance, just as steady-state capacity does.

Sources

Practise it in the Queues as buffers lab, or open this question on its own page.

Q13SeniorHow would you decide how big a queue should be?

Start from the latency you can accept, not the memory you have. By Little's law, the wait of a full queue is about its capacity divided by the drain rate. Pick the longest wait after which a message is still useful, and multiply by the drain rate.

Check the other side too. The queue should be big enough to hold the longest burst you expect, given how fast consumers drain it. If the two requirements conflict, the consumers are too slow, and the fix is capacity.

The limit itself should be a deliberate policy. Watch queue age as well as depth, and alarm when the queue stays full. The sizing assumes bounded bursts and service times without heavy tails, so if either fails the numbers are optimistic.

Sources

Practise it in the Queues as buffers lab, or open this question on its own page.

Delivery guarantees

13 questions · Read the lesson

Q1JuniorWhy does the order of "do the work" and "ack" matter?

The ack tells the broker to forget the message. If you ack first and crash before the work, the message is gone and the work never happens. If you work first and crash before the ack, the broker redelivers and the work happens again.

So the order picks which failure you accept: loss or repetition. The broker cannot tell a crash before the work from a crash after it, because both look like a missing ack.

Most systems choose repetition, then make the work safe to repeat.

Sources

Practise it in the Delivery guarantees lab, or open this question on its own page.

Q2JuniorWhat is an ack timeout, and what goes wrong if it is set too short or too long?

It is the time the broker waits for an acknowledgement before it assumes the consumer failed and hands the message to another one. Some brokers call it a visibility timeout.

Too short, and a slow but healthy consumer has its message redelivered while it is still working, so the work is done twice. Too long, and when a consumer really dies its messages sit unclaimed for that whole time.

Set it from the slowest normal processing time plus margin. Some brokers let a consumer extend the timeout while work continues, which avoids one long fixed value.

Sources

Practise it in the Delivery guarantees lab, or open this question on its own page.

Q3JuniorWhat do at-most-once, at-least-once and exactly-once delivery mean?

At most once: a message is delivered zero or one times. It may be lost, and it is never repeated. At least once: a message is delivered one or more times. It is never lost, and it may be repeated. Exactly once: the effect of each message happens once.

At-most-once comes from acknowledging before the work. At-least-once comes from acknowledging after the work, with redelivery on timeout. Exactly once cannot be had from delivery alone and is built on top of at-least-once.

Concrete cases make the difference clear. A metrics sample can tolerate loss. A payment tolerates neither loss nor repetition.

Sources

Practise it in the Delivery guarantees lab, or open this question on its own page.

Q4JuniorA message has failed processing five times in a row. What should happen to it, and why not retry forever?

It should move to a dead-letter queue after a set number of attempts. Most brokers can do this by a configured limit: in SQS it is the max receive count on the redrive policy.

Retrying forever has two costs. First, the message occupies consumer time on every attempt. A message that fails in 50 ms and is redelivered at once burns 20 attempts a second. Second, in an ordered queue it can block the messages behind it.

The dead-letter queue keeps the message for a person or a repair job. It only helps if somebody looks, so alarm on anything arriving there, keep the original body with the last error, and give it a longer retention than the source queue.

Also separate failures by kind. A validation error will never succeed, so it can be dead-lettered at once. A timeout from a dependency might heal, so it gets more attempts spaced further apart.

Sources

Practise it in the Delivery guarantees lab, or open this question on its own page.

Q5MidName the ways a consumer can end up processing the same message twice without any crash.

A slow consumer is the main one. If processing takes longer than the ack timeout, the broker redelivers while the first attempt is still running, and both finish.

Others include a lost ack, where the consumer finished but the ack never reached the broker. A producer that retries a send that did succeed leaves two copies in the queue. A rebalance or failover can hand the same message to a second consumer. A replay deliberately repeats history.

So duplicates are routine, not rare. That argues for an idempotent consumer, not for hoping the timeouts are tuned right.

Sources

Practise it in the Delivery guarantees lab, or open this question on its own page.

Q6MidA vendor says its broker offers "exactly once". How would you evaluate that claim?

Ask what is counted once. A broker can avoid duplicate writes inside its own storage. It cannot control what your consumer does with a message, such as a call to a payment API.

A realistic guarantee is effectively-once: at-least-once delivery plus either idempotent processing or a transaction that commits the result and the read position together. That works where the effect and the position live in the same system, and it stops at the boundary with outside systems.

Probe the boundary: what happens on producer retries, and on a failure during a commit? The end-to-end argument is the reason. Only the application knows what "the same effect" means, so the final guarantee is completed there.

Sources

Practise it in the Delivery guarantees lab, or open this question on its own page.

Q7MidHow does an idempotency key make a consumer safe against redelivery? What is the catch?

Each message carries an identifier that is the same on every attempt. The consumer stores the identifiers it has applied. Before acting it checks the store. If the key is present, it skips the effect and acks.

The catch is atomicity. The key must be written in the same transaction as the effect. If the effect happens and the crash comes before the key is stored, the retry repeats the effect. If the key is stored first and the effect fails, the effect is lost.

Keys also expire, so the window must outlast the longest possible redelivery. And an effect outside your database, such as an email, stays safe only if the other system honours the key.

Sources

Practise it in the Delivery guarantees lab, or open this question on its own page.

Q8MidConsumers update a customer's address from events. A redelivered old event overwrote a newer address. How do you prevent that?

Redelivery can hand a consumer an old event after a newer one was applied. Being idempotent is not enough here, because applying the old event is a legitimate first time for that event. What is missing is an ordering check.

Attach a monotonic version to each entity's events: a sequence number from the producer, or the entity's version column. The consumer applies an update only if the event's version is higher than the stored one. In SQL that is a conditional write, such as updating where the stored version is lower, so the check and the write are one atomic step.

Where events cannot carry a version, a timestamp from the source of truth can serve, with the usual care about clock skew. Keying messages by customer id keeps one customer's events in one partition, which makes the stream mostly ordered and shrinks the window where a late duplicate can appear.

Last, store the version even when you skip an event. Otherwise a very old duplicate could arrive after the record has been cleared.

Sources

Practise it in the Delivery guarantees lab, or open this question on its own page.

Q9MidA service must save an order in its database and publish an order-placed event. How do you make sure neither happens without the other?

Writing to the database and then to the broker is two writes with no shared transaction, so a crash between them leaves one without the other. Retrying does not close the gap, because the crash can come before the retry.

Use a transactional outbox. In the same database transaction that inserts the order, insert a row describing the event into an outbox table. Both commit or neither does. A separate relay then reads unsent rows, publishes them and marks them sent. Change-data-capture tools can do the same job by reading the database log.

If the relay crashes after publishing and before marking, it publishes the event again. So the pattern gives at-least-once publishing, not exactly once. Give every outbox row a stable id, put it in the event, and let consumers use it as an idempotency key.

Operationally, delete or archive sent rows so the polling query stays fast, and publish in write order with the order id as the key if events for one order must stay ordered.

Sources

Practise it in the Delivery guarantees lab, or open this question on its own page.

Q10SeniorDesign the consumer side of a payment queue so that no customer is charged twice and no payment is lost.

Use at-least-once delivery so nothing is lost, and make the charge idempotent so repeats do nothing. Attach a payment identifier to the message at the producer, before the first send, so it is the same on every retry.

In the consumer, charge through an API that accepts the identifier as an idempotency key. If you also keep your own record, write the key and the state change in one database transaction. Ack only after both are done.

Cover the gaps. A crash after the charge and before the record needs the gateway to remember the key, or a way to look up the charge by key on retry. Keys must outlive the longest redelivery. Add a dead-letter queue and reconciliation against the gateway's records, because no design removes the need to check.

Sources

Practise it in the Delivery guarantees lab, or open this question on its own page.

Q11SeniorA dependency was down for ten minutes, and 200,000 healthy messages ended up in the dead-letter queue. How do you recover, and how do you stop it happening again?

Recovery first. The messages are valid, so redrive them. Do it at a controlled rate, not all at once. Pushing 200,000 back immediately lands a spike on top of normal traffic and may knock the dependency over again. At 500 a second the redrive takes 400 seconds. Watch queue age and the dependency's error rate while it runs, and pause if either rises. The consumer must be idempotent, since some of these messages may have partly run before.

Prevention has two parts. The retry limit and spacing should outlast a plausible outage. Three tries 30 seconds apart gives up after about 90 seconds, so a ten minute outage dead-letters everything. Better, stop consuming while the dependency is known to be down: a circuit breaker around the call, which pauses the consumer or returns messages to the queue with a delay, so attempts are not spent.

Distinguish permanent errors, which go to the DLQ at once, from transient ones, which should not burn attempts so quickly. Alarm on DLQ arrival rate, so a flood pages someone within a minute and not after the weekend.

Sources

Practise it in the Delivery guarantees lab, or open this question on its own page.

Q12SeniorYour consumer sends a confirmation email through a provider that has no idempotency key. At-least-once delivery means some customers get two. What are your options?

The crash window cannot be closed completely when the provider cannot dedupe, so the real question is which error you prefer and how much you can shrink it.

Record intent before sending. Write a row for the message id with state pending, send, then set sent. On redelivery the consumer reads the state. If it is sent, skip. If it is pending, the previous attempt may or may not have gone out, and that is the gap. For an order confirmation I would send again and accept a rare duplicate. For something harmful to repeat, I would not send and would flag it for review.

Shrink the gap by keeping the pending-to-sent window short and the ack timeout longer than the provider call, so slow calls do not trigger redelivery. Use the provider's message id or delivery status, where there is one, to check whether the pending email went out.

Finally, decide the policy by cost. A duplicate confirmation is an annoyance, while a missing one may cause a support ticket. Write the choice down, and count duplicates so the rate is known.

Sources

Practise it in the Delivery guarantees lab, or open this question on its own page.

Q13SeniorCompare making a consumer idempotent with committing the result and the read position in one transaction. When would you choose each?

An idempotent consumer works with any at-least-once source and any target that can recognise a repeat, by key or by an operation like "set to this value". It is simple and portable. It needs a key, a store, and care about expiry.

A transactional commit saves the result and the offset together, so a failure leaves neither. It gives a clean effectively-once result without keys, but it needs a target and a source that can share a transaction or a checkpoint, which limits where it applies.

Choose idempotence for effects on external systems and for mixed technologies. Choose the transaction when the output stays inside one store you control. Either way, the guarantee ends at the system boundary.

Sources

Practise it in the Delivery guarantees lab, or open this question on its own page.

Partitioned logs

14 questions · Read the lesson

Q1JuniorHow is a message assigned to a partition, and why does the key matter?

The producer hashes the message key and takes the result modulo the number of partitions. Messages with the same key always go to the same partition. Without a key, messages are spread out for balance.

The key matters because it gives ordering. Messages for one account, order or device stay together and are read in the order they were sent.

Pick a key that groups what must stay in order and also spreads load evenly. A key that is too coarse overloads one partition.

Sources

Practise it in the Partitioned logs lab, or open this question on its own page.

Q2JuniorHow is reading from a log like Kafka different from reading from a traditional queue?

A queue removes a message once a consumer acknowledges it. A log keeps it. Reading only moves the consumer's position, the offset, forward.

That has three consequences. First, several independent consumers, or groups, can read the same data at their own pace, because each keeps its own position. Second, a consumer can go back and read again, to rebuild a table or to recover from a bug. Third, deletion is by retention (age or size), not by acknowledgement, so a slow consumer can lose data if it falls behind the window.

Ordering is also different. A queue with many consumers loses order, while a log keeps order inside each partition and gives each partition to one consumer in a group.

The cost is that the consumer is responsible for tracking progress, and a crash repeats whatever came after the last commit.

Sources

Practise it in the Partitioned logs lab, or open this question on its own page.

Q3JuniorWhat is an offset, and how does a consumer use it?

An offset is the position of a message inside one partition, counted from the start. It never changes for that message.

A consumer remembers the offset of the next message it should read. It saves that value from time to time, which is called committing. After a restart, it begins from the committed offset.

Work done after the last commit is repeated, so consumers should tolerate repeats. An offset only means something inside its own partition.

Sources

Practise it in the Partitioned logs lab, or open this question on its own page.

Q4JuniorBilling and analytics both need every event from the orders topic. How do you set up the consumers?

Give each service its own consumer group. A group gets a full copy of the stream, and the members inside it split the partitions. So the billing group and the analytics group each see every event, and each keeps its own committed offsets.

Putting both services in one group would be a mistake: the group would split the messages, so billing would see some orders and analytics the rest.

Because the groups are independent, they can run at different speeds. Analytics may batch and fall minutes behind while billing stays current. The one coupling is retention: if analytics falls further behind than the log keeps data, it loses events, so alarm on its lag.

Each group should be sized to the partition count. If the topic has 12 partitions, 12 is the useful maximum per group.

Sources

Practise it in the Partitioned logs lab, or open this question on its own page.

Q5JuniorWhat is a partition in a log-based system, and why have more than one?

A partition is one ordered, append-only slice of a topic. Each message gets an offset in its partition. Several partitions let many consumers read in parallel and let producers write to several machines.

One partition is one line with one reader, so its throughput is limited to what a single consumer can handle. With more partitions the topic scales out.

Order holds inside a partition, not across partitions. The partition count also sets how many consumers in a group can work at once.

Sources

Practise it in the Partitioned logs lab, or open this question on its own page.

Q6MidExplain consumer groups. What happens when there are more consumers than partitions?

A consumer group is a set of consumers that share a topic. The group assigns each partition to exactly one member, so partitions are read in order and no message goes to two members of the group. Different groups each get their own full copy of the stream.

If the group has more members than partitions, the extra members own nothing and sit idle. Adding consumers beyond the partition count does not increase throughput.

That is why the partition count deserves capacity planning. Leave room to grow, because raising it later is disruptive.

Sources

Practise it in the Partitioned logs lab, or open this question on its own page.

Q7MidWhat ordering does a partitioned log guarantee, and how do you get ordering across keys if you need it?

Messages in the same partition are delivered in the order they were appended. Because the key picks the partition, messages with the same key are ordered. There is no guarantee between partitions.

For a global order you can use a single partition, which caps throughput, or you can attach a sequence number or timestamp and reorder downstream, accepting buffering and some delay. Often the real requirement is order per entity, and the key already gives it.

Separate what needs order from what does not. Producer retries can also reorder messages unless the producer limits sends in flight.

Sources

Practise it in the Partitioned logs lab, or open this question on its own page.

Q8MidA new topic must carry 30,000 messages a second. One consumer finishes 1,500 a second, and one partition can take 10,000 a second from producers. How many partitions do you create?

Take the larger of the two requirements. Producers need 30,000 / 10,000 = 3 partitions. Consumers need 30,000 / 1,500 = 20. So 20 is the floor, set by the consumer side.

I would not stop at 20. If traffic is likely to double, 40 leaves room to add consumers without touching the topic, which matters because changing the count later remaps keys. Running 20 consumers on 40 partitions means two partitions each, which is fine.

Going far past that has costs. More partitions mean more open files, longer leader elections when a broker fails, bigger rebalances and smaller producer batches. Sizing for twice the projected need is a reasonable balance.

Check the assumption behind the number too. The formula assumes load spreads evenly over keys. If one key carries a large share, the partition holding it needs a consumer faster than 1,500 a second, and no partition count fixes that.

Sources

Practise it in the Partitioned logs lab, or open this question on its own page.

Q9MidIn your consumer loop, where do you commit the offset, and what changes if you move it?

After the work, for most consumers. Read a batch, apply its effects, then commit the offset of the next message to read. A crash before the commit makes the next owner re-read the batch, so effects repeat but nothing is lost. That is at-least-once, and it pairs with idempotent effects.

Commit before the work and a crash loses the batch, which is at-most-once. That is acceptable for data like metrics, where a gap is cheaper than a repeat.

Auto-commit is the one to be careful with. The Java client commits on a timer (5 seconds by default) inside poll, so a batch can be committed while it is still being processed, or after it failed.

Batch size is the dial. Committing every message sends many commits, while committing every 500 repeats up to 500 messages after a crash. Pick by the cost of a repeat. Also commit one past the last message you finished, or that message replays on each restart.

Sources

Practise it in the Partitioned logs lab, or open this question on its own page.

Q10SeniorA topic with 12 partitions is at its limit. Consumers keep per-customer state in memory. How do you move to 24 partitions safely?

Adding partitions in place changes the hash modulo, so about half of the keys move. For a while, a customer's older messages sit in one partition and newer ones in another, potentially handled by two consumers. In-memory state keyed by customer would be split or wrong, and per-key order breaks across the change.

The safer route is a new topic with 24 partitions. Producers write to both for a transition period, or a copier job moves history across. Consumers drain the old topic, build state in the new one, and switch when lag is zero on the old topic. Order per key holds, because each topic is consistent within itself.

If an in-place change is the only option, stop producers briefly, let consumers reach the end of the log, then add partitions, so no key has data in two places. This costs a short outage.

Either way, key consumer state by the message key and not the partition number, and confirm new partitions will not be empty and idle: 24 consumers is needed to use them.

Sources

Practise it in the Partitioned logs lab, or open this question on its own page.

Q11SeniorOne customer generates a third of your traffic and you key by customer. How do you keep the partition from falling behind?

A key maps to one partition and a partition has one reader in the group, so neither more partitions nor more consumers helps a single key. The options all trade order for balance.

Add a salt to the key for the big customer, such as a small random suffix, so its traffic spreads over several partitions. Order then holds only within each suffix. Or split by a finer key, like the customer plus the entity inside it. Or make that consumer faster by batching, or by moving heavy work to a separate pool.

Ask what ordering the customer really needs. It is often per entity and not per customer. And measure first rather than assume the cause.

Sources

Practise it in the Partitioned logs lab, or open this question on its own page.

Q12SeniorA consumer lag alert fires. The consumers look healthy and CPU is low. How do you investigate?

Lag as a single number hides where it sits. First, look per partition. If one partition carries all of the lag and the others are at zero, it is a hot key or a stuck message, and more consumers would not help. Find the key and check the partitioner.

If lag is spread out and the group is rebalancing repeatedly, the cause is usually a consumer taking longer than the poll interval (five minutes by default in the Java client), which gets it evicted. The signs are many rebalance events and offsets that move backwards. A slow downstream call inside the loop is the usual reason, and the fix is smaller batches or a longer interval.

If consumers are idle and lag still grows, check whether they own partitions at all. More members than partitions leaves some idle. Check producers too: a rate jump looks like consumer lag.

Last, compare lag with the retention window. If lag is approaching it, data is about to be deleted unread. That sets the urgency. I would also graph time lag, not just message count.

Sources

Practise it in the Partitioned logs lab, or open this question on its own page.

Q13SeniorWhat happens during a consumer group rebalance, and how do you limit the damage?

When a member joins, leaves or fails, the group redeals partitions. In the simple protocol every member stops reading, then each partition resumes from its committed offset. During the pause producers keep writing, so lag builds. Work done since the last commit is read again.

Damage grows with frequent rebalances. Causes are slow processing that looks like a failure, flaky health checks, and rolling deploys that restart members one by one.

To limit it, tune timeouts so slow work is not mistaken for failure, restart members gently, commit more often, and use newer protocols that move fewer partitions at a time. Consumers must also be idempotent, because the repeat is built in.

Sources

Practise it in the Partitioned logs lab, or open this question on its own page.

Q14SeniorYour team wants to rebuild a derived table by replaying a topic from the start. What do you check before doing it?

First, retention. The log holds only what its retention window keeps. If the history you need was deleted, replay cannot recover it, and a compacted or archived copy is needed.

Second, side effects. Consumers that act on messages, such as sending email, must not repeat effects during a replay. Use a separate group for the rebuild, with output going to a new table, and switch over when it has caught up.

Third, capacity and ordering. A replay competes with live traffic, so throttle it. Keys must stay in order, and the code has to handle old message formats. All of this works because a log does not delete messages on read.

Sources

Practise it in the Partitioned logs lab, or open this question on its own page.

Rate limiting algorithms

13 questions · Read the lesson

Q1JuniorWhat should a server send back when it rejects a request because of a rate limit?

The standard answer is HTTP status 429, Too Many Requests. It says that this caller has sent too many requests in a given time. It is the right code for a per-caller limit. A 503 means the server itself cannot take the request, which is a different message.

Add a Retry-After header. It tells the client how many seconds to wait, or a date to come back at. Without it every client guesses, and many guess the same delay. With it the server sets the schedule.

Make the rejection cheap and fast. It should cost far less than serving the request, or the limiter protects nothing. A short body that says which limit was hit helps the people debugging a client.

Many APIs also return headers with the limit, the remaining allowance and the reset time on every response, so well behaved clients can pace themselves before they are rejected.

Clients have to honour the signal. Retrying at once on a 429 turns the limit into a loop.

Sources

Practise it in the Rate limiting algorithms lab, or open this question on its own page.

Q2JuniorA token bucket holds 20 tokens and refills at 5 a second. A client has been idle for a minute, then sends 30 requests at once. How many get through, and how many can it send each second after that?

After a minute idle the bucket is full, so it holds 20 tokens. The 30 requests arrive in the same instant. The first 20 each take a token and are admitted. The other 10 find the bucket empty and are rejected.

From then on the refill sets the pace. At 5 tokens a second the client can send 5 requests a second, forever. If it sends 5 a second the bucket stays near empty. If it sends fewer, say 2 a second, the unused tokens pile up again at 3 a second, and after about 7 seconds the bucket is full and the client can burst 20 once more.

So the two settings do different jobs. The bucket size of 20 is the largest burst the service has agreed to take. The refill of 5 is the average rate it can sustain. If 20 at once is too much for the backend, the fix is a smaller bucket. If 5 a second is too much, the fix is a lower refill.

One detail: the 10 rejected requests got an answer immediately. They did not wait for tokens. Waiting for tokens is the leaky bucket queue, a different design.

Sources

Practise it in the Rate limiting algorithms lab, or open this question on its own page.

Q3JuniorDescribe the fixed window counter. What is its main weakness?

It keeps a count and the start of the current window, for example one minute. Each admitted request adds one. When the clock passes the window edge, the count goes back to zero. A request is rejected if the count already equals the limit.

It is the cheapest limiter. It needs two numbers per caller, one increment per request, and no cleanup beyond the reset.

The weakness is the edge. The count forgets everything at the boundary. A caller that sends a full limit just before the edge and another full limit just after it gets twice the limit through in a very short time, and neither window was ever over. The same thing happens naturally when many clients all act at the top of a clock minute.

The worst case is twice the limit in any span the length of a window. There are two usual fixes: a sliding window, which needs more state, or a token bucket, which caps a burst at the bucket size plus what refills.

Sources

Practise it in the Rate limiting algorithms lab, or open this question on its own page.

Q4JuniorYour API limits each source address to 10 requests a second. A customer with 300 staff behind one office gateway says the API keeps rejecting them. What is going on, and what would you change?

All 300 people reach you through the gateway's single public address, so they share one allowance. If even a third of them are active at the same moment, 100 users split 10 requests a second, which is 0.1 request a second each. Any page that makes a few calls hits the limit at once. The limiter is working as written. The key is wrong for this customer.

The address is a poor stand-in for a person. Behind one address you can find an office, a university, a mobile carrier or a proxy, and many unrelated people. The reverse also happens: one attacker can use many addresses and never meet the limit.

The change is to key on what you actually want to protect. For authenticated calls that is the API key or account, which maps to a customer and to a contract. Keep a coarse address limit, set high, as a guard for anonymous traffic. If the customer is a paying one, you can also raise their limit on request, or give a known gateway address its own larger allowance.

Then tell them what happened. A 429 that names the limit hit, plus a Retry-After header, would have saved the support ticket.

Sources

Practise it in the Rate limiting algorithms lab, or open this question on its own page.

Q5JuniorWhat does a rate limiter do, and where in a system would you put one?

A rate limiter caps how many requests a caller may make in a period of time. It checks each request against an allowance kept for that caller and rejects the ones over it. The caller can be a user, an API key, an address, a tenant, or a whole service.

It does two jobs. It protects a service from one caller who sends too much, by accident or on purpose. And it shares capacity out, so that one heavy caller cannot crowd everyone else out.

Common places are an API gateway or reverse proxy at the edge, a middleware layer inside a service, and the client side for calls to a paid or fragile dependency. Putting it early is cheaper, because a rejected request has used almost nothing. Putting it close to the resource is more accurate, because it knows what the resource can take.

Do not confuse this with load shedding. A limiter looks at the caller and enforces a promise made in advance. Shedding looks at the server's own state and reacts to overload. Most services need both.

Sources

Practise it in the Rate limiting algorithms lab, or open this question on its own page.

Q6MidA nightly job must make 5,000 calls to a partner API that allows 10 requests a second. How do you build the client side so it neither gets blocked nor takes longer than it needs to?

Put a limiter on your own side that paces calls below the partner's limit. A leaky bucket fits well, because the job can tolerate delay: calls go into a queue and leave at a fixed rate. Set the rate a little under the partner's, say 9 a second, since your clock and theirs will not agree and a window edge on their side can bunch your calls. At 9 a second, 5,000 calls take about 556 seconds, under ten minutes. At 10 a second it would be 500 seconds. The margin costs about a minute.

If the partner uses a token bucket with a burst allowance, you could send the first calls faster, but the saving is a few seconds on a job this long. It is not worth the risk of being rejected.

Still expect 429 responses, because other jobs of yours may share the key. When one arrives, honour its Retry-After, pause the whole queue and not just that call, and resume at the normal rate. Retrying only the failed call while the rest keep flowing keeps you at the limit and earns more rejections.

Run several workers in parallel only if they share one limiter. Ten workers each pacing at 9 a second send 90.

Sources

Practise it in the Rate limiting algorithms lab, or open this question on its own page.

Q7MidYour API runs on many servers. How do you enforce one rate limit per user across all of them?

The simple approach is a shared store that holds the counter for each user. Every server increments it. The danger is a race: two servers read 19, both admit, and both write 20. The fix is an atomic operation in the store, such as an increment that returns the new value, or a small script that runs the whole check inside the store.

The shared store adds a network hop to every request and becomes a dependency. To cut that, a server can keep a local allowance and sync with the store now and then. That is faster, and the limit becomes approximate, with some slack equal to what can be spent between syncs. Another option is to route each user to a fixed server, for example by hashing the key, so the count is local. That fails when the server goes away.

Decide what happens when the store is down. Failing open keeps the service up and drops protection. Failing closed protects the service and causes an outage. Protective limits usually fail open. Hard quotas, where extra traffic costs money, are more often closed.

Sources

Practise it in the Rate limiting algorithms lab, or open this question on its own page.

Q8MidHow do the sliding window log and the sliding window counter differ, and what does each cost?

The sliding window log stores a timestamp for every admitted request. To decide, it drops timestamps older than one window and counts the rest. It is exact: in any span of one window it never admits more than the limit. Its cost is memory and work. State grows with the limit for every caller, and each decision trims and scans a list.

The sliding window counter keeps just two counts, for the current and the previous fixed window. It estimates the count over the last window as the previous count times the share of that window still in view, plus the current count. It assumes the previous window's requests were spread evenly. If they were bunched, the estimate is off, in either direction.

So the log trades memory for exactness, and the counter trades a small error for a few numbers per caller. For a very large number of callers the counter or a token bucket is usually the practical choice. For a hard cap, such as a billed quota, the log is the safer one.

Per caller, the log stores up to the limit in timestamps. The counter stores two counts and a window start. Its error comes entirely from the even-spread assumption.

Sources

Practise it in the Rate limiting algorithms lab, or open this question on its own page.

Q9MidCompare the token bucket and the leaky bucket. When would you choose each?

A token bucket fills with tokens at a steady rate up to a maximum. Each request takes a token. If there is none, the request is rejected. The refill rate sets the long-run rate. The bucket size sets how large a burst can be, because a full bucket lets that many requests through at once.

A leaky bucket, used as a queue, puts requests in a queue that drains at a fixed rate. A burst is not rejected but delayed, and what comes out is smooth. Requests are rejected only if the queue is full. Used as a meter, it counts room left in the bucket, which is the same arithmetic as the token bucket.

So the real difference is what happens to a request that arrives early. The token bucket answers yes or no at once, and passes bursts straight through. The leaky bucket queue answers wait, and shapes traffic for whatever is downstream.

Choose the token bucket for an API where clients may legitimately burst and a prompt answer matters. Choose the leaky bucket when the thing behind it cannot take bursts, such as a connection to a fragile backend, and delay is acceptable. State is small for the token bucket and grows with queue size for the leaky one.

Sources

Practise it in the Rate limiting algorithms lab, or open this question on its own page.

Q10MidYour search endpoint answers in 5 ms, but a report endpoint can take 2 seconds of CPU. A flat limit of 100 requests a minute lets one customer take the service down with reports. How would you change the limiter?

Count work, not requests. Move to a token bucket where each call is charged tokens in proportion to its cost. Take a bucket of 1,000 tokens refilling at 1,000 a minute. A search costs 1 token and a report costs 100. The customer can then make 1,000 searches a minute, or 10 reports, or a mix, such as 500 searches and 5 reports. The service is protected by the total work it will accept from any one caller, which is what actually runs out.

Getting the costs right is the hard part. Start with measured CPU time or a simple tier you can explain, and keep the table small. Costs that depend on the request, such as a page size or a date range, can be estimated up front and corrected afterwards by refunding or charging the difference once the real cost is known.

Publish the costs and return the remaining balance in response headers. Clients that can see a report costs 100 will schedule them sensibly.

Keep a separate low cap on concurrent reports as well. Token costs limit work over time, but 10 reports started in the same second still run together.

Sources

Practise it in the Rate limiting algorithms lab, or open this question on its own page.

Q11SeniorDesign the rate limiting for a public API with a free tier and a paid tier, where some endpoints cost far more than others.

Start from what the limit is for. A free tier limit protects the service and nudges people to pay. A paid tier limit is a contract. Those want different algorithms and different failure behaviour.

Key the limit by account or API key, not by address, with a coarser limit by address as a guard against anonymous abuse. Give each tier its own rate and bucket size. A token bucket suits the rate, because paid users can burst and the bucket size is the burst you promise. For a hard monthly quota, count separately and exactly.

Charge by cost, not by count. A bulk export should take many tokens and a lookup one, so that one expensive call cannot hide behind a per-request limit. Keep a lower, separate limit on the costly endpoints.

Return 429 with Retry-After and headers for the limit and remaining allowance. Keep the limiter fast, local where possible, with a shared store for the exact counts. Decide failure modes per limit: open for the protective one, closed for the quota. Add a layer of load shedding behind it, because limits per caller do not stop the sum of many callers from overloading the service.

Naming "token bucket" is the easy part. The reasoning is in why a paid tier wants burst room and a free tier wants a tight rate.

Sources

Practise it in the Rate limiting algorithms lab, or open this question on its own page.

Q12SeniorWhat goes wrong with a rate limiter in production, and how do you design for it?

The limiter is a dependency on the hot path of every request, so it fails in all the ways a dependency does. The counter store can be slow or down. Clocks on different servers can disagree and shift window edges. A few very hot keys can overload one shard of the store. A key space that includes addresses behind a shared gateway can limit thousands of users as if they were one.

Design for each. Put a timeout on the limiter call and decide the fallback: open for protective limits, closed for quotas. Use a local approximate limiter as a backstop when the shared one is unreachable. Take time from the store where it matters, not from the app servers. Shard or add local caching for hot keys. Choose keys to match the thing you want to protect, and be careful with address-based keys.

A limit is also a product surface. Clients will build against it. Changing rates silently breaks them. Publish the limits, return them in headers, and roll changes out gradually, observing the rejected share per limit.

Finally, a limiter does not protect against the sum of many well behaved callers. For that the server needs load shedding on its own state.

Sources

Practise it in the Rate limiting algorithms lab, or open this question on its own page.

Q13SeniorYou must enforce a global limit of 1,000 requests a second per customer across 10 gateway nodes, and a shared counter store on every request is too slow. What are your options?

The simplest local scheme gives each node a tenth, 100 a second. It needs no coordination, and it is wrong whenever the load balancer is uneven. If a customer's traffic lands 300 a second on one node, that node rejects 200 while the other nine sit under their shares. The customer sees rejections at 300 requests a second even though they are far below 1,000.

The next step is to let nodes borrow. Each node holds a local allowance and asks a coordinator for a larger slice when it runs low, in chunks, say 50 tokens at a time. The coordinator hands out the global budget, and the store is hit once per chunk instead of once per request. The limit becomes approximate, off by up to the tokens held locally and unspent. With 10 nodes holding 50 each, the overshoot is bounded by 500 in the worst case, so keep chunks small relative to the limit.

A third option is to make the balancing exact by routing each customer to one node by hashing their key. The counter is local and exact. The price is that a node failure or rebalance resets or splits counts, and a very large customer can overload their node.

Whichever you choose, state the error you accept and what happens when the coordinator is unreachable. Falling back to the even split is a sensible degraded mode.

Sources

Practise it in the Rate limiting algorithms lab, or open this question on its own page.

Load shedding and backpressure

13 questions · Read the lesson

Q1JuniorWhat is backpressure? Give two examples of how it shows up.

Backpressure is a signal from a consumer that is falling behind to the producer that feeds it, telling it to slow down. It lets the slow part of a pipeline set the pace, instead of letting work pile up in front of it.

It shows up in several forms. A bounded buffer that blocks the writer when full is one. A server that returns 429 or 503 with a Retry-After header is another. In a streaming library the consumer asks the producer for a specific number of items and the producer sends no more. Network transport does the same thing with a receive window that limits how much unacknowledged data a sender may have in flight.

The opposite is an unbounded buffer, which hides the problem until memory or latency runs out.

Dropping at the point of overload helps only the server. Backpressure helps the whole pipeline once the signal reaches the source of the work and makes it slow down.

Sources

Practise it in the Load shedding and backpressure lab, or open this question on its own page.

Q2JuniorA queue between your web tier and a worker pool keeps filling up during traffic spikes. A teammate suggests raising its limit from 1,000 to 100,000 so nothing is ever dropped. What is wrong with that?

A bigger queue does not make the workers faster. It only lets more work wait. Suppose the workers finish 100 jobs a second. A full queue of 1,000 means a wait of 10 seconds. A full queue of 100,000 means a wait of 1,000 seconds, more than 16 minutes. Nobody waits that long, so the work would be finished for callers who have left, or finished so late that it is worthless.

The drop at 1,000 was doing a useful job. It told the sender early that the system was full, while the sender could still react.

The sensible size comes from the delay you can tolerate. If a job is useless after 5 seconds and workers do 100 a second, the queue should hold well under 500 jobs. If a spike is short, a modest buffer absorbs it. If the spike is long, a buffer only postpones the failure, and the answer is to shed, slow the senders or add workers.

Large, always-full buffers have a name in networking, bufferbloat, and the cure there is the same: control how long things wait, not how many.

Sources

Practise it in the Load shedding and backpressure lab, or open this question on its own page.

Q3JuniorWhat is the difference between throughput and goodput, and why can goodput collapse when throughput does not?

Throughput is how many requests the system finishes per unit of time. Goodput is how many of them finish in time to be useful, for example before the client timed out.

Below capacity they are equal. Above capacity with an unbounded queue they diverge. The queue grows, so each request waits longer. Once the wait passes the client timeout, every request a worker picks up has already been abandoned. The worker finishes it anyway, so throughput stays at capacity and the server looks busy and healthy. But no one receives the answers, so goodput falls toward zero.

This is a form of livelock: the system does work all the time and delivers nothing. It was described for network stacks long ago, where a machine spent all its time on interrupts and delivered no packets.

On a dashboard the signs are full CPU, flat throughput, rising latency and falling client success.

Sources

Practise it in the Load shedding and backpressure lab, or open this question on its own page.

Q4JuniorWhat is load shedding, and why is rejecting a request early better than queueing it?

Load shedding means refusing or dropping some requests on purpose when demand is above capacity, so that the ones you accept still finish in time.

A queue turns excess load into delay. Each request waits behind all the ones before it, and past a point the wait is longer than the caller is willing to stay. The server then spends its time finishing requests that nobody is waiting for. It is busy and useful to no one.

Rejecting early does three things. The caller learns at once and can back off or try elsewhere. The server spends almost nothing on the rejected request. And the requests it did accept are not delayed by a long queue.

What gets shed is a policy choice: the newest requests, the least important ones, or those that can no longer meet their deadline. Shedding does not create capacity. It only chooses how gracefully you fail.

Sources

Practise it in the Load shedding and backpressure lab, or open this question on its own page.

Q5MidWhy might you limit the number of requests in flight instead of the request rate, and how does latency change what that limit means?

Rate says how many requests arrive per second. It says nothing about how long each one occupies the server. Requests in flight is what actually uses threads, memory and connections, and it is tied to rate and latency by Little's law: in flight equals arrival rate times time in the system.

Take a service with 20 workers and a 100 ms response time. It can sustain 20 / 0.1 = 200 requests a second. If a dependency slows and responses take 500 ms, the same 20 workers sustain only 40 a second. A rate limit of 200 a second would still admit 200, and 160 of them would pile up. A limit of 20 in flight stays correct in both cases: it admits what the workers can hold and refuses the rest, whatever the latency.

So a concurrency limit adapts by itself as the service slows. Requests above the limit are rejected at once, or held in a short queue, which gives you the bounded queue behaviour with little tuning.

The cost is that picking 20 still needs thought, since it depends on how much parallelism the machine really has. Some systems adjust the limit automatically, raising it while latency is steady and lowering it when latency climbs.

Sources

Practise it in the Load shedding and backpressure lab, or open this question on its own page.

Q6MidWhat is deadline-aware dropping, and what does it need from the rest of the system?

When a worker takes the next request from the queue, the server checks whether the request can still finish before its caller gives up. If the time left is less than the expected service time, the server drops it without doing the work. Dropping is nearly free, so the worker moves straight on to a request that can still succeed.

It needs to know the deadline. The client has to send it, as a timeout or an absolute time, and every hop has to pass on the time that is left rather than start a fresh timeout. Without that, a service deep in a call chain keeps working on requests that the first caller dropped long ago.

It also needs a rough estimate of service time. If the estimate is too low, some requests start and finish late. If too high, some that could have made it are dropped.

The advantage over a fixed queue bound is that there is no size to tune. The deadline of each request decides. The cost is the plumbing for deadlines, and the risk that a deadline is not the real one.

Sources

Practise it in the Load shedding and backpressure lab, or open this question on its own page.

Q7MidDuring an overload, a service starts shedding load. Soon the load balancer marks several instances unhealthy and pulls them out, and the rest fall over. What happened, and how do you prevent it?

The health check is an ordinary request, and it was shed or delayed along with the rest. The load balancer read slow or rejected checks as dead instances and removed them. The same traffic now landed on fewer machines, so each was more overloaded, their checks failed too, and the pool shrank in a spiral until little was left.

The mistake is letting a health check measure load. It should answer a narrow question, whether the process is alive and able to serve, and not whether it is busy. Keep it cheap and answered from memory, with no database call. Give it the highest priority, or serve it on a separate port or thread pool, so it is never queued behind real work.

Also put limits on how much the balancer may remove. Many balancers have a panic threshold: if more than some share of the pool is unhealthy, they ignore health status and send to everyone. That turns a total outage into a degraded service.

A slow instance that is truly overloaded should shed load and stay in the pool. It is better to serve 60 percent of requests from ten machines than 100 percent from four before they collapse.

Sources

Practise it in the Load shedding and backpressure lab, or open this question on its own page.

Q8MidHow do you choose the size of a bounded request queue?

Work backwards from the timeout. A request that joins a queue of N on a server that finishes C requests per second waits about N divided by C seconds before it starts. That wait must be comfortably less than the time the caller will stay, minus the service time itself. This is Little's law at work: the number waiting equals the arrival rate times the wait.

For example, if workers finish 20 a second and callers give up after 2 seconds, a queue of 100 means a wait of 5 seconds, so everything that reaches a worker is already late. The queue should be a fraction of 40, with margin for service time.

The size is fragile. It depends on speed and timeout, and both change. A slow downstream, a cold cache or a noisy neighbour lowers C, and the same N now means a longer wait. So many systems bound the delay and not the length, by dropping requests that have waited too long, or they set the queue small, only enough to absorb a short burst.

So derive the bound from the timeout, and treat the count as a safety net and not as the control.

Sources

Practise it in the Load shedding and backpressure lab, or open this question on its own page.

Q9SeniorA product page makes a personalised recommendation call, a reviews call and an inventory call. Under load the recommendation service is the slowest. Rather than failing the page, how would you degrade it?

Sort the page by what it cannot do without. Inventory decides whether the buy button works, so it is essential. Reviews and recommendations enrich the page and can be missing.

Under pressure, give the optional calls less. Give them short timeouts that fit inside the page's budget, so a slow recommendation cannot hold the page past its deadline. When the call fails or times out, fill the slot with something cheap, such as a cached list of popular items, or leave the slot out. The user sees a plainer page, quickly, rather than an error or a spinner.

Make the degraded mode a deliberate state and not an accident. A flag or a load signal can switch recommendations to the cached version before they time out, so you stop sending load to the struggling service at all. Mark those calls low criticality, so the recommendation service itself sheds them first and keeps capacity for essential callers.

Test it. Degraded paths are rarely exercised, and the first time they run is usually during an incident. Run them in staging and occasionally in production.

Watch for the cost: a cached fallback can be stale or unfit for that user, so decide how wrong it is allowed to be.

Sources

Practise it in the Load shedding and backpressure lab, or open this question on its own page.

Q10SeniorYou are designing a pipeline where a fast producer feeds a slow consumer. Compare dropping, blocking, credits and pull-based flow control.

Dropping discards items when the buffer is full. It never slows the producer and keeps latency low, and it loses data. It suits telemetry or video frames and not payments.

Blocking makes the producer wait when the buffer is full. Nothing is lost and the producer slows to the consumer's pace. The risk is that a stall travels upstream and ties up threads, and a cycle of blocked components can deadlock.

Credit-based flow control has the consumer tell the producer how many items it can accept, and the producer sends only that many. The producer never overruns the consumer, and the signal is explicit and cheap to send. It needs a channel for credits, and its latency matters, because a slow credit return leaves the producer idle.

Pull-based flow control has the consumer ask for the next items when it is ready. It gives the consumer full control. Streaming libraries often expose it as a request for a number of items, so it is credits in another form.

Pick by what loss and delay cost for this data. Whichever you choose, the signal has to reach the true source of the work, or the slack just moves somewhere else.

Sources

Practise it in the Load shedding and backpressure lab, or open this question on its own page.

Q11SeniorWhen would you serve a queue newest first, and what does it cost?

Under overload a first-in first-out queue serves the oldest requests first, which are the ones most likely to have been abandoned. The newest request has waited least, so its caller is the most likely to still be there. Serving the newest first, which is LIFO, means the work that gets done is work somebody wants. An adaptive version uses FIFO while the queue is short and switches to LIFO when it gets long, so ordinary operation is still fair.

The cost is fairness and consistency. Old requests sit at the bottom and may never be served, so some callers get nothing while others get fast answers. If the same callers keep landing at the bottom, they lose every time. Requests that depend on each other can be served out of order. It also needs something to clear out the requests that have expired, or the pile grows without limit.

It fits interactive requests where a stale answer is worthless, such as a page load. It is a poor fit where order matters, such as a sequence of writes from one user.

Pair it with a cap on waiting time, so the starved requests are discarded cleanly instead of piling up.

Sources

Practise it in the Load shedding and backpressure lab, or open this question on its own page.

Q12SeniorA service handles checkout, search and background prefetch on the same fleet, and it is overloaded. How do you decide what to shed?

Shed by importance, not at random. Give each request a criticality when it enters the system, and carry it with the request through every hop. Under overload, the service first rejects the least critical class, then the next, and keeps the most critical class until the very end.

Make the signal that triggers shedding something that tracks the real problem. Queue delay, concurrency in flight, or CPU are better than request rate, because requests differ in cost. Take care with a metric that feeds back on itself: if shedding lowers it, shedding stops, load returns and it starts again. Use some hysteresis.

Do it at the cheapest point, which is as early as possible and before expensive work. Let the callers help. If a caller sees many rejections from a backend, it can throttle itself on the client side, so most of the rejected traffic never leaves it.

Plan for the sum of retries too. Rejected clients that retry add load, so use Retry-After, backoff, and retry budgets.

Test it the way it fails: replay a load spike in staging and check that checkout survives while prefetch is the first thing to go.

Sources

Practise it in the Load shedding and backpressure lab, or open this question on its own page.

Q13SeniorA request passes through a pipeline of three stages that cost 1 ms, 10 ms and 100 ms of CPU. The pipeline is overloaded. Where should you shed, and why does it matter?

Shed at the first stage, before any work is spent. The reason is arithmetic. A request dropped at stage 3 has already used 1 + 10 = 11 ms of work that gets thrown away. At 1,000 dropped requests a second that is 11 CPU seconds a second of pure waste, enough to saturate more than ten cores. A request dropped at stage 1 wastes nothing.

Look at the costs too. The last stage is by far the most expensive, so it is the real bottleneck, and it should set the admission rate for the whole pipeline. If stage 3 handles 50 a second, there is no point letting more than about 50 through stage 1. The first stage needs to know the last stage's state: through a credit, a queue-delay signal, or a rejection that is passed back up.

Use bounded queues between stages, so a full queue at stage 3 stops work at stage 2 and so on back to the front. That is backpressure moving upstream. Without bounds, the middle queues fill with work that will never finish.

The exception is when only the late stage knows enough to decide, for example because the request's cost or class is not known until it has been parsed. Then do the cheap parse early, and shed as soon as the information exists.

Sources

Practise it in the Load shedding and backpressure lab, or open this question on its own page.

Retries and circuit breakers

14 questions · Read the lesson

Q1JuniorA client makes up to 4 attempts per request. If each attempt fails independently 20 percent of the time, how many attempts does it make per request on average? What if the dependency is fully down?

Count the chance of reaching each attempt. The first always happens. The second happens if the first failed, which is 0.2. The third needs two failures, 0.2 squared, which is 0.04. The fourth needs three, 0.008. The average is 1 + 0.2 + 0.04 + 0.008 = 1.248 attempts. A 20 percent failure rate costs only about 25 percent extra load, and the chance a request still fails after four tries is 0.2 to the fourth power, 0.0016, or 0.16 percent. That is a good trade.

If the dependency is fully down, every attempt fails, and every request makes all 4. The load is four times normal. It is multiplied exactly when the dependency can least afford it.

That is the whole case for a budget or a breaker. The retry limit gives a good return when failures are random and rare, and a terrible one when they are correlated. Independent failures are the assumption behind the first calculation, and an overload is the opposite of independent.

Sources

Practise it in the Retries and circuit breakers lab, or open this question on its own page.

Q2JuniorWhat is exponential backoff, and why is jitter added to it?

Exponential backoff means waiting longer after each failed attempt, usually doubling the wait up to a cap. A client that is failing sends fewer and fewer requests, which gives a struggling dependency room to recover.

On its own it has a weakness. If many clients fail at the same moment, because a server restarted or a connection dropped, they all wait the same time and retry together. The retries arrive in waves, and each wave can be as big as the first.

Jitter adds randomness. With full jitter each wait is a random time between zero and the backoff ceiling, so the clients spread their retries over the whole window. The peak load falls, and the dependency sees a smoother stream.

Jitter spreads the same number of retries over time. It does not reduce the total. To cap the total you need a retry limit, a budget or a circuit breaker.

Sources

Practise it in the Retries and circuit breakers lab, or open this question on its own page.

Q3JuniorWhen is it safe to retry a failed request, and when is it not?

It is safe when repeating the request has the same effect as doing it once. Reads are naturally safe. Writes are safe only if they are idempotent: setting a value to X is, adding 10 to a balance is not.

A request that timed out is the hard case. The client does not know whether the server did the work. If the server did, a retry of a non-idempotent write does it twice, for example by charging a card twice. The usual fix is an idempotency key that the client generates and sends with the request. The server stores the result under the key and returns it for a repeat.

Also look at the error. Retry on failures that may clear up: a timeout, a dropped connection, a 503. Do not retry on errors that will not change, such as a bad request or a failed authorisation.

The unknown outcome after a timeout is the case that bites. Idempotency keys exist for exactly that.

Sources

Practise it in the Retries and circuit breakers lab, or open this question on its own page.

Q4JuniorYour client library's default timeout for calling an internal service is 30 seconds. The service normally answers in 80 ms, and 99 percent of calls finish within 400 ms. Is the default a problem?

Yes. A 30 second timeout is 75 times the 99th percentile. When the service hangs, every caller holds a thread, a connection and its memory for the full 30 seconds. If the caller handles 200 requests a second, that is 6,000 stuck requests within 30 seconds, and the caller runs out of threads and stops answering its own users. The failure of one service has spread to its caller.

Pick the timeout from two things. One is how long the user, or the caller above you, is willing to wait. The other is how the service normally behaves. Something near the 99th or 99.9th percentile, with some margin, such as 500 ms to 1 second here, catches real hangs and rarely cuts off a healthy call.

Do not make it too tight either. A timeout at the median would fail half the calls and trigger retries for work that was about to finish.

Set it explicitly in code. Defaults in libraries are often very long or even infinite, and they were chosen without knowing your service.

Sources

Practise it in the Retries and circuit breakers lab, or open this question on its own page.

Q5MidA service calls a database cluster with 12 replicas. One replica starts timing out on every request. Should the circuit breaker wrap the whole cluster or each replica?

Each replica, or each host, if you can tell them apart. A breaker around the whole cluster sees 1 failure in 12 attempts, about 8 percent. That is below any sensible threshold, so it stays closed. Meanwhile one request in twelve goes to the bad replica and waits out its timeout. Callers see a steady, avoidable tail of errors.

A breaker per replica sees 100 percent failures from the bad host and opens only that breaker. Traffic goes to the other 11, and the bad host receives a probe now and then until it recovers. This is often called outlier detection or ejection.

Limits apply. Do not eject too many at once: if a shared problem makes all 12 look bad, ejecting everything is an outage. Cap the share that can be out, say half. Make sure the remaining replicas can absorb the load, since 11 now carry what 12 did, about 9 percent more each.

A breaker around the whole cluster still has a job. It catches the case where everything is failing, and stops the callers from piling up on it. The two work at different levels.

Sources

Practise it in the Retries and circuit breakers lab, or open this question on its own page.

Q6MidWalk through the states of a circuit breaker and the parameters you would tune.

A breaker has three states. Closed is normal: requests go through and the breaker records outcomes. When too many recent attempts have failed, it opens. In the open state, requests fail immediately without being sent. After a cool-down it becomes half-open, and lets a few probe requests through. If they succeed, it closes. If one fails, it opens again for another cool-down.

The parameters are the failure threshold, as a rate or a count, the minimum number of requests before it decides, the window it looks at, the length of the cool-down, and the number of probes. What counts as a failure also matters: timeouts and 5xx errors usually do, client errors do not.

The breaker protects the dependency from load, and protects the caller from waiting on a service that will not answer. It fails fast, so threads and connections are freed.

The costs are real. Open means failing requests on purpose, so it needs a fallback or a clear error. Too sensitive and a blip opens it. Too slow and the damage is done. A breaker in every process trips and probes on its own schedule.

Sources

Practise it in the Retries and circuit breakers lab, or open this question on its own page.

Q7MidA mobile app places orders over flaky networks, and some customers end up with two identical orders. How would you fix it on the server?

The app times out, does not know whether the order went through, and sends it again. Both copies reach the server and both are accepted. The server cannot tell a duplicate from a second real order, because nothing links them.

Link them. The app makes a unique key once for each order the user submits, before the first attempt, and sends the same key on every retry. On the server, a unique constraint on that key, in the same table or transaction as the order, makes the second insert fail. The server catches that and returns the original order instead of an error.

Care is needed in three places. If two copies arrive at the same moment, the unique constraint makes one lose, and it should return the winner's result. If the key arrives with a different body, refuse it, as that is a client bug. And keep keys long enough to cover the slowest realistic retry, such as a day.

Return the same status for the repeat as for the first call, so the app does not have to know which attempt succeeded. The server should store the response, not only the fact that the key was used.

Keys are not needed where the operation repeats safely already, such as setting an address to a value.

Sources

Practise it in the Retries and circuit breakers lab, or open this question on its own page.

Q8MidWhat is a retry budget, and how is it different from limiting the attempts per request?

A limit on attempts per request caps retries for each request on its own, for example three tries in total. It sounds safe, but when the dependency fails, every request uses all of its attempts, so the load is multiplied by the limit.

A retry budget caps retries across requests. It might allow retries equal to a tenth of the recent requests. One way to build it is a token bucket: each new request adds a fraction of a token, and each retry costs a whole one. When the bucket is empty the client does not retry and the request fails immediately.

The result is that extra load is bounded by that fraction, however badly the dependency fails. During a blip, the budget is enough to retry the few failures. During an outage, it runs out and the client stops adding load.

The budget can sit per process or per client. A per-request limit is still useful for a single request that keeps failing. The usual practice is to use both.

Per-request limits multiply the load by the limit. A budget bounds it at the stated fraction.

Sources

Practise it in the Retries and circuit breakers lab, or open this question on its own page.

Q9MidWhat is a retry storm, and how does one start?

A retry storm is a loop in which retries add load to a dependency that is already struggling, which makes it slower, which causes more timeouts and more retries.

A typical start is a small trigger: a deploy, a cache flush, a brief loss of capacity. A few requests time out. Their clients retry. The dependency now has the original load plus retries. Its queue grows and its answers get later, and soon most attempts time out, each one triggering another. A timed-out request is also usually still in the queue, so the dependency does the work for an answer nobody reads, and then does it again for the retry.

The dangerous part is that it can outlast its trigger. Once the queue is long enough that every answer is late, the system cannot drain, even when the original fault is fixed. That is called a metastable failure.

The fixes break the loop: fewer attempts per request, a retry budget, a circuit breaker, load shedding at the dependency and backoff with jitter. Each one cuts a different link: fewer attempts shrink the multiplier, a budget or breaker caps it, shedding keeps the queue short, and jitter spreads what remains.

Sources

Practise it in the Retries and circuit breakers lab, or open this question on its own page.

Q10SeniorA search request fans out to 50 index shards and the 99th percentile latency is dominated by one slow shard. Someone proposes hedged requests. What do you check before agreeing?

First, why the tail is slow. Hedging helps when slowness is local and temporary: a garbage collection pause, a compaction, a busy neighbour. A second replica is probably fine at that moment. It does not help if the slowness comes from the request itself, such as a query that is heavy everywhere, because the copy is slow too and the load doubles for nothing.

Second, the arithmetic of the cost. If the hedge fires at the 95th percentile of shard latency, about 5 percent of shard calls send a second copy, so about 5 percent more load. Across 50 shards, a page is likely to hedge at least one shard, since the chance that none of 50 passes the 95th percentile is 0.95 to the 50th, about 8 percent. That is fine, as each hedge is cheap, but check the capacity has room for it.

Third, safety. The call must be idempotent, which a search is. Cancel the loser so the work stops. Send the copy to a different replica. And suppress hedges when the system is already loaded, because under overload every request passes the delay and hedging turns into a load multiplier. Put hedges under a budget.

Measure before and after on the real tail, and keep a switch to turn it off.

Sources

Practise it in the Retries and circuit breakers lab, or open this question on its own page.

Q11SeniorA request passes through three services in a chain, and each one retries its call to the next. What is the problem, and how do you fix it?

Retries multiply across layers. If each layer makes up to three attempts, a single failed request at the bottom can produce three attempts from the layer above for each of its three, and so on up the chain. The load on the lowest service, which is usually the one in trouble, grows as the product of the attempts at every level.

The fix is to decide where retries belong. Usually it is one layer, the one nearest the user or the one that knows the operation is safe to repeat. The other layers fail fast and pass the error up. Where a lower layer must retry, it uses a retry budget so the total is capped.

Also pass the deadline down the chain. If the first caller waits 2 seconds, the layers below get the time that is left, not a new timeout each. Otherwise work continues below after the top caller has gone, which wastes capacity.

Return clear signals. A lower layer that is overloaded should say so, with an error that tells the layers above not to retry.

Three layers of three attempts each means 27 attempts at the bottom for one user request.

Sources

Practise it in the Retries and circuit breakers lab, or open this question on its own page.

Q12SeniorAn outage's root cause was fixed an hour ago, but clients are still seeing mostly errors and the dependency looks overloaded. How do you diagnose it and get out?

This pattern is a metastable failure: the trigger is gone, and a feedback loop keeps the system in overload. The usual sustaining loops are retries, queues full of requests that clients abandoned, and caches that stay cold so that every request goes to the backend.

Diagnose it from the shape of the load. Compare attempts at the dependency with new requests. A ratio well above one points to retries. Check queue delay against the client timeout, and the share of work the dependency finishes after the client has left. If delay is above the timeout, the dependency is working for nobody.

To get out, you must reduce load below capacity for long enough to drain the backlog. Shed or reject traffic at the edge, or open breakers, disable retries or tighten budgets, and restart or purge the dependency's queue so that abandoned work is dropped. Then restore traffic gradually and watch whether it holds.

To prevent it, bound queues by delay, drop by deadline, cap retries with budgets and breakers, and test overload behaviour before it happens.

The order matters: cut load first, let the backlog drain, then restore traffic. Restoring everything at once re-triggers the loop.

Sources

Practise it in the Retries and circuit breakers lab, or open this question on its own page.

Q13SeniorDesign the client policy for two calls to the same slow dependency, a payment authorisation and a product search. How do the policies differ?

Start from what a failure and a duplicate each cost. A duplicate payment is expensive and a failed search is a nuisance, so the two get different policies.

For the payment, retries must be safe. Send an idempotency key so a repeat returns the first result. Use a longer timeout, since abandoning a call that was about to succeed leaves the outcome unknown, and a small attempt limit with backoff and jitter. If the outcome is still unknown, treat it as unknown: check the status before trying a different action. A breaker is useful, but its fallback must be an honest error and not a guess.

For the search, speed matters more than certainty. Use a short timeout and few or no retries. A retry that takes longer than the user will wait is useless. A fallback such as a cached or simplified result is good. A hedged request, which sends a second copy after a short delay and takes the first answer, can cut the tail, but only if the extra load is capped.

For both, share a retry budget and a breaker per dependency, pass deadlines down, and emit metrics on attempts per request, so a rise in amplification is visible before it becomes an outage.

Sources

Practise it in the Retries and circuit breakers lab, or open this question on its own page.

Q14SeniorA gateway holds 50,000 long-lived client connections. You restart it, and every client reconnects at once. The gateway falls over again. Design the recovery so it does not happen.

The clients all noticed the drop at the same moment and all retried at the same moment. 50,000 connection attempts in a second, each needing a handshake and authentication, are far above what the gateway handles in steady state. It fails, they all retry again, and the wave repeats.

Fix it in the client first. Reconnect with exponential backoff and full jitter, so the attempts spread over a window. With a base of 1 second and a cap of 60, the first retry is uniform over 0 to 1 second, the second over 0 to 2, and so on. After a few failures the clients are spread across a minute, and the arrival rate falls from 50,000 a second to under 1,000 a second.

Then protect the server. Cap the rate of new connections it accepts and reject the rest quickly with a hint to retry later. Do not do the expensive work, such as loading user state, until after the connection is admitted. Bring instances back gradually, and keep warm capacity so one restart does not land on a cold fleet.

For planned restarts, drain: tell clients to reconnect at random times over the next several minutes before the gateway goes down.

Add a random offset to any timer shared across clients, such as a token refresh. Shared timers produce the same herd every hour.

Sources

Practise it in the Retries and circuit breakers lab, or open this question on its own page.

Failure detection

13 questions · Read the lesson

Q1JuniorYour process runs a background thread that sends heartbeats, but a deadlock has frozen every request handler. The monitor says the node is healthy. What is wrong, and how do you fix it?

The heartbeat proves only that the thread sending it is running. It says nothing about whether the node does its job. Here the process is alive at the operating system level and useless at the application level, and the monitor is reading the wrong signal.

The fix is to make the health signal depend on real work. A deep health check exercises the request path: it takes a handler, touches the database connection and returns a result within a deadline. A weaker version has the heartbeat thread read a counter of completed requests or a timestamp that the handlers update, and stop reporting if the value has not moved.

Each choice has a cost. A deep check can fail because a dependency is slow, which makes the node look dead when the fault is elsewhere, and it adds load. A progress counter is cheap, but a node with no traffic looks stalled. Pick the check that matches what you will do when it fails. A load balancer can pull a stuck node cheaply and quickly. A database failover is expensive and deserves a stronger signal.

Sources

Practise it in the Failure detection lab, or open this question on its own page.

Q2JuniorA health check marks a server dead and traffic is moved away, but the server was only slow. What goes wrong, and how do systems limit the damage?

The server was still working. If it was a leader, a lock holder or a primary, the system may now have two of them for a while. Moved traffic can overload the remaining servers, and the slow server may come back and keep acting on stale decisions.

Systems limit the damage in a few ways. Decisions made on a suspicion are made revocable or versioned, so a returning node can be fenced off. Terms, epochs or tokens let everyone tell old authority from new. Failover is rate limited so one flapping check cannot churn the cluster.

Do not try to fix this in the detector. Making it slower only trades false alarms for slow detection. The fix is in what the system does with a suspicion.

Sources

Practise it in the Failure detection lab, or open this question on its own page.

Q3JuniorA service sends a heartbeat every 1 second and the monitor declares it dead after 1.5 seconds of silence. Why is this configuration fragile, and what would you change?

One late or lost heartbeat is enough to cross the line. If a packet is dropped, the next one arrives 2 seconds after the previous, which is already past 1.5 seconds, so a healthy node gets declared dead because of a single bad packet.

The timeout should span several heartbeat intervals so that it takes a run of missed messages, not one, to cause a verdict. Three to five intervals is a common starting point. With a 1 second interval that suggests a timeout around 3 to 5 seconds, or an interval of 300 to 500 ms if you want to keep 1.5 seconds.

Shortening the interval is not free, since heartbeats cost traffic and CPU on both sides, and a short interval does nothing for a node that is paused rather than slow. The detection time after a crash is still about the timeout, so the interval is a lever on how much slack a timeout has, not on how fast you see real failures.

Sources

Practise it in the Failure detection lab, or open this question on its own page.

Q4JuniorExplain how a heartbeat with a fixed timeout detects failures, and what the timeout trades off.

The monitored node sends a small message at a fixed interval. The monitor records when the last one arrived. If the silence since then exceeds the timeout, the monitor marks the node as suspected. A later heartbeat clears the suspicion.

The timeout sets two numbers at once. Detection time for a real crash is a little under the timeout, because part of it had already run down between the last heartbeat and the crash. The false alarm rate is how often a live node goes quiet for longer than the timeout, because of network delay or a pause.

Lengthening the timeout lowers false alarms and raises detection time. Shortening it does the reverse. There is no setting that improves both, so the right value depends on what a false alarm costs compared with a slow detection.

Sources

Practise it in the Failure detection lab, or open this question on its own page.

Q5JuniorWhy can a node in a distributed system not reliably tell whether another node has crashed or is just slow?

All it can observe is silence. A crashed node sends nothing. A node that is alive but stuck in a garbage collection pause, swapped out, or behind a congested link also sends nothing for a while. From the outside the two look the same until the silence ends, and only a crash never ends it.

In a network with no upper bound on delay, no amount of waiting proves a crash. Any timeout you pick is a bet: wait longer and you miss real failures for longer, wait less and you declare live nodes dead.

So the real design question is what happens after a suspicion. Failing over, re-electing a leader and reassigning a lock must all stay correct if the suspected node was alive and comes back.

Sources

Practise it in the Failure detection lab, or open this question on its own page.

Q6MidWhat does it mean for a failure detector to be "unreliable but useful"? How weak can a detector be and still let a group reach consensus?

Chandra and Toueg described detectors by two properties. Completeness says every crashed node is eventually suspected by the live ones. Accuracy says live nodes are not wrongly suspected, in various strengths. A perfect detector has both, and cannot be built in an asynchronous system.

The useful result is that consensus does not need a perfect detector. It is enough that eventually, after some unknown time, there is at least one live node that nobody wrongly suspects any more. Before that point the protocol may stall, but it never produces a wrong answer.

In practice this is why protocols like Raft separate safety from liveness. Timeouts and heartbeats only affect when progress happens. Terms and majorities make sure that whatever happens is consistent.

Sources

Practise it in the Failure detection lab, or open this question on its own page.

Q7MidA node on a congested link is marked dead, comes back, and is marked dead again every few seconds. Each transition triggers a rebalance. What do you do?

The detector is doing what it was asked to do. The trouble is that the reaction is wired directly to every change of state, so a marginal link produces a stream of rebalances, each of which moves data and adds load to a network that is already struggling.

Add asymmetry between going down and coming back. Declare a node dead after the usual timeout, but readmit it only after it has been healthy for a longer period, say a minute or several consecutive good intervals. This is hysteresis. Keep a count of recent transitions per node, and once it passes a threshold, quarantine the node instead of rebalancing again, and raise an alert for a person to look at.

Also cap the rate of reactions cluster-wide so that one bad node cannot churn the others. And consider separating the two states in the data path: a node that is suspected can stop receiving new work immediately, which is cheap and reversible, while moving its data only happens after it has been gone for a long time. Fast cheap reactions can follow the detector closely. Slow expensive ones should not.

Sources

Practise it in the Failure detection lab, or open this question on its own page.

Q8MidYour service runs on a garbage collected runtime with occasional pauses of a second or more. How should that change the way you set up failure detection and the actions taken on it?

Any timeout shorter than the longest pause will produce false alarms. Any timeout longer than it will take at least that long to see a real crash. So first measure the pause distribution rather than guess, and treat the tail of it as the floor for any timeout.

Then make the actions safe under false alarms. A node that comes back from a pause must not be allowed to act on authority it lost. That means fencing tokens for storage, terms for leaders, and leases that the holder checks before every action, with a safety margin for its own clock.

Also consider heartbeats that are sent from a thread the collector does not stop, or from a sidecar process, so that a pause in the application does not look like a dead machine. And reduce the pauses themselves: smaller heaps, a different collector, or moving the hot path off the managed runtime.

Sources

Practise it in the Failure detection lab, or open this question on its own page.

Q9MidYour single health monitor sits in one availability zone. At 3 a.m. it reports every node in another zone as dead. How do you tell a real outage from a problem with the monitor's own view, and what should the system do?

Start with the pattern. Real failures rarely take out a whole zone's nodes at exactly the same moment, while a broken link between the monitor and that zone does. A sudden, perfectly correlated change across many independent nodes points at the observer or the path to it.

To check, ask other observers. Nodes in the zone can report on each other, and probes from a second zone tell you whether the zone is reachable from elsewhere. If the nodes see each other and clients in other zones can reach them, the zone is fine and the monitor is blind.

The system should be built so that the monitor's suspicion alone cannot cause drastic action. A rule such as "if more than 20 percent of the fleet turns suspect at once, freeze automated failover and page a person" turns a bad view into an alert instead of a mass migration. Where an action must change who is the leader, it should go through a quorum of nodes, not a single observer. A lone observer is one vantage point, and it can be the part that is partitioned.

Sources

Practise it in the Failure detection lab, or open this question on its own page.

Q10MidWhat is a phi accrual failure detector, and how does it differ from a fixed timeout?

Instead of a yes or no, it outputs a suspicion level. It keeps a window of recent heartbeat arrival intervals, fits a distribution to them, and reports how unlikely the current silence is, on a logarithmic scale. A phi of 1 means a silence this long happens about one time in ten, phi 2 one in a hundred, and so on.

The application picks a threshold. The useful difference is that the threshold is relative to the network the detector has seen. On a quiet network the same threshold fires after a short silence, on a jittery one after a longer silence. A fixed timeout would need retuning for each.

It is still a guess from silence. A pause longer than anything in the window still looks like a crash, and the first few samples after startup are a poor fit. Phi moves along the same accuracy against speed curve as a fixed timeout. It just picks the point automatically.

Sources

Practise it in the Failure detection lab, or open this question on its own page.

Q11SeniorDesign the failure detection for a cluster of a few hundred nodes. Who monitors whom, how does suspicion spread, and how do you avoid a partition splitting the cluster into two views?

All-to-all heartbeats cost a message per pair per interval, which grows with the square of the cluster. The usual shapes are a central monitor, which is simple but is itself a point of failure and a hot spot, or a gossip style scheme where each node heartbeats a few peers and suspicion is passed along with the gossip, which scales but takes longer for a suspicion to reach everyone.

Whatever the topology, a suspicion is local knowledge. Node A suspecting node B does not mean B is dead, and during a partition both sides will suspect each other. Decisions that need one answer, such as who is the leader or which side keeps serving writes, must not be made from a local suspicion. They go through a quorum: the side that can still reach a majority proceeds, the other side stops.

Two tricks cut false alarms. With indirect probing, a node that misses a heartbeat asks a few others to probe the target before suspecting it. With incarnation numbers, a node that was wrongly suspected refutes the rumour by announcing a newer version of itself. Finally, keep the detector's output apart from the action: a suspicion goes into a view, and a quorum of views drives membership changes.

Sources

Practise it in the Failure detection lab, or open this question on its own page.

Q12SeniorA fleet of 100 servers runs at 70 percent load and an automated system moves traffic off any server it suspects. A switch fault makes 20 of them look dead. Walk through what happens next and how you would design against it.

The system moves the 20 servers' traffic onto the other 80. Total demand is 100 x 70 = 7,000 units, so each survivor now carries 7,000 / 80 = 87.5 percent. That is a 25 percent rise in load on every healthy machine, in the middle of a network fault.

Higher load means slower responses, and the heartbeats and health checks share those machines. Latency climbs, a few more servers miss their deadlines, the detector suspects them, their traffic moves, and the load on the remaining servers rises again. The loop feeds itself, and a fault that started with 20 percent of capacity can become an outage of all of it.

The design has to bound the reaction. Cap the number of servers that may be drained at once and cap the share of capacity. Treat a large correlated burst of suspicions as a sign that the observer or network is at fault, and freeze instead of acting. Keep headroom: at 70 percent, losing 20 percent of servers is survivable only if the rest do not tip over, so decide the headroom on purpose from the largest failure you intend to survive. Drain gradually, and shed low-priority work before overloading the survivors. Test it by injecting a correlated suspicion burst in staging and watching the load curve.

Sources

Practise it in the Failure detection lab, or open this question on its own page.

Q13SeniorYou are tuning the failure detector for a replicated database. Walk through how you would choose between fast detection and few false alarms, and what measurements you would want first.

Start from costs, not from the detector. Ask what one false alarm costs: a failover with a few seconds of unavailability, a cache flush, a leader election that aborts in-flight writes. Then ask what one second of undetected failure costs: requests timing out, replication lag, a stale primary serving reads.

Measure the inputs. Collect heartbeat interval distributions per link over days, including the tail, and record every pause event with its length. The 99.9th percentile of silence from a live node is the floor for a fixed timeout, and anything below it will fire routinely.

Then pick a point on the curve and make it explicit. If false alarms are expensive, use a long timeout or a high phi threshold and accept slow detection, and move the fast path elsewhere, for example clients retrying against another replica. If detection must be fast, invest in making the reactions cheap and reversible. In the review, state the number of expected false alarms per day and the expected detection time, and have the simulator or production data back them.

Sources

Practise it in the Failure detection lab, or open this question on its own page.

Raft and consensus

13 questions · Read the lesson

Q1JuniorWhy do Raft clusters usually have three or five nodes? What would you gain or lose with four or six?

A cluster of n nodes needs a majority of floor(n/2) + 1 to make progress. Three nodes need 2 and tolerate 1 failure. Four nodes need 3 and still tolerate only 1. Five need 3 and tolerate 2. Six need 4 and tolerate 2.

So going from three to four adds a machine and gains nothing in fault tolerance, while every commit now has to reach three nodes instead of two. The same holds from five to six. Even sizes pay for hardware and latency without buying a failure.

Even sizes have a further drawback: a clean split. A four-node cluster cut into two and two has no side with a majority, so the whole cluster stops. A five-node cluster cut two and three always has one live side.

Three is common for small deployments, and five is used when the cluster must survive one node being down for maintenance while another fails. Beyond five or seven, each commit waits on more replicas and the leader sends more messages, so larger groups buy tolerance at a steady cost in latency.

Sources

Practise it in the Raft and consensus lab, or open this question on its own page.

Q2JuniorWhy does Raft need a majority of nodes to elect a leader and to commit an entry? What happens with three nodes if one dies, and if two die?

Any two majorities of the same set overlap in at least one node. That overlap is the whole trick. If an entry is on a majority, then any future majority that elects a leader includes a node that has the entry, and the election restriction stops a candidate without it from winning. So a committed entry is never lost.

With three nodes a majority is two. Lose one node and the other two can still elect and commit, so the cluster keeps working. Lose two and the last node cannot form a majority. It keeps raising its term and asking for votes, but it will never become leader and nothing commits until a second node returns.

The cluster does not drift into a wrong answer in that state. It stops. Raft chooses to be unavailable rather than inconsistent.

Sources

Practise it in the Raft and consensus lab, or open this question on its own page.

Q3JuniorWhat are the three roles in Raft, and what is a term for?

A node is a follower, a candidate or a leader. Followers are passive: they answer requests from leaders and candidates and otherwise wait. A follower that hears nothing for an election timeout becomes a candidate and asks for votes. A candidate that gets a majority becomes the leader, and the leader handles all client writes and sends heartbeats.

A term is a counter that goes up with every election. Each term has at most one leader. Every message carries the sender's term. A node that sees a higher term than its own adopts it and steps down to follower, which is how an old leader learns it has been replaced, and how stale messages from an earlier term are ignored.

Terms are the cluster's logical clock. They are what keeps two leaders from acting at once.

Sources

Practise it in the Raft and consensus lab, or open this question on its own page.

Q4JuniorA client sends a write to a three-node Raft cluster. Describe what happens from the request until the client gets its answer, and at which moment it is safe to say the write is durable.

The client talks to the leader. If it reaches a follower, the follower redirects it. The leader appends the command to its own log as a new entry with the current term and the next index, and writes it to disk.

It sends an AppendEntries message with the entry to both followers. Each follower checks that its log matches at the preceding index and term, appends the entry, saves it to disk and replies. As soon as one follower has replied, the entry is stored on two of three nodes, which is a majority. The leader marks it committed, applies it to its state machine and answers the client.

That is the moment it is safe to say the write is durable, and not before. At the time of the answer the entry may sit on only two machines, and that is enough because any future leader must have won votes from a majority, and any majority of three includes one of those two. The followers learn the new commit index from the next heartbeat or AppendEntries and apply the entry then.

Sources

Practise it in the Raft and consensus lab, or open this question on its own page.

Q5MidWhy does a Raft leader only count replicas to commit entries from its own term, even if an entry from an earlier term is on a majority?

Because an entry from an earlier term can be on a majority and still be overwritten. A later leader with a higher-term entry at the same index can win an election without it, because the election restriction compares terms first. Counting replicas of the old entry and committing it would then lose a committed entry when that leader overwrites it.

Raft's rule is that a leader commits an entry from a previous term only indirectly, by committing an entry from its own term after it. Log matching then guarantees everything before that entry on the same nodes, including the old one. The paper's figure of the scenario is the standard thing to sketch here.

In practice a new leader appends a no-op entry in its own term as soon as it is elected. That commits the earlier entries at once instead of waiting for the next client write.

Sources

Practise it in the Raft and consensus lab, or open this question on its own page.

Q6MidA node that was down for a while restarts and immediately runs for election. Can it win and lose committed entries? What stops that?

It can run, but it should not win if its log is behind. A voter grants its vote only to a candidate whose log is at least as up to date as the voter's own. Up to date is decided by the term of the last entry first, and then by the length. Since a committed entry is on a majority, and the candidate needs a majority of votes, at least one voter has the entry and will refuse a candidate that lacks it.

So the stale node loses, adopts the higher term from the responses, and becomes a follower. The leader then repairs its log by stepping back through the follower's entries until the two agree and sending everything after that point.

Restarts matter here too. Raft persists the term, the vote and the log before responding to any message, so a restarted node cannot vote twice in one term or forget entries it acknowledged.

Sources

Practise it in the Raft and consensus lab, or open this question on its own page.

Q7MidWhy are Raft election timeouts randomised, and how should they relate to the heartbeat interval and the network delay?

If every follower used the same timeout, they would all time out together after a leader died, all become candidates for the same term, and split the vote. Nobody would get a majority, they would all time out again at the same moment, and the cluster could loop. Drawing each timeout at random from a range means one node usually fires first, wins before the others time out, and its heartbeats stop them.

The ordering is heartbeat interval, well below election timeout, well below the typical time between failures. Heartbeats must arrive several times per election timeout so that normal jitter does not trigger elections. The election timeout, and especially the width of its random range, must be large compared with the message delay, so that a candidate's votes come back before a second node times out.

When the range is tight relative to delay, split votes become common. Each adds a full timeout of leaderless time. So the timeout is a tradeoff too: longer means fewer split votes and more time without a leader after a crash.

Sources

Practise it in the Raft and consensus lab, or open this question on its own page.

Q8MidA new leader has ten log entries. A follower has seven, and its entries 6 and 7 are from an older term and differ from the leader's. How does the leader bring the follower into line, and why is it safe to delete the follower's entries?

The leader starts with a guess that the follower is current, so it sends the entry after its own last one and names the entry before as the anchor, with that entry's index and term. The follower has no entry at index 10, so it rejects. The leader lowers its guess for that follower by one and tries again, through anchors 9, 8, 7 and 6, each rejected because the follower either has no entry there or holds one with a different term. At anchor 5 the index and term agree, so the follower accepts.

On accepting, the follower deletes everything after index 5 and appends the leader's entries 6 to 10. That is five rejections and a success.

The deleted entries are safe to drop because they were never committed. A committed entry is on a majority, and the election restriction would have stopped a leader without it from winning, so the leader would hold it. Whatever the follower has that the leader lacks must therefore be uncommitted. For long gaps, the follower can return the conflicting term and the first index of that term, which lets the leader skip back a whole term at a time.

Sources

Practise it in the Raft and consensus lab, or open this question on its own page.

Q9MidYou run a three-server Raft cluster and want to grow it to five. Why is it dangerous to push the new five-server configuration to every server at once, and what are the safe alternatives?

The servers will not all switch at the same instant. Suppose two servers still use the old configuration and three have the new one. In the old view, two of three is a majority, so the pair can elect a leader. In the new view, three of five is a majority, so the other group can elect a different leader, possibly in the same term. The two majorities share no server, so two leaders can commit different entries.

Raft's original answer is joint consensus. First the cluster moves to a combined configuration, where every election and commit needs a majority of the old set and a majority of the new set. Once that entry is committed, the leader writes the new configuration alone. At no point can either side decide on its own.

The simpler approach, described in Ongaro's dissertation, changes one server at a time. Going from 3 to 4, a majority of the old set is 2 and of the new set is 3, and 2 + 3 > 4, so any two majorities overlap. Five servers means two such steps. New servers should also join as non-voting members first and be counted only after they have caught up on the log, so that an empty newcomer cannot stall commits.

Sources

Practise it in the Raft and consensus lab, or open this question on its own page.

Q10SeniorA Raft follower acknowledges an entry, then the machine loses power and comes back with a log missing its last few entries because the disk write was only in a cache. Can this break safety? How do you design against it?

Yes. Raft's safety argument assumes that a node never forgets what it acknowledged. Take three servers. The leader replicates an entry to S2, S2 acknowledges, and the leader commits it on {S1, S2}. S2 loses power and restarts without the entry. Meanwhile S1 is down. S3 never saw the entry. S2 and S3 now form a majority: S3 asks for a vote, and S2, whose log looks equal to S3's, grants it. S3 becomes leader and the committed entry is gone.

The defence is to treat persistence as part of the protocol. A server must flush its term, its vote and the new log entries to stable storage, and confirm the flush, before replying to the leader or granting a vote. That means an fsync or an equivalent, not just a write into the page cache, and it is a large part of the cost of each commit. Batching entries and grouping many requests under one flush recovers throughput.

Also assume the storage can be wrong. Use disks with power-loss protection, checksum log records so that torn writes are detected, and on a failed check treat the node as new: wipe it and rejoin as an empty member, not as a voter holding a corrupt log.

Sources

Practise it in the Raft and consensus lab, or open this question on its own page.

Q11SeniorThe FLP result says consensus cannot be guaranteed to terminate in an asynchronous system with one crash. Raft and Paxos are used everywhere. How do they get around it?

They do not get around it. They give up the guarantee the theorem forbids, which is termination, and keep the one it allows, which is safety. Raft never produces two leaders in a term or two different committed entries at one index, no matter how the network behaves. What it cannot promise is that an election ever finishes.

What makes elections finish in practice is timing assumptions the proof does not make. Randomised timeouts make it unlikely that candidates keep colliding, and real networks are mostly synchronous, with bounded delays most of the time. The partially synchronous model captures this: after some unknown stabilisation time, delays are bounded, and progress follows.

The link to failure detection is direct. The timeout that drives elections is an unreliable failure detector, and FLP says it cannot be made reliable. Raft is built so that this unreliability only ever costs availability, never correctness. Paxos makes the same split: the acceptors' promise and accept rules are safe on their own, and the leader election that makes it live is a separate, timing-dependent concern.

Sources

Practise it in the Raft and consensus lab, or open this question on its own page.

Q12SeniorA five node Raft cluster is split so the leader is on a side with one other node. Describe what each side does, what clients see, and what happens when the partition heals.

The old leader keeps accepting client writes and appends them to its log, because nothing tells it to stop. But it can only replicate them to one follower, which is two of five. The commit index never moves, so those clients wait for acknowledgements that never come, or time out. Reads served by that leader are stale from now on unless it checks a majority before serving them.

The three node side stops hearing heartbeats, times out, and elects a leader in a higher term. That leader commits new entries, so this side is the real cluster. Clients that reach it make progress.

On heal, the old leader receives a message with the higher term and steps down. The new leader's heartbeat fails the consistency check at the point where the logs diverge, steps back, and the stale entries are deleted and replaced. The writes the minority leader accepted are gone, which is correct because they were never acknowledged as committed. Two things follow for clients. A write is only durable once acknowledged, and a leader that must not return stale data cannot serve reads from local state alone.

Sources

Practise it in the Raft and consensus lab, or open this question on its own page.

Q13SeniorA Raft leader answers a read from its local state. Can the answer be stale, and what does it take to serve a linearizable read?

Yes. A leader that has been cut off from the majority does not know it until it hears a higher term. In that window it will answer reads from a log that the real cluster has moved past. Serving reads locally trades correctness for latency.

To make a read linearizable the leader has to confirm it is still the leader at the time of the read. The direct way is to exchange a round of heartbeats with a majority before answering. The cheaper way is a lease: if the leader heard from a majority within the last election timeout, less a margin, then no one else can have won in the meantime, it can answer without a new round, with a margin for clock drift between nodes.

The leader must also have committed at least one entry in its current term before serving reads, so that it knows where the committed prefix ends. A new leader does this with a no-op. Followers can serve linearizable reads too. They ask the leader for its current commit index and wait until they have applied up to it.

Sources

Practise it in the Raft and consensus lab, or open this question on its own page.

Locks, leases and fencing

14 questions · Read the lesson

Q1JuniorWhat is a fencing token, and where does it have to be checked?

A fencing token is a number the lock service issues with every grant, and it goes up every time. A client sends the token with each write it makes while holding the lock. Storage keeps the highest token it has seen and rejects any write with a lower one.

A stale holder carries a token from before the lock was reassigned. By the time its late write arrives, storage has seen the newer holder's higher token, so the write is rejected. The holder learns it lost the lock from the rejection.

The check has to be at storage, or wherever the protected resource lives. Checking in the client is not enough, because a stalled client checks and then stalls. The resource must be able to say no on its own.

Sources

Practise it in the Locks, leases and fencing lab, or open this question on its own page.

Q2JuniorA worker holds a 30-second lease and renews it every 10 seconds. Why renew so early instead of just before the lease ends?

A renewal is a network call, and it can be slow, lost or retried. If the worker waits until 29 seconds, a single dropped packet means it loses the lease before it can try again.

Renewing at one third of the lease leaves room for two failed attempts. Renewal at 10 seconds that fails can be retried at 15 and 20, and the lease does not end until 30. The rule of thumb is to renew at between a third and a half of the lease length, and to retry quickly after a failure.

There is a limit to what early renewal protects. If the worker is paused for 40 seconds, it renews nothing, and the lease expires however carefully it was timed. What it can do is stop work as soon as it fails to renew. A worker that cannot reach the lock service for 20 seconds should assume it may have lost the lease, stop starting new protected operations, and re-acquire the lock if it wants to continue, rather than assuming everything is fine.

Sources

Practise it in the Locks, leases and fencing lab, or open this question on its own page.

Q3JuniorDescribe a sequence of events in which a client that correctly acquired a lock still writes data it should not have.

The client acquires a lease on the lock and starts its work. Before it writes, it stalls: a garbage collection pause, a swapped out page, a frozen virtual machine, or a slow disk. The lease expires at the lock service while the client is stalled. The service hands the lock to a second client, which does its work and writes.

The first client wakes up. From its point of view no time has passed. It sends the write it had prepared. Storage has no idea the lease is gone, so it accepts the write, and the first client's stale data lands on top of the second client's.

Every component did its job. The lock service expired the lease on time, the second client held a valid lock, and the first client was never told it lost anything. The fix has to be somewhere the stale write can be recognised, which is at storage.

Sources

Practise it in the Locks, leases and fencing lab, or open this question on its own page.

Q4JuniorWhat is a lease, and why do distributed locks use leases instead of locks that last until released?

A lease is a lock with an expiry. The holder gets the right to act for a fixed time, after which the right is gone unless it was renewed. A plain lock that lasts until released is a problem the moment the holder crashes: nobody can release it, and everyone waits forever.

With a lease, a crashed holder's lock frees itself when the lease runs out. The cost is a window: a holder that is alive but slow can lose the lease without noticing, and then act as if it still held it.

The trade is lease length. Short leases recover fast from a crash and go stale under short pauses. Long leases survive pauses and make everyone wait after a crash. Both are failure modes. The length chooses between them rather than removing either.

Sources

Practise it in the Locks, leases and fencing lab, or open this question on its own page.

Q5MidA client checks its own clock before each write to make sure its lease is still valid. Why is that not sufficient, and how does clock drift make it worse?

The check happens before the write and the write happens after. Anything between the two, a pause or a slow network hop, can carry the write past the expiry even though the check passed. A check cannot be atomic with an action that happens somewhere else.

Even without a pause, the client's clock is not the lock service's clock. If the client's clock runs slow, it believes the lease has more time than it does. A client that starts its own lease timer when the grant arrives is also already late by the network delay. Both errors push the client to write after the service has moved on.

A careful client subtracts a safety margin that covers its expected drift and delay. That shrinks the window but cannot close it, because the pause can be longer than any margin. The margin is a mitigation. A fencing token is the guarantee.

Sources

Practise it in the Locks, leases and fencing lab, or open this question on its own page.

Q6MidHow should the lock service itself be built so that it does not become the thing that fails? What does a lock service need from consensus?

A lock service on one machine is a single point of failure, and a lock service on several machines that do not agree can hand the same lock to two clients. So the service is usually a small replicated state machine over a consensus protocol: a few nodes that agree on the sequence of grants, releases and expiries.

Consensus gives it one agreed order, so the token counter is unique and increasing across failovers, and a client that talks to any replica sees the same holder. The service tolerates a minority of its own nodes failing, and the lease model covers clients failing.

Operations matter as much as design. The service should be small and boring, because every client depends on it. Sessions with keepalives let it detect dead clients, and clients should be told explicitly when their session expired rather than discovering it on a rejected write. Reads of "who holds the lock" should be served with care, because a stale answer here is exactly the problem fencing exists for.

Sources

Practise it in the Locks, leases and fencing lab, or open this question on its own page.

Q7MidA nightly billing job must run on only one of three scheduler instances. You use a lock with a lease for the election. After a failover, customers are billed twice. What happened, and how do you fix it?

A plausible sequence: instance A takes the lock, starts the job and is paused for longer than the lease, perhaps by a long garbage collection or a frozen VM. The lease expires, B takes the lock and starts the job. A wakes, still believes it is the leader, and continues. For some minutes two instances run the billing loop.

The lock never allowed two holders at the lock service. The problem is that nothing downstream checks who is the current holder. Fix it where the damage happens. Give each charge an idempotency key derived from the customer and the billing period, so a second attempt is detected and ignored. Better still, have the billing store reject writes from an older lock generation by carrying the fencing token through, and recording the highest token seen for the job.

Then add safeguards on the instance: stop the job if a renewal fails, and check the lease between batches. These shrink the window but only the idempotency key and token close it. For a job that moves money, the lock is a correctness lock and should be treated as one.

Sources

Practise it in the Locks, leases and fencing lab, or open this question on its own page.

Q8MidA service computes lease expiry by adding 10 seconds to the current wall-clock time and compares against the clock on every check. An operator corrects the machine's time forward by two minutes. What breaks, and what do you change?

Every lease on that machine expires at once. The stored expiry times were computed from the old time, and after the step they all lie in the past. A lock service that did this would hand every lock to a new client while the old holders are running, so a large number of clients would think they hold the same locks.

A step backward is also harmful. Leases would last two minutes longer than intended, and a crashed holder would block everyone for that long.

The fix is to measure durations with a monotonic clock, one that never jumps and is not adjusted by time synchronisation, and compare elapsed time against the lease length. Wall-clock time is for timestamps people read, not for deadlines. The service should also be told about its own clock changes and treat a big step as a reason to distrust its leases, for example by refusing to grant new ones for a lease length.

A monotonic clock fixes the jump, but not rate differences between machines, so the holder still keeps a safety margin, and the resource still checks a token.

Sources

Practise it in the Locks, leases and fencing lab, or open this question on its own page.

Q9SeniorWhen is it acceptable to use a distributed lock without fencing? How do you decide whether a lock is for efficiency or for correctness?

Ask what happens if two clients hold the lock at once. If the answer is wasted work, such as two workers computing the same report or two nodes warming the same cache, the lock is for efficiency. A rare double execution costs money or time but nothing is corrupted, and a simple lease from a single lock server is fine.

If the answer is corrupted data, a double charge, or a violated invariant, the lock is for correctness. Then every assumption has to hold under pauses, clock drift and partitions, and a lease without fencing does not. The resource must check a token, or the operation must be made idempotent or conditional, and the lock service itself needs consensus.

Teams often start with an efficiency lock and quietly begin relying on it for correctness. Write the intent down next to the lock. In a design review, ask for the token check at the resource as proof that a correctness lock is really one.

Sources

Practise it in the Locks, leases and fencing lab, or open this question on its own page.

Q10SeniorA colleague proposes a lock for payment processing built on five independent in-memory key-value servers. A client sets a key with a time-to-live on each, and counts itself the holder if it succeeds on three within less than the time-to-live. There is no consensus among the servers. Assess it.

The majority count looks like consensus but is not. The servers never talk to each other, and each one decides by its own clock when the key expires. Safety therefore depends on timing: that clocks run at about the right rate, that network delay is small against the time-to-live, and that a client is not paused for long between acquiring and using the lock.

Two sequences break it with no bug involved. A clock on one of the three servers that granted client 1 jumps forward and its key expires early. Client 2 then gets that server plus two others that client 1 did not reach, and both hold a majority. Or client 1 pauses after sending its requests, the keys expire, client 2 acquires, and client 1 wakes up, reads its buffered replies and believes it holds the lock.

There is also no fencing token. The random value each client stores does not increase, so the payment store cannot order two holders.

For payments, I would reject it. Use a consensus-backed lock service that issues increasing tokens, and make the payment store check them or use idempotency keys. If the lock is only to avoid duplicated work, a single server with a lease is simpler and no less safe. The designer of this scheme has disputed these criticisms, so read both arguments before deciding.

Sources

Practise it in the Locks, leases and fencing lab, or open this question on its own page.

Q11SeniorRaft leaders and lock holders both rely on leases to act without a round trip. What assumption does that make about clocks, and what breaks if the assumption fails?

A leader lease says: I heard from a majority less than one election timeout ago, so nobody else can have been elected since, so I may act alone. That is a statement about elapsed time measured on different machines. It assumes that the leader's clock and the followers' clocks advance at nearly the same rate, within a bound, over the lease length.

If a follower's clock runs fast or the leader's runs slow, the follower can time out and elect a new leader while the old one still believes its lease is valid. Two leaders act at once for the overlap. For reads that means a stale answer, for lock grants it means two holders.

The mitigations are a margin that covers the maximum rate difference, leases much shorter than the election timeout, and refusing to serve from the lease when the margin is exceeded. The alternative that does not depend on clocks is a round trip to a majority per operation, which is slower but safe under any clock behaviour. Pick one deliberately and write down why.

Sources

Practise it in the Locks, leases and fencing lab, or open this question on its own page.

Q12SeniorFencing tokens assume the resource can compare tokens. What do you do when the protected resource cannot, for example a third-party API or a file system with no version check?

Then a lock alone cannot make the operation safe, and the honest answer is to say so first. The usual escape is to find a version somewhere. Many stores offer compare-and-set or conditional writes on a version or an ETag, which is a fencing token under another name. Writing to a new object or file named by the token, then atomically swapping a pointer, turns an unconditional write into a conditional one.

When the operation is not idempotent and has no version, such as sending a payment to an external API, move the token into the request as an idempotency key and make the external side reject duplicates. If it cannot, the operation has to be made safe to repeat or safe to lose, or it has to go through a single serialising component that is itself replicated with consensus.

Lamport's view of ordering explains why this works. A token is a logical timestamp for the lock, and the resource needs enough state to compare timestamps. Without that comparison somewhere on the write path, the system is relying on timing, which an asynchronous network does not promise.

Sources

Practise it in the Locks, leases and fencing lab, or open this question on its own page.

Q13SeniorYour lock service has a 12-second session lease and the master fails over in about 20 seconds. How do you design client behaviour so that sessions survive the failover without letting a client act on a lock it has really lost?

Treat the lease running out locally as a state of doubt, not a verdict. The client cannot tell whether the session ended or the master is merely unreachable. It should start a grace period longer than a typical failover, such as 45 seconds, during which it tries to reach the new master and keeps the session if a keepalive succeeds.

During that period the client must not act as though the lock is certain. The library should raise a jeopardy event so the application can quiesce: finish or park in-flight work, stop issuing protected writes and flush nothing it cannot undo. If the session survives, a safe event lets it resume without a restart. If the grace period ends first, an expired event tells it the locks are gone.

The service side matters too. The new master must not grant a lock the old master might still consider held, so it should keep the old sessions' locks reserved for the grace period while clients reconnect, and clients' timers should be conservative about the master's clock rate.

None of this removes the paused-client case, where the code that reacts to the event never runs. So pair the session with a sequencer or token the protected resource checks, and consider a lock-delay for resources that cannot check it.

Sources

Practise it in the Locks, leases and fencing lab, or open this question on its own page.

Q14SeniorA lock holder updates a database row and then publishes a message. Both resources check fencing tokens. The holder is paused between the two steps, loses the lock, and wakes up. What state is left, and how do you design the operation so this is harmless?

The database accepted the first write under token 33. During the pause a new holder took token 34. When the first holder wakes and publishes, the message broker sees 34 already and rejects the stale message. The result is a half-finished change: the row is updated and the message never went out. Each resource enforced fencing correctly, and the pair still ended in a state that neither writer intended.

Fencing makes each resource safe against stale writes. It does not make two resources change together. That needs a transaction or a design that does without one.

Options: make the second step derivable from the first. The new holder reads the row, sees the update with token 33 and no matching message, and republishes. This is the outbox pattern: write the row and an outbox record in one local transaction, and let a separate relay publish from the outbox, idempotently keyed by the record id. Then there is one resource with a commit point, and fencing guards that one. The broker step can be repeated safely, because duplicates are ignored.

Avoid designs where a lock is expected to give atomicity across stores. It only orders holders, and recovery has to be built into the data.

Sources

Practise it in the Locks, leases and fencing lab, or open this question on its own page.

Percentiles

13 questions · Read the lesson

Q1JuniorWhy do teams look at percentiles instead of the average latency?

Latency is skewed. Most requests are fast and a few are slow, so the average sits above the typical request and far below the slow ones. It describes nobody's experience.

A small share of slow requests barely moves the mean. If two percent of requests take twenty times longer, the mean rises by a fraction, while the p99 jumps to the slow path's latency. A dashboard built on averages can stay green while one user in fifty has a bad time.

Read the median for the typical request and a high percentile for the tail, side by side. Page loads that make many calls feel the tail more often than the average suggests, since each call is another chance to draw a slow one.

Sources

Practise it in the Percentiles lab, or open this question on its own page.

Q2JuniorHow does a monitoring system store a request's latency in a histogram, and how does it later answer "what is the p95"?

The histogram is a fixed list of buckets, each covering a range such as 0 to 100 ms or 100 to 250 ms. Recording a request means finding its bucket and adding one to that counter. Nothing about the individual request is kept, so memory stays the same whether the service handles ten requests or ten million.

Prometheus-style histograms store the counts cumulatively: the bucket labelled le="0.25" counts every request at or below 250 ms. To find the p95 of 10,000 requests, look for the first bucket whose cumulative count reaches 9,500. If the 250 ms bucket holds 9,000 and the 500 ms bucket holds 9,900, the p95 lies between 250 and 500 ms. The system then assumes requests are spread evenly inside that bucket and interpolates.

The trade-off follows directly. The answer is an estimate, and its error is bounded by the width of the bucket that holds the percentile. A coarse bucket layout makes the dashboard cheap and the p95 blurry. A finer one costs one extra time series per bucket, per label combination.

Sources

Practise it in the Percentiles lab, or open this question on its own page.

Q3JuniorWhy do dashboards usually show p50, p95 and p99 together rather than a single number?

Each one answers a different question. The p50 is the typical request. The p95 and p99 show how bad it gets for the unlucky ones. The gap between them is itself information: a p99 far above the p50 means a separate slow path, such as a cache miss, a retry or a pause.

A single number can hide a change. If the p50 stays flat and the p99 doubles, one slow path got worse, and the median alone would not show it.

The right set depends on traffic. A service with few requests cannot support a p99.9: out of a thousand requests, a single sample sits above it.

Sources

Practise it in the Percentiles lab, or open this question on its own page.

Q4JuniorYour dashboard shows a p99 of 2 seconds for the last minute, but the service handled only 40 requests in that minute. How much should you trust it?

Not much. With 40 requests, 1 percent is 0.4 of a request. Using the nearest-rank definition, the p99 is the 40th value in sorted order, which is the slowest request in the window. The "p99" is really the maximum.

That makes it jumpy. One request that hit a cold cache or a garbage collection pause turns a p99 of 40 ms into 2 seconds, and the next minute it falls back with no change in the service. Someone reading the chart sees a spike that says more about a single unlucky request than about the system.

The cure is to see more requests before you read a tail percentile. Widen the window to five or fifteen minutes. Merge the histograms from all hosts before computing it, instead of reading each host alone. Print the request count under the number so a reader can judge it. If an alert must stay on a quiet service, base it on a count of slow requests over a longer window, because a handful of slow requests is a clearer signal than one percentile of a thin minute.

Sources

Practise it in the Percentiles lab, or open this question on its own page.

Q5JuniorWhat does it mean when a service reports a p99 latency of 300 ms?

It means 99 percent of requests finished in 300 ms or less, and one percent took longer. Sort every latency in the window from smallest to largest and the p99 is the value 99 percent of the way along.

It does not say how slow the slowest one percent were. Those requests could be 301 ms or thirty seconds. That is why teams often look at a higher percentile as well, such as p99.9, or at the maximum.

The window matters too. A p99 over one minute and a p99 over a day are different measurements, and a p99 over very few requests is decided by a handful of them.

Sources

Practise it in the Percentiles lab, or open this question on its own page.

Q6MidHow do the bucket boundaries of a histogram limit the accuracy of the percentiles you read from it?

A percentile read from a histogram is only known to lie in one bucket. If the system reports a single value, it interpolates inside the bucket and assumes the requests are spread evenly in it. The error is at most the width of that bucket, and often much less.

That is a problem when the bucket is wide compared with the value. With equal-width buckets, one that is narrow next to the tail can be very wide next to the median, so the median is badly estimated while the p99 is fine. Narrow buckets fix that but multiply the series you store.

Geometric buckets, where each is a fixed percentage wider than the last, give a relative error that is the same everywhere. Sketches such as DDSketch make that error a guarantee and stay mergeable across hosts. The price is memory and, in systems that store each bucket as a series, a larger number of time series.

Sources

Practise it in the Percentiles lab, or open this question on its own page.

Q7MidYour latency SLO is that 99 percent of requests finish in under 300 ms. The histogram has bucket boundaries at 250 ms and 500 ms. Why is the SLI unreliable, and what do you change?

A bucket count tells you how many requests were at or below its boundary, so the SLI can be read exactly only at a boundary. Here the threshold of 300 ms falls inside the 250 to 500 ms bucket.

Say a window of 10,000 requests has 9,000 at or below 250 ms and 9,900 at or below 500 ms. At least 9,000 requests are certainly good, which is 90 percent, and at most 9,900 can be, which is 99 percent. The 900 in between could all sit at 260 ms or all at 490 ms. Interpolation assumes an even spread and reports 9,180, or 91.8 percent. It looks precise and rests on a guess. Whether the SLO is met could depend on that guess alone.

The remedy is to put a bucket boundary at 300 ms. With le="0.3" the good count is read directly and the ratio is exact. In general, derive bucket boundaries from your objectives, and keep a few extra ones just below them for warning thresholds. Old data cannot be re-bucketed, so add the boundary before tightening a target, not after.

Sources

Practise it in the Percentiles lab, or open this question on its own page.

Q8MidWhy is averaging each host's p99 the wrong way to get the fleet p99, and what should you do instead?

A percentile describes the shape of a whole group of requests. The shape of the union of several groups is not the average of their shapes. The average also gives a host with a sliver of the traffic the same weight as the busiest one, and the answer can come out too high or too low depending on who is slow.

A host with ten requests and a terrible p99 would count as much as a host with ten thousand. Weighting by traffic fixes that part but not the rest, because the merged p99 depends on how the slow requests are spread over hosts.

The right approach is to export a histogram from every host, add the bucket counts, and read the percentile from the sum. Mergeable sketches do the same with bounded error. If only percentiles are stored, the best you can do is an upper bound from the maximum of the host values.

This bug survives testing because test hosts are identical, and identical hosts agree with their own average.

Sources

Practise it in the Percentiles lab, or open this question on its own page.

Q9MidWhat is coordinated omission, and how does it make a load test report a better tail than users would see?

A closed-loop load generator sends a request, waits for the reply, and sends the next. When the system stalls, the generator is stuck waiting, so it sends nothing during the stall. It records one slow request. The requests that would have been sent on schedule, and would have queued behind the stall, are never sent and never counted.

The result is a tail that is too low, and the more the system stalls the more it understates. The generator and the system have coordinated, without meaning to, to omit the worst samples.

The fix is to send on a fixed schedule, independent of replies, and measure each reply from the time it was meant to go out. Some tools also back-fill the missing samples from the expected interval. A closed loop is still the right model when real clients do wait for a reply before acting again, such as a fixed pool of workers.

Sources

Practise it in the Percentiles lab, or open this question on its own page.

Q10MidYou store one p99 value per minute and are asked for the p99 of the whole hour for a report. What can you compute, and what should you have stored?

From per-minute p99s alone you can compute bounds, not the answer. The maximum of the sixty values is an upper bound on the hourly p99, because if every minute has at most 1 percent above its own p99, the hour cannot have more than 1 percent above the largest one. Nothing gives a matching lower bound that is useful.

The average is wrong, and wrong in a way that depends on traffic. If fifty-nine quiet minutes read 40 ms and one busy minute reads 2 seconds, the average is about 73 ms. The real hourly p99 depends on how many requests the busy minute held. Say 5 percent of that minute's requests were slow. If it carried a quarter of the hour's traffic, 1.25 percent of the hour's requests were slow and the hourly p99 is 2 seconds. If it carried a tenth, only 0.5 percent were slow and the hourly p99 stays near 40 ms. The average of 73 ms tells you neither.

What you should have stored are per-minute histograms, or mergeable sketches such as DDSketch. Adding sixty histograms bucket by bucket gives the histogram of the hour, and you read the percentile from that. The rule is the same as for hosts: sum the distributions, then read the percentile once.

Sources

Practise it in the Percentiles lab, or open this question on its own page.

Q11SeniorDesign the latency measurement for a service on 500 hosts so the fleet p99.9 is accurate, cheap to store and can be sliced by endpoint.

Measure on each host, aggregate across hosts, and keep the aggregation mergeable.

On each host, record every request's latency into a histogram with geometric buckets or a quantile sketch, keyed by endpoint and a few low-cardinality labels. Export the bucket counts, not computed percentiles. The record path is a counter increment, so overhead per request is tiny.

In the pipeline, add bucket counts across hosts for each label set and each time window, then compute percentiles from the sum. A p99.9 over a minute needs enough requests, so decide the windows with traffic in mind and keep longer roll-ups for low-volume endpoints.

Watch the costs. Every label multiplies the series count, and every bucket is a series in some systems, so bound label cardinality and the number of buckets. Check accuracy by comparing against exact percentiles on a sample of traffic, and state the relative error of the sketch. Rule out the shortcut up front: a fleet percentile computed from per-host percentiles is wrong however carefully it is done.

Sources

Practise it in the Percentiles lab, or open this question on its own page.

Q12SeniorA per-minute p99 alert fires a few times every night, when traffic drops to about 20 requests a minute, and almost never by day. Diagnose it and fix it without hiding real regressions.

Start with the arithmetic. With 20 requests in the window, 1 percent is 0.2 of a request, so the p99 is the slowest request of the minute. By day, with 6,000 requests a minute, 60 requests sit above the p99, and one outlier cannot move it. At night a single slow request does. Slow requests arrive at about the same rate in both periods, but the night metric swings on each one.

Confirm it by plotting request count against alert time, and by checking that the alerting minutes each contain one or two slow requests. Then change what the alert measures.

Replace the percentile with a ratio: slow requests over all requests, in a window long enough to hold a meaningful number of them. Compare it with the budget rate, and use paired windows as in burn-rate alerting, say one hour confirmed by five minutes, so a lone slow request cannot page. At 20 requests a minute an hour holds 1,200, and a 99 percent target tolerates 12 slow ones.

Keep a safety valve for real trouble. A drastic failure at night still produces a high ratio in the short window, so it pages quickly. Also keep a daytime percentile on the dashboard for diagnosis. You have lost nothing except pages triggered by one request.

Sources

Practise it in the Percentiles lab, or open this question on its own page.

Q13SeniorA load test shows a p99 of 50 ms, but production shows several hundred. List the explanations you would check, in order.

Start with how the test measures. If the generator waits for each reply, coordinated omission hides the requests that queue behind a slow one, and the test tail is too low. Check that the test sends on a schedule and times from the intended send.

Then compare the load. Production is open loop, with independent arrivals and bursts, while a test with a fixed number of connections may keep the system under a steady, gentler load. Queueing grows sharply with utilisation, so a test at lower utilisation reports a better tail.

Next compare the workload: data size and key distribution, cache warm-up, request mix, connection reuse, and whether the test ran long enough to include pauses and background jobs. A short test misses rare events.

Finally, check the measurement itself: how percentiles are aggregated, bucket widths, and whether the two environments compute the same statistic over the same window. To confirm which explanation is right, replay captured production traffic at its original arrival times and compare.

Sources

Practise it in the Percentiles lab, or open this question on its own page.

Distributed tracing

13 questions · Read the lesson

Q1JuniorA user reports an error at 14:02 and the error page shows a request ID. How does a trace ID help you find the cause across ten services?

If the request ID is the trace ID, it is a key that every service shares. Each service puts the current trace ID into every log line it writes, usually as a structured field filled in by the logging library from the active span. Searching your log store for that one ID returns the lines from the gateway, the backend that failed, and every service in between, ordered by time.

The trace gives the structure that the logs lack. Open the trace by the same ID and you see which service called which, how long each call took, and which span carries the error status. You then read the logs of that span only, instead of ten services' worth.

The W3C trace context identifier is 32 hexadecimal characters, so it is long enough to be unique across services and to be pasted into a search box. Expose it on error pages and in a response header, because support staff can then pass it along without needing access to your tools.

The link works only if the ID reaches every service, so a hop that drops the header leaves its logs without a matching ID.

Sources

  • Sergey Kanzhelev, Morgan McLean, Alois Reitbauer, Bogdan Drutu, Nik Molnar, Yuri Shkuro (2021). Trace Context.
  • OpenTelemetry project (2024). Traces.

Practise it in the Distributed tracing lab, or open this question on its own page.

Q2JuniorHow does the trace identifier get from one service to the next?

Through context propagation. When a service receives a request, it reads the trace context from the incoming message, usually a header. It makes itself a child span of the caller. When it calls another service, it writes the trace identifier and its own span identifier onto the outgoing message.

The W3C Trace Context standard defines a common header format so services built with different tools can still join one trace.

Instrumentation usually lives in shared libraries, such as the web framework and the client, so application code does not do it by hand. The usual failure is a hop that does not forward the header, such as a queue or a third-party service. The trace then splits in two at that point.

Sources

  • Sergey Kanzhelev, Morgan McLean, Alois Reitbauer, Bogdan Drutu, Nik Molnar, Yuri Shkuro (2021). Trace Context.

Practise it in the Distributed tracing lab, or open this question on its own page.

Q3JuniorWhen would you reach for a trace instead of logs or metrics?

Use metrics to see that something is wrong and how widely: rates, errors, latency percentiles. They are cheap and aggregate over all requests, but they have forgotten which request was which.

Use logs to see what a service did in detail. They are rich, but a log line in one service does not say which upstream request caused it unless an identifier is attached.

Use a trace when you need to know where one request spent its time across services: which call was slow, whether calls ran in parallel or in sequence, and what the critical path was.

In practice you chain them. An alert fires on a metric, a trace of one slow request finds the slow span, and the logs of that span give the cause.

Sources

Practise it in the Distributed tracing lab, or open this question on its own page.

Q4JuniorWhat is a trace and what is a span?

A trace is the record of one request and everything it caused across services. It is a tree. Each node is a span, which is one timed operation such as a call to a service or a database query.

A span has a start time, an end time, a name, a parent span and tags. All spans in a trace share one trace identifier, which is what lets the pieces from different services be joined into one picture.

That is the payoff. A metric tells you something is slow. A trace tells you which call in which service took the time on one particular request.

Sources

Practise it in the Distributed tracing lab, or open this question on its own page.

Q5JuniorA service handles 10,000 requests a second and each request produces about 20 spans. Why not store every span?

Do the volume first. 10,000 requests times 20 spans is 200,000 spans a second. If a span is about 500 bytes once encoded, that is 100 MB a second, or roughly 8.6 TB a day, before indexing or replication. Most of it describes healthy, fast requests nobody will open.

There is also a cost on the request path. Creating spans, serialising them and sending them takes CPU and network from the service itself, and at this scale the overhead is measurable.

Sampling keeps a fraction. Keeping 1 percent cuts the example to about 86 GB a day. Dapper started with a uniform rate of 1 in 1024 and found it still produced enough data to find problems, because services that matter have so many requests that even a small fraction contains many examples of any common behaviour.

The price is that rare events can be missed. A problem affecting one request in a million will usually not appear in a 1 percent sample. That is why teams add rules that always keep errors or very slow traces, and why rates should come from metrics that count every request.

Sources

Practise it in the Distributed tracing lab, or open this question on its own page.

Q6MidWhat is the critical path of a trace, and why is the slowest span not always the one to optimise?

The critical path is the chain of spans that determines the end-to-end latency. Follow the trace from the end. When a service calls others in parallel, the path goes through the child that finished last. When it calls them in sequence, the path goes through all of them. The time the path spends in each span's own work adds up to the request latency.

A span off the path can be as slow as you like without affecting the total, because something else is still running when it finishes. A call with the longest own time may be one of several parallel branches, with another branch still going. Making it faster changes nothing.

So rank work by time on the critical path, not by duration or self time alone. Expect the path to move after a fix, because the next-slowest branch becomes the critical one.

Sources

Practise it in the Distributed tracing lab, or open this question on its own page.

Q7MidEach backend call is slow one time in a hundred. A request calls a hundred backends in parallel. Roughly how often is the request slow, and what does this say about tail latency?

If the calls are independent, the chance that all hundred are fast is 0.99 multiplied by itself a hundred times, a little over a third. So the request meets at least one slow call about two times in three. The general form is one minus the fast probability to the power of the number of calls.

The point is that rare slowness in a part becomes common slowness in the whole when a request fans out and waits for the slowest. Tail latency of the components decides the typical experience of the service.

Mitigations include fewer calls per request, hedged or duplicated requests after a short delay, tolerating missing results, and fixing the causes of slow calls. The independence assumption flatters the system. Slow calls often cluster, for instance on one bad host.

Sources

Practise it in the Distributed tracing lab, or open this question on its own page.

Q8MidCompare head-based and tail-based sampling. What does each keep, and what does each cost?

Head-based sampling decides at the start of a request, usually with a random draw, and passes the decision along in the trace context. It is cheap and needs no buffering. Because the outcome is not known yet, it keeps slow and failing requests at the same rate as healthy ones, so the stored sample is a fair picture of traffic and a poor picture of problems.

Tail-based sampling decides after the trace is complete. A rule can keep every slow or failed trace and a small baseline of the rest. The cost is that every span of every trace must be held until the decision, and all spans of one trace must reach the same collector to be judged. Storage grows with the share of traces that are interesting, which can be large during an incident.

Either way the stored sample is biased. Compute rates from metrics that see every request, and use traces to explain individual requests.

Sources

Practise it in the Distributed tracing lab, or open this question on its own page.

Q9MidA tail sampler receives 3,000 new traces a second, waits 30 seconds before deciding, and traces average 15 spans of about 500 bytes. How much must it hold, and what breaks if the buffer is too small?

Multiply rate by wait. 3,000 traces a second for 30 seconds is 90,000 traces in flight. At 15 spans each that is 1.35 million spans, and at 500 bytes each about 675 MB. Real in-memory representations are larger than the encoded size, so plan for a multiple of that, and for bursts on top of it. If the work is spread across several sampler instances by trace ID, divide by the instance count.

If the buffer holds fewer traces than the rate times the wait, it has to push traces out before their timer fires. Those are judged early on partial data or lost, and the configured wait no longer means what it says. A slow trace is the likeliest casualty, because it is the one still open when its turn comes.

Two related issues belong in the same sizing exercise. Spans can arrive after a decision, so keep a cache of recent decisions to let late spans follow the earlier verdict. And all spans of a trace must go to the same instance, so route by trace ID, and expect a resize to split the traces in flight.

Sources

Practise it in the Distributed tracing lab, or open this question on its own page.

Q10MidIn a trace, a parent span lasts 300 ms and has one child of 120 ms that starts 150 ms after the parent does. What explains the missing time, and how do you find out which explanation is right?

Lay out the numbers. The child runs from 150 ms to 270 ms, so the parent spent 150 ms before calling it and 30 ms after, 180 ms in all. That time belongs to the parent's own work, or to something the trace cannot see.

The usual suspects are uninstrumented work such as a database call or serialisation that has no span of its own, waiting for a thread or a connection from a pool, a garbage collection pause, and a lock. If the child runs on another host, clock differences matter too: a few milliseconds of skew moves its bar, though skew does not explain 150 ms.

To decide, look at the parent's self time and attach more evidence. Add spans around the suspicious calls and see whether the gap fills. Check metrics for pool wait and GC pauses on the parent's host at that time. Take a CPU profile or a thread dump from a slow instance, which shows where the time really goes. If the gap appears only in some traces, compare a slow one with a fast one and look for what differs, such as payload size or instance.

Do not guess a cause from the trace alone. The gap tells you where to look, not what is there.

Sources

Practise it in the Distributed tracing lab, or open this question on its own page.

Q11SeniorA request puts a message on a queue and a worker processes it later. The trace splits in two at the queue. How do you keep it connected, and what do you do when one message belongs to many requests?

Treat the message as a carrier. The producer writes the trace context into the message headers when it publishes, and the consumer reads it when it starts processing and creates its span as a child, or with a link, to the producer's span. OpenTelemetry's messaging conventions use links as the default and allow a direct parent only when a consumer handles a single message.

For batches, a worker may handle messages from many traces at once. Create one span for the batch and add a link to each message's context, instead of picking one parent. That keeps every origin findable without pretending the batch belongs to a single request.

Be honest about latency in the picture. The time a message waits on the queue is part of the user's wait but it is not work in either service, so show it as its own span or gap. Two details remain. Clocks differ between hosts, so a consumer span can appear to start before its producer. And retries and dead-letter paths need the same context, or they fall out of the trace.

Sources

  • Sergey Kanzhelev, Morgan McLean, Alois Reitbauer, Bogdan Drutu, Nik Molnar, Yuri Shkuro (2021). Trace Context.
  • OpenTelemetry project (2024). Traces.

Practise it in the Distributed tracing lab, or open this question on its own page.

Q12SeniorThirty percent of the root spans in your backend services have no parent, although the edge gateway starts a trace for every request. How do you find where context is lost across 200 services, and how do you stop it coming back?

A server span that should have a parent but is a root means the incoming request carried no usable trace context. So the question for each service is how often its inbound spans are roots. Graph that ratio per service and per caller. A healthy service sits near zero. A service whose callers are all healthy but whose own inbound ratio is high has a problem upstream of it, in the service that calls it. Walking the call graph from the edge, the first edge where the ratio jumps shows the hop that drops context.

Typical culprits are a client library that does not inject the header, a thread pool or async hop where the context is not carried over, a queue or proxy that strips headers, and a mix of propagation formats, such as an older vendor header on one side and W3C traceparent on the other. A service mesh sidecar cannot repair the middle of an application: it can start spans for traffic it sees, but the app has to pass the context from the inbound call to the outbound one.

To stop it recurring, put propagation in the shared HTTP, gRPC and messaging clients so teams do not write it, standardise on W3C Trace Context with any legacy format as a secondary propagator, and add a contract test that a call through each client carries the header. Keep the orphan-ratio graph as an alert, so a regression is found within a day.

Sources

Practise it in the Distributed tracing lab, or open this question on its own page.

Q13SeniorDesign a tracing pipeline for a large service so that slow and failed requests are always kept, overhead is low, and cost is bounded.

Split the problem into recording, collection and storage, and put the expensive decision where the information is.

Recording: instrument shared libraries so application code is untouched, and make the cost of an unsampled span very small. Dapper reports that unsampled annotations are nearly free, which is what lets tracing stay on everywhere. Propagate the sampling flag in the trace context.

Collection: send spans to a tier of collectors, routed by trace identifier so all spans of one trace land on the same one. There, hold each trace in a buffer until it finishes or a timeout passes, then apply tail rules: keep traces over a latency threshold, traces with errors, and a small random baseline. Bound the buffer in memory and decide what to do when it fills, for example fall back to head-sampled decisions.

Storage and cost: apply a second round of sampling or a rate target per service so a noisy service cannot use the whole budget, and keep counters of everything seen so rates can be recovered from metrics. Plan for the case where a bad incident makes most traces slow, since a tail sampler then stores most of them.

Then list how it fails: dropped spans, clock skew, collectors restarting with traces in flight. Measure the pipeline itself, for example by checking that the share of slow traces it stores matches what metrics say was slow.

Sources

Practise it in the Distributed tracing lab, or open this question on its own page.

SLOs and alerting

14 questions · Read the lesson

Q1JuniorWhat is an error budget? How much downtime does a 99.9 percent SLO over 30 days allow?

The error budget is the amount of failure an SLO allows: one minus the target, applied to the window. For 99.9 percent, 0.1 percent of requests or of time may be bad.

Over 30 days that is 43.2 minutes of total outage. Partial failures count in proportion, so a 50 percent error rate for ten minutes costs five minutes of budget.

The budget makes reliability a resource to be spent. While it lasts, the team can take risk, such as releasing often. When it is spent, the team slows changes and invests in reliability. Planned work draws on the same budget as accidents, so a risky migration and a bad deploy compete for it.

Sources

Practise it in the SLOs and alerting lab, or open this question on its own page.

Q2JuniorWhat SLIs would you choose for a nightly batch pipeline that builds a daily report from user events?

Request latency and error rate fit a user-facing API, not a job that runs once a night. Ask what the report's readers care about and measure that.

Freshness is the first: the report should be ready by, say, 06:00. As a ratio, count the days on which it was ready on time over all days in the window, or the share of the data newer than a threshold. Coverage is the second: the share of the day's events that actually made it into the report. If a source silently fails and the job finishes with 80 percent of events, a green job status hides a wrong report. Correctness is the third: a check that totals match an independent count, or that known test events appear.

Throughput and end-to-end time are useful for capacity, but they are not what readers feel, so keep them as dashboards instead of objectives.

Each indicator should be a ratio of good events to valid events, so it can be given a target such as 99 percent of mornings on time, and an error budget of about three or four late mornings in a year. "The job exited with status zero" is not an SLI, because a job can succeed at producing the wrong thing.

Sources

Practise it in the SLOs and alerting lab, or open this question on its own page.

Q3JuniorWhat is the difference between an SLI, an SLO and an SLA?

An SLI, a service level indicator, is a measurement of service quality, usually a ratio of good events to all events. For example, the share of requests that succeed in under 300 ms.

An SLO, a service level objective, is a target for an SLI over a period, for example 99.9 percent over 30 days. It is an internal goal that guides decisions.

An SLA, a service level agreement, is a promise to a customer, often with consequences such as credits if it is missed. The SLO should be stricter than the SLA so the team notices trouble before it costs money.

Pick the SLI from what users experience. "The process is up" is not an indicator.

Sources

Practise it in the SLOs and alerting lab, or open this question on its own page.

Q4JuniorWhy not set the reliability target to 100 percent?

It is not achievable, and chasing it is very expensive. Every extra nine costs more, because the failures that remain are the rare and hard ones. Users also cannot tell the difference between 100 percent and a very high number, since their own network, device and other services fail more often than the service does.

A target of 100 percent also leaves no budget, which means no change is ever safe. Releases, experiments and maintenance all carry risk, so the team stops improving the product.

Choose the target from what users need and what each extra nine costs, and leave enough budget to keep shipping.

Sources

Practise it in the SLOs and alerting lab, or open this question on its own page.

Q5MidWhat is a burn rate? What does a burn rate of 14.4 over one hour tell you about a 30-day SLO?

Burn rate is how fast the error budget is being spent compared with the rate that would spend it exactly over the whole window. It is the measured error ratio divided by the budget rate. A burn rate of one empties the budget at the end of the window.

A burn rate of 14.4 sustained for one hour uses two percent of a 30-day budget, since one hour is one 720th of the window and 14.4 times that is two percent. Held at that rate, the whole budget would be gone in about two days.

That is why the number appears in alerting guidance: it is the rate at which a short, severe problem has already cost a meaningful share of the budget. Divide the window by the burn rate to get time to exhaustion: 30 days over 14.4 is about 2.1 days.

Sources

Practise it in the SLOs and alerting lab, or open this question on its own page.

Q6MidWhy alert on burn rate instead of a fixed error-rate threshold?

A fixed threshold has no link to the objective. Set high, it misses slow leaks that would still empty the budget. Set low, it pages on short blips that cost almost nothing. Either way the page does not tell the responder how much budget is at stake.

A burn-rate alert is stated in terms of the budget. Firing at a given burn rate over a given window means a known share of the budget has gone, or will go within a known time. That lets you choose which problems deserve a page and which a ticket, and the same rule works across services with different objectives.

Burn-rate alerts do not fix everything. A single long window is slow to clear, a short window is jumpy, and low-traffic services give noisy ratios.

Sources

Practise it in the SLOs and alerting lab, or open this question on its own page.

Q7MidShould a latency SLO say "p99 under 500 ms" or "99 percent of requests under 500 ms"? They sound identical.

Over a single window they are the same statement: if 99 percent of requests were under 500 ms, the p99 is under 500 ms. They differ in what you can do with them afterwards.

The ratio form is a count of good events over a count of valid events. Counts add up, so you can sum them across hosts, regions and days and divide once. A percentile does not. A fleet p99 cannot be rebuilt from per-host p99s, and a monthly p99 cannot be rebuilt from daily ones.

The ratio also plugs into error budgets. One percent of requests may be slow, so every request over 500 ms spends budget, and you can say how much was spent by a given incident. Burn-rate alerts then work unchanged, with the slow share playing the role of the error ratio. A percentile target only says pass or fail for a window, and it does not say how badly a failing window failed or how much margin a passing one had.

The ratio form has a cost: you need a bucket boundary at 500 ms to read it exactly. The percentile form needs a mergeable histogram anyway, so that is rarely a real obstacle.

Sources

Practise it in the SLOs and alerting lab, or open this question on its own page.

Q8MidA service gets one request a minute under a 99.9 percent SLO over 30 days. Your fast burn-rate alert pages whenever a single request fails. Is the alert broken?

Work out what a failure costs. A 30-day month holds 43,200 requests at this rate, so the budget is 43.2 failed requests. One failure spends about 2.3 percent of it.

Now the alert. The fast pair fires at a burn rate of 14.4 over one hour, which is an error ratio of 1.44 percent. An hour holds 60 requests, and one failure out of 60 is 1.67 percent, a burn rate of 16.7. The five-minute window holds about five requests, so one failure there is 20 percent. Both windows are over the line, and the alert fires. The rule is doing exactly what it was designed to do: page when about 2 percent of the budget has gone, which one failure has done.

So the alert is correct and the setup is wrong. A 99.9 percent target on a service this small leaves 43 failures a month, and each one matters. Ask whether the owners mean that. If the service is a background job with retries, a looser target such as 99 percent, or counting final outcomes after retries, fits better. If the target stands, add probe traffic or group the service with others so a page needs several failures.

Sources

Practise it in the SLOs and alerting lab, or open this question on its own page.

Q9MidWhat does the second, shorter window in a multi-window burn-rate alert do?

The long window decides whether the burn is large enough to matter. It averages away short blips, so the alert does not page for them. The short window checks that the burn is still happening now.

Without the short window, a long-window alert keeps firing for as long as the bad minutes stay in the window, long after the service has recovered. People are paged for a problem that is already over. The short window drops quickly when errors stop, so the alert clears soon after.

Requiring both gives fewer false alerts than a short window alone and faster resets than a long window alone. Real setups run several such pairs at different burn rates. The fastest page someone and the slowest only raise a ticket.

Sources

Practise it in the SLOs and alerting lab, or open this question on its own page.

Q10SeniorA team has spent most of its error budget with a third of the window left. What do you do, and what policy would you want in place beforehand?

First understand where the budget went. A single large incident, a slow leak and steady background failure need different responses. Look at the burn rate now: if it is still above one, the budget will run out before the window ends.

Then act on the policy. A good error budget policy is agreed before the budget is spent. It says what happens at thresholds: for example, at a given share spent, reliability work takes priority, risky releases need extra review, and when the budget is gone, releases pause except for fixes until the service is back in objective.

Make the trade-off explicit with product owners. If the objective is wrong, because it is stricter than users need or looser than they notice, change it through the same process instead of quietly ignoring it. Write the postmortems for the big spends and track the fixes.

A policy only works if someone outside the team that wants to ship can enforce it, and if the numbers come from measurements everyone trusts.

Sources

Practise it in the SLOs and alerting lab, or open this question on its own page.

Q11SeniorProduct wants a 99.95 percent SLO for checkout. It hard-depends on auth at 99.9, payments at 99.95 and inventory at 99.9. What do you tell them?

Say that the target is out of reach as designed, and show the arithmetic. If a request needs all three, and they fail independently, the best availability is 0.999 times 0.9995 times 0.999, which is about 99.75 percent. A 99.95 percent target allows 21.6 minutes of failure in 30 days. The dependencies alone are expected to cause about 108, before checkout's own bugs and releases.

Then offer options, in order of effort. First, check whether each dependency is truly hard. Inventory could be served from a cache that is allowed to be a minute stale, which removes it from the product. Auth sessions can often be validated locally from a signed token, so a brief auth outage does not block checkout. Second, ask the owning teams what they really deliver. Measured availability often differs from the published target, in either direction. Third, negotiate tighter targets for the dependencies that matter, with the cost made explicit. Fourth, if none of that works, lower checkout's target or promise it only for the paths that avoid the weak links.

State the assumptions. Independence is optimistic, since shared infrastructure makes failures cluster, so the product is a rough guide and not a guarantee. Whatever target is agreed, keep a budget line for the dependencies so the split is visible.

Sources

Practise it in the SLOs and alerting lab, or open this question on its own page.

Q12SeniorDesign burn-rate alerting for a 99.99 percent SLO over 30 days. What is different from a 99.9 percent service?

Start with the budget: 0.01 percent of 43,200 minutes is 4.32 minutes of total outage in a month. The burn-rate pairs from the Workbook are expressed relative to the budget, so the same table applies: 14.4 over one hour, 6 over six hours, 1 over three days. What changes is how small the numbers get.

A burn rate of 14.4 over an hour means 2 percent of the budget, which is about 5 seconds of full outage. A total outage crosses that threshold within seconds, so the limit is not the rule but the pipeline. If metrics are scraped every 15 to 30 seconds and rules evaluate every minute, detection takes tens of seconds, and a human who must wake up, open a laptop and act needs several minutes. One five-minute response already uses more than the whole month's budget.

The design consequence is that paging cannot protect this budget. Paging still matters for slow burns and for learning, but the weight shifts to prevention and automation: canary releases that stop bad deploys before they reach everyone, automatic failover and rollback, and load shedding. Measure at a finer resolution than a minute, or the SLI itself will be too coarse to see the events that matter.

Finally, check that the target is credible. The dependencies of a 99.99 percent service need to be better still.

Sources

Practise it in the SLOs and alerting lab, or open this question on its own page.

Q13SeniorDesign alerting for a 99.95 percent SLO on a service with low and spiky traffic.

Start with why ratios fail here. With few requests, one failure is a huge error ratio and a huge burn rate. A rule written for steady traffic will page for single unlucky requests, and the quiet hours make the ratio meaningless.

Options in order of how often they are right: generate synthetic traffic from probes so there is always a signal to measure; combine small services into one SLO for monitoring; lengthen the windows so a few failures are diluted; or change the product so one failure matters less, such as client retries.

Choose the objective carefully too. A very high target on very low traffic leaves a budget of a handful of requests, so every failure is an incident. Decide whether that is what the business wants.

Then keep the structure: multiple burn rates with paired windows, with fast pairs paging and slow pairs filing tickets. Test the rules by replaying history, counting pages, false pages and time to detect. Throughout, alert on symptoms users feel, such as failed requests, and leave causes like CPU to dashboards.

Sources

Practise it in the SLOs and alerting lab, or open this question on its own page.

Q14SeniorOne team measures its SLO per calendar month and another over a rolling 30 days. How do the two behave differently, and which would you recommend?

A calendar window resets. On the first of the month the budget is full again, whatever happened on the 30th. That is easy to report and it matches how business reviews and contracts work, but it distorts behaviour. A team that has burned its budget by the 20th gets ten days of freeze, and a team that starts the month clean may take big risks on day one. A large outage on the last day of a month is forgotten the next morning, even though users are not so forgetful.

A rolling window never resets. Each day the oldest day drops out and a new one enters, so an incident stays in the budget for the whole window and then leaves on the day it ages out. Budget returns gradually, which better matches how users remember. The drawbacks are that the number moves daily and is harder to explain to people outside engineering.

The Workbook recommends rolling windows because they track user experience, and defines them as a whole number of weeks, so every window has the same count of weekends and weekdays. It suggests four weeks as a good general-purpose length. I would take a four-week rolling window for engineering decisions, and add calendar-month summaries for finance or customer reports, derived from the same data.

Sources

Practise it in the SLOs and alerting lab, or open this question on its own page.

B-trees

8 questions · Read the lesson

Q1JuniorA table has a hundred million rows in a B-tree with a branching factor of about 500. Roughly how many page reads is a point lookup?

About three to four. With 500 children per page, one level reaches 500 leaves, two levels reach 250 thousand, three levels reach 125 million. So a tree of height three or four covers the table.

In practice fewer reads go to disk. The root and often the second level are hot and stay in the buffer cache, so a lookup may do one or two real reads.

A good answer says the cost grows with the logarithm of the table size, base the branching factor, and that this base is large.

Sources

Practise it in the B-trees lab, or open this question on its own page.

Q2JuniorWhat happens when you insert a key into a B-tree page that is full?

The page splits. The engine allocates a new page, moves about half of the keys to it, and adds a separator key and a pointer to the parent page so lookups can find the new page.

If the parent is also full, it splits in the same way, and the split can climb to the root. When the root splits, the tree grows one level taller. That is the only way a B-tree gets taller, so all leaves stay at the same depth.

A split writes at least three pages for one insert: the old leaf, the new leaf and the parent. Splits are rare per insert, but they are why one small write can touch several pages.

Sources

Practise it in the B-trees lab, or open this question on its own page.

Q3JuniorWhy do databases store indexes as B-trees instead of binary trees?

A disk is read in pages, not in single keys. A binary tree puts one key in each node, so a lookup among a million keys follows about twenty pointers, and each one may be a separate page read.

A B-tree packs hundreds of keys into one page. Each page has many children, so the tree is very shallow. Three or four levels cover a very large table, and the top levels are small enough to stay in memory.

The trade-off is that every node is a wide sorted array. Inserting into a node means shifting keys, and a full node must be split.

Sources

Practise it in the B-trees lab, or open this question on its own page.

Q4MidWhy are inserts with random keys, such as random UUIDs, slower into a B-tree than inserts with increasing keys?

Increasing keys always land in the rightmost leaf. That page is hot in memory, it fills completely, and then the tree adds the next page. Writes are close to sequential.

Random keys land on a different leaf each time. Once the tree is bigger than memory, most inserts need a page read to find the leaf, and each one dirties a different page. Splits of half-full pages leave leaves only about two thirds full on average, so the tree is also larger.

The usual fix is a key that is roughly time ordered, or a separate surrogate key for the clustered index. The trade-off is hot-spotting the right edge under heavy concurrent writes.

Sources

Practise it in the B-trees lab, or open this question on its own page.

Q5MidWhy does a B-tree database write a log before it changes pages, and why not just write the pages?

Changing a page in place is a random write, and a split changes several pages. If the machine crashes halfway, the tree can be left with a half-finished split and be corrupt.

A write-ahead log is an append-only file. The engine writes a record describing the change and flushes the log, and only then calls the write committed. The changed pages can sit in memory and be written later, in batches. After a crash, the engine replays the log to redo committed changes and undo unfinished ones.

So the log buys two things: durability with one sequential write, and a safe way to put off the random page writes. The cost is that every change is written twice, once in the log and once in the page.

Sources

Practise it in the B-trees lab, or open this question on its own page.

Q6MidWhy does a B-tree write far more bytes than the application asked it to?

The unit of writing is a page. Changing one 100 byte record dirties a whole page of several kilobytes, so the engine writes the whole page for a small change. That is write amplification.

The log adds a second write of every change. Splits add more, because a split writes two leaves and a parent. Some engines also write a full copy of a page the first time it changes after a checkpoint, to survive a torn write.

You reduce it with larger checkpoint intervals, so a page that changes many times is written once, and with sequential keys, so each insert dirties the same few pages. A good answer names the page size as the multiplier.

Sources

Practise it in the B-trees lab, or open this question on its own page.

Q7SeniorWhat does a checkpoint do, and how do you choose how often to take one?

A checkpoint writes the dirty pages in memory to the data file and records a point in the log. Recovery then only needs to replay the log from that point, and older log can be recycled.

Checkpoint rarely and you write fewer pages, because a hot page that changed a hundred times is written once. The cost is a long replay after a crash and a large log. Checkpoint often and recovery is quick, but you write pages more often and may produce bursts of I/O that hurt query latency.

A good answer mentions spreading the writes out over the interval so they do not arrive in a spike, and sizing the interval from the recovery time the service can tolerate.

Sources

Practise it in the B-trees lab, or open this question on its own page.

Q8SeniorA crash happens while a page is being written, and only part of it reaches disk. How does a B-tree engine cope?

A torn page cannot be repaired by replaying a log record that says "change bytes 40 to 80", because the base page is no longer a valid page.

There are two common defences. One is to write a full image of a page into the log the first time it changes after a checkpoint, so recovery can restore the whole page and then apply later records. The other is to write pages first to a separate area and then copy them to their place, so a good copy always exists. Page checksums let the engine detect the damage in the first place.

The trade-off is more bytes written. This is one more reason write amplification in a B-tree is higher than the size of the record suggests.

Sources

Practise it in the B-trees lab, or open this question on its own page.

LSM trees

8 questions · Read the lesson

Q1JuniorFiles in an LSM tree are never edited. How does a delete work?

The engine writes a marker, called a tombstone, for the key. A read that finds the tombstone first treats the key as deleted, because the newest version wins.

The old value is still in older files. Compaction removes it later, and the tombstone itself can be dropped only when the compaction reaches the oldest data that could hold the key.

So a delete does not free space right away, and a heavy delete workload can slow reads, because scans must step over many tombstones.

Sources

Practise it in the LSM trees lab, or open this question on its own page.

Q2JuniorWhen would you choose an LSM-based store over a B-tree based one?

Pick an LSM tree when the workload is write heavy and the data is much larger than memory. Writes are sequential, so a disk absorbs a high rate of inserts, and compaction can pack data densely.

Pick a B-tree when reads, especially range scans and point reads with a tight latency target, matter most, or when you want predictable latency. A B-tree reads one place per level and has no background merging that competes for I/O.

A good answer names the trade-off both ways. An LSM tree has background work and read cost that varies. A B-tree pays random page writes.

Sources

Practise it in the LSM trees lab, or open this question on its own page.

Q3JuniorDescribe how a write moves through an LSM tree.

The write is appended to a log for durability and inserted into the memtable, a sorted table in memory. When the memtable is full, it is written to disk in one sequential pass as an immutable sorted file, an SSTable.

Over time files pile up. A background process, compaction, merges them into larger sorted files and drops old versions of keys.

The write itself never changes an existing file. That is what makes writes fast and sequential, and why reads have to look in more than one place.

Sources

Practise it in the LSM trees lab, or open this question on its own page.

Q4MidDefine write, read and space amplification for an LSM tree, and say why you cannot minimise all three.

Write amplification is the bytes written to disk per byte the application wrote, mostly from compaction rewriting data. Read amplification is the number of files, or the amount of data, a read must examine. Space amplification is the bytes stored per byte of live data, caused by old versions that have not been merged away.

They pull against each other. Merging more eagerly keeps few files and few old versions, so reads and space are good, and the data is rewritten many times. Merging lazily saves write work, and leaves more files and more stale data.

A good answer says that the compaction policy is a choice of which cost to pay, based on the workload.

Sources

Practise it in the LSM trees lab, or open this question on its own page.

Q5MidCompare leveled and tiered compaction. Which suits a write-heavy ingest workload?

Leveled compaction keeps one sorted run per level, and each level is a fixed multiple larger than the one above. A merge pushes a level down into the next. Reads check few runs and stale data is removed quickly, and each entry is rewritten about once per level, or more.

Tiered compaction lets several runs of similar size accumulate and merges them together when there are enough. Each entry is rewritten about once per level, so writes are cheaper. Reads check more runs and space use is higher because old versions linger.

For write-heavy ingest where reads are rare or filtered, tiered fits. For read-heavy loads, or when disk space is tight, leveled fits. Say what you would measure to decide.

Sources

Practise it in the LSM trees lab, or open this question on its own page.

Q6MidHow does a point read work in an LSM tree, and what makes it slow?

The read checks the memtable first, then the files from newest to oldest, and returns the first version it finds. A file is checked by looking up its index to find the one block that could hold the key.

A key that is present is usually found early. A key that is absent has to be ruled out in every file, which is the worst case. Each file check can mean a disk read.

Bloom filters fix most of this. A small in-memory filter per file says "definitely not here" for almost every file that does not hold the key. The read then touches only the file that has it, plus a rare false alarm.

Sources

Practise it in the LSM trees lab, or open this question on its own page.

Q7SeniorHow does the size ratio between levels change an LSM tree, and how would you tune it?

A larger ratio makes each level bigger relative to the one above, so there are fewer levels. In leveled compaction that means fewer levels to read, and more rewriting for each entry at each merge, since each merge pulls in a larger neighbour. In tiered compaction a larger ratio means more runs wait before a merge: cheaper writes, more runs to read.

To tune, you start from the workload mix. Measure the share of writes, point reads, misses and scans, and the space budget. Then pick a policy and ratio that put the cost where the workload can bear it, and watch compaction backlog and read latency after the change.

Adaptive designs mix policies, with tiered at small levels and leveled at the largest, so that most data sits in one run and recent data is cheap to write.

Sources

Practise it in the LSM trees lab, or open this question on its own page.

Q8SeniorAn LSM store has fine average write latency but sometimes stalls writes for seconds. What is happening, and what do you do?

Compaction has fallen behind ingest. Files are piling up faster than they merge, so the store slows or stops writes to let compaction catch up, rather than let read cost and disk use grow without bound. The memtable may also be full while the previous one is still flushing.

Possible fixes are to give compaction more I/O bandwidth, to add parallel compaction threads, to switch to a policy that rewrites less, to smooth ingest with a queue upstream, or to leave headroom so a burst does not outrun the merge. Limiting the rate of compaction I/O so it does not starve reads is the other side of the same trade.

A good answer treats the stall as a signal that sustained write rate is above what the compaction policy can merge, not as a random glitch.

Sources

Practise it in the LSM trees lab, or open this question on its own page.

Indexes and filters

8 questions · Read the lesson

Q1JuniorWhat is a Bloom filter, and what kinds of mistakes can it make?

A Bloom filter is a bit array with several hash functions. To add a key, you set the bits its hashes point to. To check a key, you test those same bits. If any is zero, the key is definitely absent. If all are set, the key is possibly present.

It makes only one kind of mistake: a false positive, where an absent key happens to land on bits that other keys have set. It never makes a false negative, because a key that was added has all its bits set.

That one-sided error is what makes it useful as a guard in front of an expensive lookup. A false positive costs one wasted lookup, never a wrong answer.

Sources

Practise it in the Indexes and filters lab, or open this question on its own page.

Q2JuniorHow does the number of bits per key change a Bloom filter?

More bits per key means fewer collisions, so a lower false positive rate. The rate falls fast at first and then slowly. Each extra bit per key cuts the false positive rate by a similar factor, so going from a few bits to ten buys a lot, and going from ten to twenty buys a small share of the remaining errors for double the memory.

The number of hash functions matters too. Too few makes each test weak. Too many fills the array with set bits. The best count is about 0.69 times the bits per key.

A good answer gives the trade-off as memory against wasted lookups, and ties the choice to how costly a wasted lookup is.

Sources

Practise it in the Indexes and filters lab, or open this question on its own page.

Q3JuniorWhat does adding an index cost, and what does it buy?

An index lets a query find rows by a column without scanning the table. A lookup reads a few pages instead of all of them.

The cost lands on writes. Each insert, delete or update of an indexed column must also change the index, which is another tree with its own page writes and its own log records. The index also takes disk space and memory in the cache.

So each index is a bet that the reads it speeds up are worth the writes it slows. A good answer says to index for the queries you actually run and to drop indexes that nothing uses.

Sources

Practise it in the Indexes and filters lab, or open this question on its own page.

Q4MidWhy do LSM stores keep a Bloom filter for each sorted file, and what does it save?

A read for an absent key has to be ruled out in every file. Each check is a block read from disk. With many files, a miss costs many reads.

A small in-memory filter per file answers "definitely not here" for nearly every file that lacks the key. The read skips those files. Only the file that holds the key, and the rare file with a false positive, is read.

The filter costs memory, about ten bits per key for a rate near one in a hundred. It does not help range scans, because a filter answers membership of one key, not order. A good answer says that.

Sources

Practise it in the Indexes and filters lab, or open this question on its own page.

Q5MidA query filters on column a with equality and on column b with a range. In what order should a two-column index list them?

Put the equality column first. Entries in a composite index are sorted by the first column, then by the second inside each value of the first. With a fixed value of a, the entries for b are contiguous, so a range on b becomes one scan.

With the range column first, the matching entries for a are scattered through the range, and the engine has to filter many entries it reads.

The same index also serves queries on a alone, and cannot serve a query on b alone well. A good answer says the index follows the leftmost prefix rule and relates it to sorted order.

Sources

Practise it in the Indexes and filters lab, or open this question on its own page.

Q6MidWhat is a covering index, and when does it help?

A covering index contains every column a query needs. The engine answers from the index alone and never visits the table page for each matching row. That saves a random read per row, which is the largest cost of a lookup that returns many rows.

The index gets wider because it stores the extra columns. It uses more space and makes writes to those columns touch the index too.

A good answer says to cover the hot, narrow queries, and not to widen an index to cover everything. It also notes that engines check that the index entry is visible to the reader, which can still require a table visit.

Sources

Practise it in the Indexes and filters lab, or open this question on its own page.

Q7SeniorYou have a fixed memory budget for Bloom filters across all levels of an LSM tree. Should every level get the same bits per key?

No. A miss that reaches a level costs about one read per false positive at that level. A false positive at a small upper level costs the same as one at the huge bottom level, but the bottom level holds most of the keys and so uses most of the filter memory at a uniform rate.

Giving the upper levels more bits per key, and the largest level fewer, lowers the total expected wasted reads for the same memory. The expected cost of a miss is the sum of the false positive rates over all runs, and moving bits to where each bit removes more of that sum helps.

A good answer states the objective as the sum of the rates, notes the uniform setting is not optimal, and mentions that the gain grows with the number of levels.

Sources

Practise it in the Indexes and filters lab, or open this question on its own page.

Q8SeniorA table takes thousands of inserts a second and has grown ten indexes over the years. Insert latency is rising. How do you investigate and fix it?

Start by measuring which indexes are used. Most databases track how often each index serves a query. An index that nothing reads is pure write cost and can go. Check for redundant ones too, such as an index on a that is covered by one on a and b.

Then look at the write path. Each remaining index adds random page writes and log records per insert. Options are to merge indexes with a composite that serves several queries, to make indexes partial, so they cover only the rows that matter, to move rarely used lookups to a replica or search system, and to batch writes so pages are touched once.

A good answer weighs each index by reads served against write cost, and says to change one thing at a time with before and after measurements.

Sources

Practise it in the Indexes and filters lab, or open this question on its own page.

Two-phase commit

8 questions · Read the lesson

Q1JuniorWhat happens if one participant votes no?

The coordinator decides abort and tells every participant. Those that voted yes roll back their prepared changes and release their locks. The participant that voted no can abort at once, since it never promised anything.

A no vote is cheap. The expensive failure is the missing vote or the missing decision, because silence cannot be told from a slow reply. The coordinator can abort on a missing vote, since nobody has committed yet.

Sources

Practise it in the Two-phase commit lab, or open this question on its own page.

Q2JuniorWalk through the two phases of two-phase commit.

In the prepare phase, the coordinator sends a prepare request to every participant. Each participant makes its changes durable, keeps its locks, and replies yes or no. A yes is a promise: it will commit if told to, even after a crash.

In the commit phase, the coordinator writes its decision to its own log. Commit if every vote was yes, abort otherwise. It then sends the decision, and each participant applies it, releases its locks and acknowledges.

Two points to name. The yes vote is the point of no return for the participant. The decision is final once the coordinator has logged it.

Sources

Practise it in the Two-phase commit lab, or open this question on its own page.

Q3JuniorWhat problem does two-phase commit solve?

A transaction may change data on several machines. The danger is that some commit and others do not, and the data is left half changed.

Two-phase commit makes the outcome the same everywhere. A coordinator first asks every participant whether it can commit. Only if all say yes does the coordinator tell them to commit. If any says no, everyone aborts.

The trade-off is that the participants must wait for the coordinator's decision. That waiting is the cost of agreeing.

Sources

Practise it in the Two-phase commit lab, or open this question on its own page.

Q4MidWhat is cooperative termination, and when does it help?

A prepared participant that has timed out asks the other participants what they know. If any of them heard the decision, or never voted yes and therefore aborted, the asker learns the outcome and can finish.

It helps when the coordinator crashed after telling some participants but not all. It does not help when every participant is prepared and none heard anything. They are all in doubt, and any choice could contradict the coordinator's log.

So it shortens many blocks, but cannot remove them. Say that it needs the participants to know each other.

Sources

Practise it in the Two-phase commit lab, or open this question on its own page.

Q5MidThe coordinator crashes after every participant voted yes. What state are the participants in, and what can they do?

They are in doubt. Each one promised to commit and is holding locks, but none knows the decision. If it commits, another participant may have been told to abort. If it aborts, the coordinator may have decided commit.

A participant cannot choose on its own. It must wait for the coordinator to recover and read its log, or learn the decision from a peer that heard it. Until then, the locks stay held and other transactions that need those rows wait behind them.

This is why two-phase commit is called blocking. A good answer names the lock holding, and says that a longer outage means a longer block.

Sources

Practise it in the Two-phase commit lab, or open this question on its own page.

Q6MidWhich timeouts are safe in two-phase commit, and which are not?

Before a participant votes, it can abort alone after a timeout. No one can have committed without its yes, so this is safe.

The coordinator can also abort when a vote does not arrive. Nobody has been told to commit yet.

After a participant votes yes, a timeout is not a license to abort. The coordinator may have decided commit and told someone else. An abort by this participant would split the outcome, which is the one thing the protocol exists to prevent. The safe moves are to keep waiting, ask the coordinator, or ask peers.

Sources

Practise it in the Two-phase commit lab, or open this question on its own page.

Q7SeniorWhy is three-phase commit rarely used, even though it avoids blocking?

Three-phase commit adds a pre-commit round, so no participant is ever unsure in a way that forces it to wait. If the coordinator fails, the others can elect a new one and finish, using timeouts to decide.

The protocol assumes a network that does not partition and timeouts that are always correct. In a real network a slow link looks like a crash. Two groups can reach different decisions, so it can break atomicity. It also adds a round trip to every commit.

Paxos-based commit gets the nonblocking behaviour with a sound assumption. The commit decision is stored in a replicated log that survives the failure of a minority. That is the line of work to cite.

Sources

Practise it in the Two-phase commit lab, or open this question on its own page.

Q8SeniorWhat does two-phase commit cost in latency, availability and throughput, and why do many systems avoid it across services?

Latency: two round trips plus forced log writes at each participant and at the coordinator, and the transaction is as slow as its slowest participant.

Availability: the transaction commits only if every participant is up. With n participants each up with probability a, it commits with probability about a to the n. Add the blocking when the coordinator fails, and the locks of in-doubt transactions stall other work.

Throughput: locks are held through both rounds, so hot rows serialize.

Teams avoid it between independent services because those services do not share a transaction manager and should not lock each other. They use sagas or design to keep a transaction inside one partition instead. It remains common inside one database, where the participants are replicas or shards that the same system manages.

Sources

Practise it in the Two-phase commit lab, or open this question on its own page.

Sagas

8 questions · Read the lesson

Q1JuniorHow is a compensating action different from a rollback?

A rollback erases a change as if it never happened. No one saw it. A compensation is a new, committed change that cancels the effect of an old one. A refund does not remove the charge. It adds a credit.

So the earlier change was visible, and anything that reacted to it may have done so. Some actions cannot be compensated at all, such as sending an email. Put those at the end, after the steps that can fail.

Sources

Practise it in the Sagas lab, or open this question on its own page.

Q2JuniorCompare orchestration and choreography for a saga.

With orchestration, one coordinator sends a command to each service, waits for the reply and decides what comes next. The flow is in one place, so it is easy to read, test and resume. The cost is an extra component and more messages, and the coordinator must be durable.

With choreography, each service does its step and publishes an event, and the next service reacts. There is no central owner, and services are loosely coupled. The cost is that the flow lives across many subscribers. It is hard to see where a saga is, and cycles of events are easy to create.

A fair rule is choreography for a few steps, orchestration once the flow has branches or many services.

Sources

Practise it in the Sagas lab, or open this question on its own page.

Q3JuniorWhat is a saga?

A saga is a long transaction split into a sequence of local transactions. Each local transaction commits on its own in one service. Each has a compensating action that undoes its effect.

If every step succeeds, the saga is done. If one fails, the compensations of the earlier steps run in reverse order.

The trade-off is that a saga is atomic in the end but not isolated. Other work can see the steps while the saga is running.

Sources

Practise it in the Sagas lab, or open this question on its own page.

Q4MidWhy must saga steps and compensations be idempotent?

Messages are delivered at least once, and an orchestrator that crashes does not know whether its last command ran. It sends it again. If the step is not safe to repeat, the customer is charged twice, or a refund is paid twice.

Make each step take an identifier, usually the saga id plus the step number, and remember it. A repeat then returns the first result. A compensation also has a case to handle: it can arrive for a step that never ran, if the request was lost. It should record that and do nothing.

Sources

Practise it in the Sagas lab, or open this question on its own page.

Q5MidWhat isolation anomalies can a saga show, and how do you reduce them?

Because each step commits at once, others see the middle. A reader can see a charge that a later failure refunds, a dirty read in effect. Two sagas can touch the same record, and one can overwrite what the other relied on, a lost update. A saga can also read one value twice and get two answers.

Countermeasures include a semantic lock, which is a pending flag that other code must respect. Commutative updates, so order does not matter. A pessimistic order of steps, so the hardest to undo comes last. Re-reading a value before a step relies on it, and versioning records.

Each one pushes work onto the application. Say that the saga's isolation is something you build, not something you get.

Sources

Practise it in the Sagas lab, or open this question on its own page.

Q6MidA saga has done three of five steps and step four fails. What happens next, and what if a compensation fails too?

The saga runs the compensations for steps three, two and one, in reverse order. When they finish, the saga ends as compensated.

A compensation that fails is retried. It must be safe to repeat, so give it an idempotency key. If it keeps failing, the saga cannot finish by itself. Park it, raise an alert, and let a person or a repair job decide. Compensations should be written so they cannot fail for business reasons, only for transient ones.

The orchestrator must write its progress durably before each step. After a crash, it reads where the saga stood and carries on.

Sources

Practise it in the Sagas lab, or open this question on its own page.

Q7SeniorDesign a saga for placing an order: reserve stock, charge the card, create the shipment. Where does it get hard?

Order the steps by how hard they are to undo. Reserve stock first, since a reservation is cheap to release. Charge the card next. Create the shipment last, because a shipment is the hardest to take back.

Use an orchestrator that persists its state. Give each step and each compensation an idempotency key. Mark the order pending, as a semantic lock, so the user and other code see that it may change. Set a deadline per step and a retry limit, then park the saga for a person.

The hard parts: a charge that succeeded but whose reply was lost, so the saga must look up the payment before compensating. A reservation that expires while the charge is slow. A compensation that fails for good. Name each, and say what you would monitor, such as the count of parked sagas and their age.

Sources

Practise it in the Sagas lab, or open this question on its own page.

Q8SeniorWhen would you choose a saga over two-phase commit, and when the reverse?

Choose a saga when the steps are in separate services or organizations, take long, or call things that cannot join a transaction, such as a payment provider. A saga holds no locks across steps, so one slow step does not block others, and no service waits for a coordinator.

Choose two-phase commit when the participants are databases under one team, the transaction is short, you need real isolation, and compensation would be awkward. A money transfer between two shards of one store is an example.

The trade-off is isolation against availability. Two-phase commit gives strong isolation and blocks. A saga stays available and makes the application deal with the anomalies.

Sources

Practise it in the Sagas lab, or open this question on its own page.

Idempotency and the outbox

8 questions · Read the lesson

Q1JuniorWhat is the dual-write problem?

A service must update its database and also publish an event. These are two calls to two systems with no shared transaction. If the service crashes between them, one happened and the other did not.

If it writes the row and then crashes, the event is lost, and no one downstream hears about the order. If it publishes first and then fails to write, the event describes something that never happened. Retrying does not fix it, because the service no longer knows what it finished.

Sources

Practise it in the Idempotency and the outbox lab, or open this question on its own page.

Q2JuniorHow does an idempotency key stop a duplicate request?

The client generates a unique key for one logical operation and sends it with every attempt, including retries. The server stores the key with the result of the first run. If a request comes with a key it has seen, it returns the stored result and does nothing else.

The key must identify the operation, not the attempt. A new random key on each retry defeats it. Store the key and the effect in one transaction, so a crash cannot leave one without the other.

Sources

Practise it in the Idempotency and the outbox lab, or open this question on its own page.

Q3JuniorWhat does it mean for an operation to be idempotent?

Doing it more than once has the same effect as doing it once. Setting a field to 5 is idempotent. Adding 5 to it is not.

It matters because networks lose replies. A client that did not hear back cannot tell whether the request ran, so it retries. If the operation is idempotent, the retry is harmless. If not, the retry may charge a card twice.

HTTP defines some methods as idempotent, such as PUT and DELETE. A POST is not, so APIs that create things need an extra mechanism.

Sources

Practise it in the Idempotency and the outbox lab, or open this question on its own page.

Q4MidHow does the transactional outbox solve the dual-write problem?

The service writes the business row and an event row in the same local database transaction. They commit together or not at all. A separate relay reads unsent rows from the outbox table and publishes them to the broker, then marks them sent.

The event can no longer be lost while the database survives, and it cannot describe a write that rolled back. The cost is delay, since the event goes out after the relay polls, and an extra table to prune.

The relay can crash after publishing and before marking, so the same event goes out again. The outbox gives at-least-once publication, and not more.

Sources

Practise it in the Idempotency and the outbox lab, or open this question on its own page.

Q5MidWhy is the outbox relay at least once, and what must the consumer do about it?

The relay publishes, then marks the row sent. These are two steps on two systems, so the dual-write problem appears again inside the relay. If it crashes between them, it publishes the event again on restart. It cannot do better without a shared transaction with the broker.

So consumers must be idempotent. Each event carries a stable id. The consumer records the ids it has applied, in the same transaction as its effect, and drops an id it has seen. That turns at-least-once delivery into effectively-once processing.

Ordering is a related point. Publish events for one entity in the order of the outbox, and key the partition by entity.

Sources

Practise it in the Idempotency and the outbox lab, or open this question on its own page.

Q6MidHow long should you keep idempotency keys, and what goes wrong if you drop them too soon?

Keep a key at least as long as the longest period a client can retry the same operation, plus the time a request can sit in a queue. A common choice is a day.

If the key expires before a late retry arrives, the retry looks new and runs again. That is a duplicate. A key table that grows without end costs storage and index size, so expiry is needed, and the lifetime is a trade between table size and how late a retry can safely be.

Also decide what a repeat does while the first request is still running. Return a conflict, or wait for it, but do not run it twice.

Sources

Practise it in the Idempotency and the outbox lab, or open this question on its own page.

Q7SeniorTwo requests with the same idempotency key arrive at the same time. How do you make sure only one runs?

A check and then an insert is a race. Both can see no key and both proceed. Make the database enforce it. Insert the key with a unique constraint as the first step of the transaction. The loser gets a conflict.

Then decide what the loser does. It can wait and return the winner's stored result, or return a conflict status that tells the client to retry later. Store a state with the key: in progress or done, along with the result. A crashed winner leaves a key stuck in progress, so give it a lease or a timeout after which another request may take over.

Also store a hash of the request. The same key with a different body is a client bug, and should be rejected rather than answered with the old result.

Sources

Practise it in the Idempotency and the outbox lab, or open this question on its own page.

Q8SeniorDesign a flow so an order is created once and its event is processed once, with retries at every hop. What does each layer need?

The client sends an idempotency key with the order. The API stores the key, the order row and an outbox row in one transaction. A retry returns the stored result, and a late retry after key expiry is the known gap.

The relay publishes outbox rows at least once, with a stable event id. The consumer applies each event and records its id in the same transaction as its effect, so a repeat does nothing.

Each layer makes its own retry safe. No layer can promise exactly once alone. The system gets the effect of exactly once from at-least-once delivery plus idempotent handling. List the leftovers: keys that expire, an outbox that grows if the relay stalls, and a consumer table to prune. Monitor relay lag and the age of the oldest unsent row.

Sources

Practise it in the Idempotency and the outbox lab, or open this question on its own page.

CDNs and edge caching

8 questions · Read the lesson

Q1JuniorWhat is a cache hit ratio, and what moves it?

It is the share of requests the cache answers without going to the origin. A higher ratio means less origin load and lower latency.

Three things move it most. A longer TTL lets each copy serve more requests. A cache key that holds only what changes the response lets requests share copies. Skewed traffic, where a few objects are very popular, gives caches more repeats to answer.

Spreading the same traffic over more caches lowers it, since each cache sees fewer repeats.

Sources

Practise it in the CDNs and edge caching lab, or open this question on its own page.

Q2JuniorWhat does the TTL on a cached response trade off?

It trades origin load against freshness. A longer TTL means a copy serves more requests before it expires, so the origin does less work. It also means the copy can outlive a change at the origin, and users see old content.

A good answer gives a way to pick. Content that never changes, such as a versioned script, can have a very long TTL. A page that changes often needs a short TTL, a purge, or both.

Sources

Practise it in the CDNs and edge caching lab, or open this question on its own page.

Q3JuniorWhat does a CDN do, and why does it help?

A CDN runs caches in many places, called edges, in front of your origin. A user's request goes to a nearby edge. If the edge has a fresh copy it answers at once. If not, it asks the origin, keeps the reply and answers.

It helps in two ways. Users get answers from a short distance, so latency falls. The origin sees only the misses, so its load grows much more slowly than traffic.

The trade-off is that copies can be out of date, so you set rules for how long they may be reused.

Sources

Practise it in the CDNs and edge caching lab, or open this question on its own page.

Q4MidWhat is a cache key, and how can a bad one hurt a CDN?

The key is what a cache uses to decide two requests want the same object. It is usually the host and path, plus any request headers the response depends on, which a server names with the Vary header.

A key that includes a value that changes per request, such as a tracking parameter, turns one object into many entries. Each needs its own miss. The hit ratio falls and origin load rises, while users ask for the same things.

The fix is to list the parameters and headers that matter and ignore the rest. Add a Vary header only when the body really differs, since each one multiplies the entries.

Sources

Practise it in the CDNs and edge caching lab, or open this question on its own page.

Q5MidHow do you keep content fresh at the edge: a short TTL, a purge, or versioned file names?

A short TTL is the simplest. It bounds staleness and sends more traffic to the origin all the time.

A purge deletes copies when the content changes. You keep a long TTL and still get fresh content. The cost is an extra system that must reach every cache, and a purge that misses one edge leaves an old copy there until its TTL ends. Keep a TTL as a safety net.

Versioned names put a hash in the file name. A new version is a new key, so the old copy can be cached for a very long time and never needs a purge. It fits files that pages reference. It does not fit the page itself, which needs a fixed address.

Sources

Practise it in the CDNs and edge caching lab, or open this question on its own page.

Q6MidWhat does stale-while-revalidate do, and what does it cost?

It lets a cache answer with an expired copy for a short window after expiry, while it refreshes the copy in the background. Users do not wait for the origin on the request that finds the copy expired.

The cost is that a user may see a copy that is slightly old. The origin load does not fall, because the refresh still happens. What changes is who waits for it.

A related directive, stale-if-error, lets a cache serve an old copy when the origin is failing, which keeps a site up through a short outage.

Sources

Practise it in the CDNs and edge caching lab, or open this question on its own page.

Q7SeniorA new page goes live and a million users ask for it within a minute. How do you protect the origin?

The risk is that every edge misses on the new object at once, and the origin sees a burst of identical requests.

A good answer combines several tools. Collapse concurrent misses at each edge, so one request goes to the origin and the others wait for it. Add a shield so that edges share one fetch. Warm the cache before launch by requesting the object through the CDN. Give the response a TTL that suits the content and use stale-while-revalidate so that refreshes do not block users.

Then say what you would watch: origin request rate, hit ratio per object, and error rate. Name the trade-off. Collapsing makes waiting users share one slow fetch, so a slow origin slows them all, which is why you also set a timeout.

Sources

Practise it in the CDNs and edge caching lab, or open this question on its own page.

Q8SeniorWhat is an origin shield, and when would you add one?

It is a cache layer between the edges and the origin. Each edge that misses asks the shield first. If many edges miss on the same object, the shield sends one request to the origin and answers the rest from its copy.

Add one when many edges means many misses for the same object, which is common for long-tail content and for a new object that all edges request at once. It raises origin offload without changing each edge's hit ratio.

The costs are an extra hop on a double miss, one more layer to run and purge, and a single region that every miss passes through. A shield placed far from the origin can add latency, so put it near the origin.

Sources

Practise it in the CDNs and edge caching lab, or open this question on its own page.

DNS and traffic steering

8 questions · Read the lesson

Q1JuniorWhat are A, AAAA and CNAME records, and why does a CNAME matter for a CDN?

An A record maps a name to an IPv4 address. An AAAA record maps it to an IPv6 address. A CNAME says one name is an alias for another, and the resolver then looks up the target.

A CDN usually asks you to point your name at one of its names with a CNAME. The CDN can then change the addresses behind its name for steering and failover without you touching your zone. A CNAME cannot sit at the zone apex beside other records, so providers offer an alias feature for the apex.

Sources

Practise it in the DNS and traffic steering lab, or open this question on its own page.

Q2JuniorWhat happens when a client looks up a name?

The program asks the operating system, which passes the question to a recursive resolver. If the resolver has a fresh cached answer, it replies. If not, it asks a root server which servers handle the top-level domain, asks those which servers handle the zone, and asks the zone's authoritative server for the record. It caches the reply and returns it.

Caching at the resolver and at the operating system means most lookups never reach the authoritative server. Each record carries a time to live that limits how long a cache may reuse it.

Sources

Practise it in the DNS and traffic steering lab, or open this question on its own page.

Q3JuniorWhat is a DNS TTL, and what do short and long values trade off?

The TTL is the number of seconds a cache may reuse a record. After that it must ask again.

A long TTL means fewer queries to the authoritative servers, faster lookups for users, and slower spread of a change. A short TTL means a change reaches users sooner and costs more queries and more lookup waits.

You choose the value before you need to change the record, because a cached answer cannot be recalled.

Sources

Practise it in the DNS and traffic steering lab, or open this question on its own page.

Q4MidYour health check removes a dead endpoint from DNS in 10 seconds. Why do users still fail for longer?

Resolvers cached the old answer, and they keep it until the TTL ends. A resolver that refreshed just before the change keeps the dead address for one full TTL. So the worst case is the detection time plus the TTL.

Some resolvers and applications hold answers longer than the TTL, so the real delay can be longer still.

To cut it, use a short TTL on records you may need to move, let clients retry another address when one fails, and put a load balancer or anycast address in front so that failover does not depend on caches.

Sources

Practise it in the DNS and traffic steering lab, or open this question on its own page.

Q5MidSome resolvers ignore your TTL. How does that change how you design failover?

It means the TTL is a request, not a guarantee. A share of users may keep a dead address for minutes however low you set it.

Design as if some users will be slow to move. Do not make DNS the only failover step. Keep the old endpoint serving or redirecting for a while after a move. Make clients try more than one address and fail fast. Use a stable front, such as an anycast address or a load balancer, so the address users hold does not have to change.

Measure rather than assume. Watch how long traffic keeps arriving at an old address after a change, and plan for that tail.

Sources

Practise it in the DNS and traffic steering lab, or open this question on its own page.

Q6MidHow does weighted DNS routing work, and how precise is it?

The authoritative server answers each query with endpoint A or B in set proportions. It is used to send a small share of traffic to a new version or to move load in steps.

It is coarse. The weight applies to queries, and a resolver caches its answer and serves every user behind it for the TTL. A large resolver sends all its users one way. With many resolvers and a short TTL the split comes close to the weight. With few large resolvers or a long TTL it can be far off.

For a precise split by request, use a load balancer or a service mesh.

Sources

Practise it in the DNS and traffic steering lab, or open this question on its own page.

Q7SeniorWhen would you use anycast instead of DNS steering, and what are its limits?

Anycast announces one address from many sites. The network sends each packet to the nearest announcement. Failover follows routing convergence, which is usually faster than waiting for caches to expire, and no resolver holds a stale answer because the address does not change.

It suits short, stateless exchanges, such as DNS itself, and fronts that terminate connections near the user and forward them. Many designs use DNS for the name and anycast for a stable address.

The limits are that routing cost is not always the fastest path, a route change can move a user to another site mid-connection and reset a long TCP connection, and it balances by geography rather than load. A site under overload must withdraw its announcement to shed traffic.

Sources

Practise it in the DNS and traffic steering lab, or open this question on its own page.

Q8SeniorHow does latency-based DNS routing choose an endpoint, and where can it go wrong?

The provider measures delay from regions to endpoints and answers each query with the endpoint that looks fastest for the asker's region.

The authoritative server sees the resolver, not the user. If a user is far from the resolver, the choice fits the resolver's location. The EDNS Client Subnet extension passes part of the client address to help, and not every resolver sends it.

Other problems follow. The table of delays goes stale, the answer is cached for the TTL, and the choice ignores load, so the nearest endpoint can be the one that is overloaded. Combine it with health checks and capacity limits.

Sources

Practise it in the DNS and traffic steering lab, or open this question on its own page.

Connections and head-of-line blocking

8 questions · Read the lesson

Q1JuniorWhy does a new HTTPS connection take time before the first request?

TCP needs one round trip to set up the connection. TLS needs more round trips to authenticate the server and agree on keys. With TLS 1.3 it is one, so a new connection needs two round trips before the request can be sent.

At a 50 ms round trip that is 100 ms of setup. This is why clients reuse connections, and why QUIC, which combines the transport and encryption handshakes, needs one round trip.

Sources

Practise it in the Connections and head-of-line blocking lab, or open this question on its own page.

Q2JuniorWhat is HTTP/2 multiplexing and what problem does it solve?

HTTP/2 splits one connection into streams. Many requests and responses are in flight on the same connection at once, with their frames interleaved.

With HTTP/1.1 a connection serves one request at a time, so a client needs many connections for parallelism, and requests wait when they are all busy. Multiplexing removes that wait, needs fewer connections and fewer handshakes, and lets header compression work across requests.

Sources

Practise it in the Connections and head-of-line blocking lab, or open this question on its own page.

Q3JuniorWhy do clients keep a pool of connections, and what is the risk of getting its size wrong?

A pool lets requests reuse open connections, so most requests skip the handshake. It also bounds how many connections a client holds.

Too small and requests wait for a free connection, which shows up as queueing and high tail latency. Too large and it wastes memory and file descriptors on both ends, and the sum across many clients can overload a server or a database behind it.

Size it from the request rate and how long a connection is busy, and add headroom for bursts.

Sources

Practise it in the Connections and head-of-line blocking lab, or open this question on its own page.

Q4MidAn HTTP/1.1 client sends 200 requests a second and each takes 90 ms. How do you size the pool?

Use the rate times the time in the system. 200 per second times 0.09 seconds is 18 requests in service at once, so the pool needs at least 18 connections. Add headroom for bursts and slower responses, so a size near 24 is reasonable.

Below the needed size, the queue grows without bound while the load lasts, and latency climbs with it. Above it, extra connections cost memory. The shortfall matters more than the surplus.

Also say that this is an average. Check the 99th percentile, and watch the queue length, because it shows the problem first.

Sources

Practise it in the Connections and head-of-line blocking lab, or open this question on its own page.

Q5MidHow does QUIC avoid transport-level head-of-line blocking?

QUIC runs over UDP and has streams built into the transport. Each stream has its own ordering and its own retransmission. When a packet is lost, only the streams whose data it carried wait. Data for other streams is delivered as soon as it arrives.

HTTP/3 maps HTTP onto QUIC streams. The stream that lost a packet still pays for the retransmit, so the cost is not zero. Other streams are no longer held back by it.

QUIC also combines the transport and TLS handshakes, so a new connection needs one round trip.

Sources

Practise it in the Connections and head-of-line blocking lab, or open this question on its own page.

Q6MidWhat is head-of-line blocking in TCP, and why does it hurt HTTP/2?

TCP hands the application one ordered stream of bytes. If a packet is lost, later packets may arrive, but TCP cannot deliver them until the lost one is retransmitted.

HTTP/2 puts many streams on that one byte stream. A lost packet carrying data for one stream holds back every other stream on the connection, even though their data arrived. The more streams share the connection, the more requests a single loss delays.

On a clean network it rarely matters. On a lossy one, such as mobile, it can make HTTP/2 slower in the tail than several HTTP/1.1 connections.

Sources

Practise it in the Connections and head-of-line blocking lab, or open this question on its own page.

Q7SeniorTail latency doubled after a client moved from HTTP/1.1 to HTTP/2 over a lossy mobile network. How do you investigate?

Start from the likely cause. HTTP/2 moved many requests onto few connections. On a lossy path, each loss now stalls every stream on its connection, so the tail got worse even if the median improved.

To confirm, compare the tail by loss rate or by network type. Look at retransmit counts and at the share of requests that finished late without a loss of their own, if you can measure it. Check the pool: how many connections, and how many streams each carried.

Then choose a fix. Use more connections, test HTTP/3 where UDP is available, or cut response sizes so fewer packets are in flight. Name the trade-off for each. More connections cost handshakes and fairness, HTTP/3 costs CPU and needs a fallback, and smaller responses cost development effort.

Sources

Practise it in the Connections and head-of-line blocking lab, or open this question on its own page.

Q8SeniorUnder packet loss, would you use one HTTP/2 connection or several? What about HTTP/3?

One HTTP/2 connection maximizes the effect of head-of-line blocking, since a loss stalls every stream. Several connections limit the damage, because a loss stalls only its own connection. The price is more handshakes, more memory and weaker congestion control, since each connection competes with the others.

A moderate pool, such as a handful of connections spread across streams, is a common middle path when loss is real. Measure the tail latency under your actual loss rate and choose from the data.

With HTTP/3 the need falls, because a loss delays only one stream. One connection is usually enough. Say what you would check: UDP is allowed on your network paths, CPU cost of user-space QUIC, and a fallback to HTTP/2 when UDP is blocked.

Sources

Practise it in the Connections and head-of-line blocking lab, or open this question on its own page.

URL shortener

8 questions · Read the lesson

Q1JuniorHow long should a short code be, if it uses letters and digits?

Letters in both cases and digits give 62 symbols. Six characters give 56 billion codes and seven give 3.5 trillion.

Pick a length so the number of links you expect is a tiny share of the space. Random codes also need a collision check, so extra room keeps retries rare. The trade-off is a longer link.

Sources

Practise it in the URL shortener lab, or open this question on its own page.

Q2JuniorEstimate the load for a service that makes 100 million links a month.

A month is about 2.6 million seconds, so 100 million links is about 40 creations a second. If reads are 100 times writes, that is about 4,000 redirects a second on average, and a peak of several times that.

Storage is the other number. Five years of links is 6 billion records. At 500 bytes each that is about 3 terabytes. State your assumptions and invite the interviewer to change them.

Sources

Practise it in the URL shortener lab, or open this question on its own page.

Q3JuniorWhat does a URL shortener do, and what are its two main operations?

It maps a short code to a long address. The two operations are create, which takes a long address and returns a code, and redirect, which takes a code and sends the user to the long address.

The store behind it is a key-value table keyed by code. Reads far outnumber writes, so a good answer says so early and plans a cache.

Sources

Practise it in the URL shortener lab, or open this question on its own page.

Q4MidHow do counter ranges let many servers make codes without a central bottleneck?

A coordinator hands each creation server a block of numbers, for example a million at a time. The server uses the block alone and writes each number in base 62. It asks for a new block when the old one runs out.

Coordination happens once per block, not once per link. The blocks must never overlap, so the coordinator needs durable state or a lease. A crash wastes the rest of a block, which is harmless.

The downside is that codes are sequential and guessable. A reversible scramble hides the order without making it secret.

Sources

Practise it in the URL shortener lab, or open this question on its own page.

Q5MidWhat are the strengths and weaknesses of making a code by hashing the long address?

The same address always gives the same code, so duplicates are free and no coordination is needed.

Two different addresses can share a short prefix of the hash, so collisions still need a check and a re-hash with a salt. The scheme also cannot give two users separate links to one address unless the user is part of the hash input. A secure hash does not help guessability if the code is short.

Sources

Practise it in the URL shortener lab, or open this question on its own page.

Q6MidWhy do random short codes collide, and how do you handle it?

Random draws collide by the birthday bound. A repeat becomes likely after about the square root of the code space, long before the space is full.

Handle it with a check on write. Make the code the primary key and let the insert fail on a duplicate, then draw a new code. That removes the race between two servers that drew the same code.

Set a retry limit. If retries keep failing, the code length is too small for the table, and the fix is a longer code.

Sources

Practise it in the URL shortener lab, or open this question on its own page.

Q7SeniorCompare a 301 and a 302 redirect for a short link service.

A 301 says the move is permanent. Browsers and caches may remember it and skip the server next time. That cuts load and latency.

A 302 says the move is temporary, so each click returns to the server. That keeps click counts, allows a link to expire or change its target, and costs more traffic.

If analytics or edits matter, use a 302, perhaps with a short cache lifetime. If links are permanent and cost matters most, a 301 works. The trade-off is load against control.

Sources

Practise it in the URL shortener lab, or open this question on its own page.

News feed

8 questions · Read the lesson

Q1JuniorWhat does a pull feed cost per read, and what does it save?

A read fetches recent posts from every account the reader follows. With 200 follows that is up to 200 lookups, which are best done in parallel and from a cache.

It saves write work. A post is one write, no matter how many followers it has, and inactive users cost nothing.

Sources

Practise it in the News feed lab, or open this question on its own page.

Q2JuniorWhat does a push feed cost per post?

One write for each follower of the author. An account with 200 followers costs 200 inserts and an account with 10 million followers costs 10 million.

The average can look fine while single posts are huge. A good answer names the tail, not only the mean.

Sources

Practise it in the News feed lab, or open this question on its own page.

Q3JuniorWhat is a news feed, and what are the two basic ways to build one?

A feed shows a reader the recent posts of the accounts they follow, newest first.

Fan-out on write, or push, copies each new post into the inbox of every follower. Reads are one lookup. Fan-out on read, or pull, builds the feed when it is opened by fetching recent posts from each followed account. Writes are cheap and reads are heavier.

Sources

Practise it in the News feed lab, or open this question on its own page.

Q4MidWhat is the celebrity problem and how does a hybrid feed solve it?

A push post costs one insert per follower. An account with millions of followers floods the writers, and posts behind it in the queue are delayed.

A hybrid pushes accounts below a follower threshold and does not push accounts above it. At read time the service reads the reader's inbox, pulls the latest posts of the celebrities the reader follows and merges by time.

Writes are bounded by the threshold. Reads are bounded by the number of celebrities followed. The threshold sets the balance.

Sources

Practise it in the News feed lab, or open this question on its own page.

Q5MidEstimate the write load of a push feed with 10 million daily users, one post a day each and 200 follows on average.

About 10 million posts a day is about 115 posts a second. Each makes 200 inserts, so about 23,000 inserts a second on average.

Reads are higher. If each user opens the feed ten times a day, that is about 1,200 reads a second. The average write load is fine. The celebrity case is what needs a design.

Sources

Practise it in the News feed lab, or open this question on its own page.

Q6MidHow should a feed be paginated?

Use a cursor, not a page number. New posts arrive at the front, so a page number shifts and the next page repeats or skips items.

The cursor names the last item the reader saw, as a time and an id, and the next request asks for older items. Include the id because two posts can share a time. Keep the cursor opaque so you can change it. Refresh asks for items newer than the newest the client holds.

Sources

Practise it in the News feed lab, or open this question on its own page.

Q7SeniorWhat do you store for a feed, and what happens when an inbox is lost?

Store post ids, not posts, in a capped list per reader, ordered by time. Posts live once in a partitioned post store, so an edit or delete changes one place. A read fetches ids, then batches the post lookups.

The inbox is a cache of work you can redo. If it is lost, rebuild it by pulling from the follow graph. That lets the inbox store be fast and cheap and not strongly durable.

Skip inbox writes for users who have been away, and rebuild on return.

Sources

Practise it in the News feed lab, or open this question on its own page.

Q8SeniorHow would you choose the celebrity threshold, and what happens when an account crosses it?

Start from two budgets. The write side: how many inserts one post may cost before it delays others. The read side: how many extra pulls a read can afford. The threshold is where those meet. Lowering it makes writes cheaper and reads slower.

Activity can matter too. A very active account with moderate followers can be pulled, and a quiet one with many followers can be pushed.

When an account crosses, switch it to pull for new posts and leave old copies. Filter at read time for deletes and unfollows.

Sources

Practise it in the News feed lab, or open this question on its own page.

Chat system

8 questions · Read the lesson

Q1JuniorHow does a chat server deliver a message to a user who is not making a request?

The user keeps a persistent connection open to the server, usually a WebSocket. The server writes the message to that connection when it arrives.

A normal request and response cannot do this, because the client has to ask first. The server therefore needs to track which connection belongs to which user.

Sources

Practise it in the Chat system lab, or open this question on its own page.

Q2JuniorWhat is a gateway server in a chat system?

A server that holds many long-lived client connections and forwards messages between them and the services behind it. It does little work per message, so one machine can hold a very large number of idle connections.

Keeping it thin lets you scale connection count separately from business logic. It holds state, which is who is connected, so a crash drops its users.

Sources

Practise it in the Chat system lab, or open this question on its own page.

Q3JuniorHow do you keep chat messages in order?

Give each message a sequence number per conversation, assigned by the server when it accepts the message. Clients sort by that number.

Do not order by client clocks. They disagree. A single writer per conversation gives a simple total order.

Sources

Practise it in the Chat system lab, or open this question on its own page.

Q4MidThe server resends a message when it gets no ack. How do you avoid showing it twice?

The server cannot tell a lost message from a lost ack, so it resends in both cases. That is at-least-once delivery.

The client keeps the sequence numbers it has and drops a message it already holds. For messages the client sends, a client-made message id lets the server drop a repeat. The result looks like exactly once, built from at-least-once delivery and a duplicate check.

Sources

Practise it in the Chat system lab, or open this question on its own page.

Q5MidEstimate the gateways you need for 5 million concurrent users.

If one gateway holds about 100,000 idle connections, 5 million users need about 50 gateways, plus spare capacity for a crash and for peak load.

Check the other limits too. Keepalives every 30 seconds on 5 million connections are about 170,000 small messages a second. Memory per connection and buffers usually set the cap, not CPU.

Sources

Practise it in the Chat system lab, or open this question on its own page.

Q6MidHow do delivery and read receipts work?

Sent means the server stored the message. Delivered means the recipient's device acknowledged it. Read means the recipient opened the conversation.

A read receipt can carry a sequence number meaning read up to here, so one receipt covers all earlier messages and a lost one is fixed by the next. Store only the highest number per user per conversation, and batch the writes.

Sources

Practise it in the Chat system lab, or open this question on its own page.

Q7SeniorHow do you deliver messages to a user who is offline?

Store each message first and treat the push to the connection as an optimisation. If the user has no connection, nothing else is needed.

On reconnect the client reports the last sequence number it holds for each conversation. The server returns everything after it, in order. This is the same range read as history, so there is no per-user queue.

For a phone with the app closed, send a small notice through the platform push service and let the app fetch by sequence number.

Sources

Practise it in the Chat system lab, or open this question on its own page.

Q8SeniorHow would you design presence, and what would you not guarantee?

Use a heartbeat with an expiry. A connected client pings every so often, and the server records online with a lifetime a little longer than the interval. When pings stop, the entry expires and the user shows as offline.

The expiry is a failure detector, so it trades speed against false offline marks. Do not broadcast every change to every contact. Send presence only for open conversations, and only on change, and accept delays of seconds.

Presence can be late and approximate. Messages and their order cannot.

Sources

Practise it in the Chat system lab, or open this question on its own page.

Your progress is saved in this browser. Sign in to keep it on every device. Privacy · Terms