All modules

Case studies: interview questions

19 questions. Try answering out loud before you open the model answer.

1. In a URL shortener, how do you generate short codes so two servers never issue the same one?

Seniorid-generationurl-shortener

What the interviewer is really testing

Whether you can get uniqueness across many stateless servers without putting a coordination call on every write, and whether you see the security side of predictable identifiers.

Show the model answer, follow-ups and checklist

Model answer

I would compare three options and pick one.

Random 7-character codes with a conditional write are the simplest. With 3.5 trillion possible codes and 6 billion links, a collision is rare, and “put if absent” turns one into a cheap retry. No coordination is needed.

A counter encoded in base 62 can never collide, so the write needs no check at all. The problem is where the counter lives. A database sequence called on every request is a bottleneck and a single point of failure.

The fix is range leasing. Each API server asks an allocator for a block of a million IDs, then issues them from memory. The allocator is one row in a consistent store, incremented once per million writes, so its load is negligible and servers keep working for hours if it is down. Unused IDs from a crashed server are skipped.

Because sequential IDs are guessable, I would scramble the counter with a reversible function before encoding it, which keeps uniqueness and hides the order.

Custom aliases go in the same table through a conditional write that returns 409 on conflict, with a naming rule that keeps them apart from generated codes.

I would choose leased ranges with a scramble, and say that random codes are a reasonable alternative if the team prefers fewer moving parts.

Likely follow-ups

A server crashes after leasing a range of one million IDs and using ten. What happens to the rest?
They are abandoned. The ID space is in the trillions, so gaps are free, and not reclaiming ranges keeps the allocator a single counter.
How big should the leased range be?
Big enough that the allocator is called rarely and servers survive an allocator outage, small enough that a crash wastes little. At tens of writes per second per server, a million IDs lasts hours.
Users complain that links are guessable. How do you fix it without losing uniqueness?
Apply a bijection to the counter before encoding, such as a Feistel network over the code space. Distinct inputs still map to distinct outputs, but consecutive IDs no longer look consecutive.
Why not hash the long URL and take the first seven characters?
Truncated hashes collide long before the space is full, so every write needs a lookup and retry. It also forces two users shortening the same URL to share one code and one set of analytics.

Common mistakes

  • Calling a central counter on every request and not noticing it is a bottleneck and a single point of failure.
  • Using a truncated hash and ignoring collisions.
  • Using UUIDs, which are unique but far too long to be a short code.
  • Forgetting custom aliases share the namespace with generated codes.

A strong answer includes

  • Compares at least two approaches (hash, random, counter) with their costs
  • Removes per-write coordination, usually with leased ranges
  • Explains what happens to unused IDs on a crash
  • Addresses guessability
  • Handles custom aliases with a conditional write
  • Sizes the code space against the expected number of links

Revise: Design a URL shortener

2. The Redis cluster behind your rate limiter becomes unreachable. What happens to API traffic?

Seniorrate-limitingfailure-modesredis

What the interviewer is really testing

Whether you treat the limiter as a dependency that can fail, choose fail-open or fail-closed per rule with a reason, and keep some protection in place while the store is down.

Show the model answer, follow-ups and checklist

Model answer

The first thing is to notice quickly. The gateway calls Redis with a timeout of a few milliseconds and a circuit breaker. A dead Redis then costs each request at most that timeout, and once the breaker opens, nothing at all.

What the gateway does next depends on what each rule protects, so I would make it a per-rule setting.

Rules that protect capacity fail open. If the general “1,000 requests a minute per API key” rule cannot be checked, the request is allowed. Rejecting everything would turn a limiter outage into an API outage, which is worse than the abuse the limiter exists to prevent. But failing open should not mean unlimited. Each gateway falls back to an in-memory token bucket set to the limit divided by the number of gateways. It is inaccurate, and it still stops one client from sending fifty times its share.

Rules that are security or cost controls fail closed. Login attempts, one-time code checks and SMS sends are rejected, usually with a 503, while the store is down. Failing open there gives an attacker unlimited password guesses for as long as the outage lasts.

Two more points. First, fail-open means the limiter is not the last line of defence, so backends still need their own concurrency limits and load shedding. Second, recovery needs care: when Redis returns, counters are empty, every client has a full bucket, and gateways should reconnect gradually.

I would alert on the fail-open rate. A limiter that has been quietly failing open for a week is the same as having no limiter.

Likely follow-ups

Redis is not down, just slow, with p99 at 50 ms. What changes?
Slow is worse than dead, because every request waits. A timeout of a few milliseconds turns slow calls into failures, and a circuit breaker stops sending them once the error rate is high. After that the same fail-open or fail-closed policy applies. Without the timeout, the limiter adds 50 ms to every API call and can exhaust the gateway's connection pool.
How does the local fallback limiter know its share of the limit?
It divides the limit by the number of gateway instances, taken from service discovery or configuration. Traffic is never perfectly even, so some clients are rejected a little early and others get a little extra. That is acceptable for an emergency ceiling that is not the normal path.
What happens at the moment Redis comes back?
The counters are gone or stale, so every client starts with a full bucket and can burst once. That is within each client's limit, so it is tolerable. The breaker should close gradually, with a few probe requests first, so that all gateways do not reconnect and flood Redis in the same second.
Would you replicate the counters synchronously so a failover loses nothing?
No. A lost counter costs a few extra requests for one client, while synchronous replication would add latency to every request for every client. An asynchronous replica that can be promoted quickly is the right trade.

Common mistakes

  • Answering that Redis is highly available and never saying what happens when it is not.
  • Choosing fail-open or fail-closed for the whole system instead of per rule.
  • Failing open with no fallback, so a limiter outage removes all protection at once.
  • Calling Redis with no timeout, so a slow store adds its latency to every request.
  • Forgetting that limits on login and one-time codes are security controls.

A strong answer includes

  • Tight timeout and circuit breaker on the call to the counter store
  • Fail open for rules that protect capacity, with the reason
  • Fail closed for security or cost-sensitive rules, with examples
  • A local in-memory fallback limit on each gateway
  • Backends have their own overload protection
  • Describes recovery, including lost counters and reconnection
  • Alerts on the rate of fail-open decisions

Revise: Design a rate limiter

3. A customer's limit is 1,000 requests a minute and you serve them from three regions. How do you enforce it?

Staffrate-limitingmulti-regionconsistency

What the interviewer is really testing

Whether you see that an exact global count and a fast local decision pull against each other, can put a number on the overshoot of each option, and choose according to what the limit is for.

Show the model answer, follow-ups and checklist

Model answer

I would first ask what the limit is for. If it protects our capacity, approximate is fine. If it is a contractual quota that we bill against, it must be exact, but it does not have to be exact inline.

There are three designs.

Independent regional limits. Each region has its own counters and enforces the full 1,000. The worst case is 3,000 a minute if the customer spreads traffic evenly. In practice routing sends most customers to one region. There is no cross-region dependency at all.

One global counter. Every region checks a counter in one home region. It is exact, and every request from the other two regions pays a cross-region round trip, tens of milliseconds or more, and fails when the home region does. I would not put that on the request path.

Local enforcement with shared usage. Each region counts locally and publishes per-key usage to the others about once a second. A region allows a request if its local count plus the last known remote usage is under the limit. Overshoot is bounded by what the other regions admit in one sync interval. At 1,000 a minute, about 17 a second, that is a few tens of requests in the worst case.

I would run the first design by default and the third for customers large enough to matter. The usage messages carry absolute per-region counts for the window, not deltas, so a retried message cannot double-count.

For a billed quota I would keep the inline limiter approximate and meter from a durable log of requests. The limiter is a guard, and the ledger is a separate system.

Likely follow-ups

What happens to the usage-sharing design during a partition between regions?
Each region stops hearing about the others' usage and enforces against what it last knew. Behaviour degrades to independent regional limits, with a worst case of three times the limit. It keeps serving, which is the right choice, because a rate limit is not worth an outage. A metric should show that sync is stale.
Why not simply give each region a third of the limit?
It can never overshoot, but a customer whose traffic all arrives in one region is cut off at a third of what they are entitled to. Fixed shares only work if they follow demand, and making them follow demand means building the usage-sharing mechanism anyway.
The customer says they were rejected while under 1,000 a minute. How do you investigate?
Read the decision log, where each rejection records the rule, the region, the local count and the remote usage the region believed. Look for remote usage counted twice because a sync message was retried, for windows that are not aligned between regions, and for a different rule, such as a burst limit, being the one that fired.
Could the counter be a CRDT?
Yes. Use a grow-only counter per window with one slot per region. Each region increments only its own slot, merging takes the maximum of each slot, and usage is the sum. Duplicate or reordered sync messages are then harmless, which is exactly the property the sync needs.

Common mistakes

  • Putting a cross-region call on every request and not mentioning its latency or what happens when that region is down.
  • Assuming cross-region replication of Redis gives an exact shared count, when it is asynchronous.
  • Not asking whether the limit is overload protection or a billed quota.
  • Giving no number for the overshoot of the chosen design.
  • Sending usage deltas that are not idempotent, so a retried message double-counts.

A strong answer includes

  • Asks what the limit protects and how exact it must be
  • Gives the worst case for independent regional limits
  • Rejects a synchronous global counter on latency and availability grounds
  • Describes asynchronous usage sharing and bounds its overshoot by the sync interval
  • Says what happens in a partition
  • Separates billing-grade metering from the inline limiter
  • Makes the sync idempotent

Revise: Design a rate limiter

4. One node in your 24-node cache cluster dies at peak traffic. Walk me through what happens.

Seniorcachingconsistent-hashingfailure-modes

What the interviewer is really testing

Whether you follow a cache failure through to the database behind it, put a number on the extra load, and know the options (remap, replica, spare pool) and the stale-data trap when the node returns.

Show the model answer, follow-ups and checklist

Model answer

I would walk through it in time order.

First seconds. Requests routed to the dead node hang until they time out. That is one request in 24, so timeouts must be short, tens of milliseconds, and the proxy should stop sending to a node after a few consecutive failures. Otherwise application threads pile up waiting on a dead socket.

The map changes. The config service confirms the node is down and publishes a new cluster map. Without replicas, the node’s keys now belong to other nodes. With virtual nodes they spread over all 23 survivors.

The miss wave. About 4% of keys now miss. Say we serve 900,000 reads a second at a 95% hit rate: the database normally sees 45,000 reads a second, and it now sees roughly another 36,000. Losing 4% of the cache nearly doubles database load. This is the real incident. Hot keys refill within seconds and the long tail over minutes, so the load decays, but the first minute is the dangerous one. Coalescing concurrent misses for the same key keeps popular keys from multiplying the load.

The replacement. A new node joins empty and takes keys back from the others, which causes a second, smaller miss wave. I would move ring positions to it gradually.

What I would build depends on that 1.8 times figure. If the database has the headroom, remapping or a small spare pool is enough. If not, each primary gets an asynchronous replica that is promoted on failure, at double the memory cost. Either way, a node that returns after being out of the ring is flushed first, because it holds values that were deleted elsewhere while it was away.

Likely follow-ups

The database can only take 1.3 times its normal load. What do you change?
Remapping is no longer acceptable on its own, because the miss wave is about 1.8 times. Run a replica per primary so a failure loses no keys, or use more, smaller nodes so each failure loses a smaller share. Add a cap on concurrent database reads from cache misses, so the excess is shed or served stale instead of overloading the database.
The dead node comes back two minutes later with its memory intact. Is that good news?
No. For two minutes its keys were written and deleted on other nodes. When the ring hands those keys back, the node answers with values from before the outage, including ones that were explicitly invalidated. It has to be flushed before it serves, and then ramped in like a new node.
How do you detect the failure quickly without false alarms?
Two levels. Each proxy ejects a node for a few seconds after several consecutive timeouts, which protects requests straight away. The config service changes the cluster map only after its own health checks agree, and readmits a node only after several successes, so a brief blip does not move keys back and forth.
Why do virtual nodes matter in this failure?
With one ring position per node, all of the dead node's keys fall to a single neighbour, which doubles that node's load and evictions and can push it over too. With around 150 positions per node the keys spread across all 23 survivors, about 4% extra each.

Common mistakes

  • Stopping at "only 1/N of keys move" without asking what those misses do to the database.
  • Treating a cache failure as harmless because it is only a cache.
  • Letting a node rejoin with its old contents.
  • Long client timeouts, so a dead node stalls one request in 24 for seconds.
  • Forgetting the second wave of misses when the replacement node joins.

A strong answer includes

  • Short timeouts and fast ejection of the dead node
  • Puts a number on the extra database load
  • Names remap, replica and spare pool with their costs
  • Coalesces concurrent misses for the same key
  • Flushes a returning node before it serves
  • Ramps the replacement in gradually
  • Explains how virtual nodes spread the failed node's keys

Revise: Design a distributed cache

5. Your Dynamo-style store uses N=3, W=2, R=2. A client writes, gets success, reads the key back and sees the old value. How?

Staffquorumconsistencyreplication

What the interviewer is really testing

Whether you know what R + W > N really guarantees and can name the specific mechanisms that break it, instead of treating a quorum as strong consistency.

Show the model answer, follow-ups and checklist

Model answer

R + W > N guarantees one thing: any R of a key’s replicas include at least one of the W that acknowledged the write. Each cause below breaks one of the assumptions behind that sentence.

Sloppy quorum. If a home replica was unreachable, the write may have been acknowledged by replica A and a fallback node holding a hint. The read then asks B and C, and neither has it. The sets did not overlap because the write set was not drawn from the home replicas. It heals when the hint is replayed.

Last-write-wins with clock skew. The write was stamped by a machine whose clock is behind. Every replica accepted it, compared timestamps and kept the older value, which carries a later timestamp. The client was told “success” and the write is gone for good. This is the cause I would suspect if the stale read persists.

The read was not really R=2 over the same replicas. A default consistency level of one somewhere in the client, or per data centre quorums where the write met its quorum in one data centre and the read ran in another.

A ring change in progress. While a node is joining or being replaced, the three replicas the reader consults may not be the three the writer used.

Another writer. A concurrent write from a second client won, and what looks like the old value is actually theirs.

To find out which, I would trace both requests: the consistency levels used, which replicas answered, the timestamps stored with each version, and whether hints or topology changes were active at the time.

The fixes are specific. Use strict quorums where it matters, keep clocks synchronised and monitored, and for keys that need read-after-write guarantees every time, use a consensus-backed operation or a different store.

Likely follow-ups

With strict quorums and R + W > N, is the store linearizable?
No. A write that fails after reaching one replica can be returned by one read and missed by the next, and concurrent writes are ordered by timestamp, not by real time. Linearizable operations need consensus, which is why Cassandra offers Paxos-based lightweight transactions for the keys that need them.
How would you confirm the clock-skew theory?
Trace the write and compare the timestamp stored with each version against the real time of the requests, then check the clock offset on the node or client that assigned it. If the surviving old version carries a timestamp later than the new write, the new write lost on comparison. Fix the clock, then rewrite the value.
Would raising W to 3 fix it?
It would force every home replica to have the write, and it makes writes fail whenever any one replica is down, which gives away the availability the design exists for. It does nothing for clock skew. It is better to find the actual cause and fix that.
The client only needs to read its own writes. What is the cheapest way to provide that?
Handle it per session. The client keeps the version it last wrote and treats a read that returns an older version as stale, retrying against more replicas. That gives read-your-writes for that client without making the whole store strongly consistent.

Common mistakes

  • Saying it cannot happen because R + W > N.
  • Blaming replication lag in general without naming a mechanism.
  • Forgetting that last-write-wins depends on clocks.
  • Proposing W=3, R=3 without noticing the availability cost.
  • Confusing quorum overlap with linearizability.

A strong answer includes

  • States what quorum overlap guarantees and what it assumes
  • Explains sloppy quorums and hinted handoff as a cause
  • Explains last-write-wins with clock skew as a cause
  • Checks the consistency levels really used, including per data centre quorums
  • Mentions a ring change in progress
  • Says how to confirm the cause from traces and timestamps
  • Matches the fix to the cause

Revise: Design a key-value store

6. Your Snowflake-style ID generator's clock jumps back by two seconds. What happens, and what should the generator do?

Mid-levelid-generationclocksfailure-modes

What the interviewer is really testing

Whether you understand that uniqueness depends on a worker never reusing a timestamp, and can reason about detection, the restart case and prevention.

Show the model answer, follow-ups and checklist

Model answer

Each ID is a timestamp, a worker ID and a sequence number. It is unique only if a worker never uses the same timestamp and sequence twice. If the clock goes back two seconds and the generator carries on, it starts issuing IDs for milliseconds it has already covered, and the sequence restarts from zero in each of them. Any ID it issued in those two seconds can be issued again.

So the generator keeps the last timestamp it used and compares on every call. When the clock is behind that value it has three safe options.

  • Wait. For a gap of a few milliseconds, sleep until the clock catches up.
  • Refuse. For two seconds, return an error, fail the health check so the load balancer sends callers to other generators, and raise an alert. The original Snowflake did this.
  • Use a logical clock. Take the larger of the clock and the last timestamp, so time never goes backwards from the generator’s point of view. IDs stay unique and the time embedded in them runs up to two seconds ahead of the real time for a while.

I would wait for small gaps and refuse for large ones, because a clock that jumped by seconds is a sign of a sick machine and I want it out of the pool.

The harder case is a restart. The last timestamp lived in memory, so after a restart the check has nothing to compare against. The generator should persist a high-water mark periodically and, on startup, wait until its clock has passed it.

Prevention matters too: configure the time daemon to slew the clock instead of stepping it, and use a time source that smears leap seconds.

Likely follow-ups

The generator restarted during those two seconds. How does it know the clock went back?
It does not, unless the last timestamp was stored outside the process. The generator saves a high-water mark a few seconds ahead of the timestamps it is using, so there is no write per ID, and waits at startup until the clock has passed it. Taking a fresh worker ID on every start is another way out, at the cost of using up worker IDs faster.
Why do clocks go backwards at all?
NTP steps the clock when it has drifted too far to correct gradually, virtual machines resume from a pause or migration with a stale clock, operators set the time by hand, and a leap second repeats a second on systems that do not smear it. A monotonic clock never goes backwards, but it does not give a time that can be compared across machines.
Could the generator avoid depending on the wall clock?
Partly. It can read the wall clock once at startup and then advance by the monotonic clock, which cannot go backwards within a process. The embedded time then drifts slowly from real time, and the restart case still needs the persisted high-water mark.
Does refusing for two seconds hurt availability?
Only for that generator. With several per region behind a load balancer and callers that retry, nobody notices. If the generator is a library inside every application process, that process cannot create records for two seconds, and the logical clock approach becomes more attractive.

Common mistakes

  • Carrying on with the earlier time and assuming the sequence number will prevent collisions.
  • Assuming NTP guarantees that clocks never go backwards.
  • Forgetting that a restart loses the in-memory last timestamp.
  • Stopping every generator when only one has a bad clock.
  • Using these IDs to order events precisely across machines.

A strong answer includes

  • Explains why reusing a timestamp can duplicate an ID
  • Compares the clock with the last timestamp on every call
  • Waits for small gaps and refuses for large ones
  • Takes the node out of the load balancer and alerts
  • Persists a high-water mark for restarts
  • Mentions slewing and leap smearing as prevention
  • Notes that the logical clock option trades accurate embedded time for availability

Revise: Design a unique ID generator

Seniortypeaheadstream-processingcaching

What the interviewer is really testing

Whether you can add freshness without giving up the precomputed, immutable index that makes serving fast, and whether you think about caches and abuse once the feedback loop is short.

Show the model answer, follow-ups and checklist

Model answer

I would keep the daily index as it is and add a small overlay for trending queries. Rebuilding the whole index every few minutes means reprocessing a hundred million queries to change a few thousand, and updating the main trie in place puts writes and locking on a path that is fast because it is read-only.

Detect. A stream job consumes the query log and keeps counts per normalised query over a sliding window of the last five to ten minutes. It compares each count with that query’s usual rate. Ranking by raw count would only rediscover queries that are always popular, so what I want is the ratio to the baseline.

Filter. The same rules as the batch build, and stricter: a minimum number of distinct users, and the blocklist. A five-minute window has less evidence behind it and is a more attractive target.

Publish. The job writes an overlay of a few thousand rising queries with scores, already expanded to their prefixes. Suggestion servers fetch it every 30 to 60 seconds.

Merge. On a lookup, the server takes the stored list for the prefix and the overlay entries for the same prefix, ranks them together, removes duplicates and cuts to the limit. That is one extra hash lookup.

Caches. A ten-minute CDN TTL would defeat all of this. I would cut the TTL to about a minute, or purge only the prefixes the overlay touched.

Expire. Overlay entries carry a short expiry and disappear unless the stream job confirms them again. If a query stays popular, the next daily build picks it up.

The trade-off is two sources to merge and a stream job to operate, in exchange for a five-minute path that leaves the main index untouched.

Likely follow-ups

How do you stop people gaming the trending overlay?
Count distinct users or devices, not events, and cap what one user can contribute. Require a query to come from many networks and regions before it qualifies, hold sensitive categories for review, and keep the serving-time blocklist as the fast way to remove something that got through.
The CDN caches suggestion responses for ten minutes. How can a query appear within five?
Either lower the TTL to about a minute or purge the prefixes that the overlay changed. A short TTL costs some origin traffic. The roughly 18,000 short prefixes refreshed once a minute are about 300 requests a second from each cache that fronts the origin, so put a shield tier in front instead of letting every edge location refetch. Client-side caches need the same limit.
Is merging the overlay with a stored top-10 list exact?
It is exact for every query in the overlay, because the overlay carries a score for each. A query that is in neither the stored top 10 nor the overlay cannot enter the result. That is acceptable, because such a query is neither popular nor trending.
What if the stream job falls behind or dies?
Overlay entries carry an expiry. Servers drop expired entries and serve the main index alone, so freshness falls back to daily and nothing breaks. Alert on consumer lag and on the age of the newest overlay.

Common mistakes

  • Updating the main trie in place on every search.
  • Rebuilding the whole index every five minutes.
  • Ranking the overlay by raw counts, which just rediscovers queries that are always popular.
  • Forgetting that CDN and client cache TTLs make the freshness target unreachable.
  • Skipping filters on the fast path, where abuse is easiest.

A strong answer includes

  • Keeps the daily index and adds a small overlay
  • Uses a stream job with a sliding window over the query log
  • Detects rising queries against a baseline, not by raw count
  • Applies distinct-user thresholds and the blocklist to the overlay
  • Merges the overlay at lookup time
  • Aligns CDN and client cache TTLs with the target
  • Expires overlay entries and degrades to the main index

Revise: Design typeahead (search autocomplete)

8. Your crawler runs on 200 machines. How do you guarantee that no website is hit more than once a second?

Seniorweb-crawlerpartitioningrate-limiting

What the interviewer is really testing

Whether you can turn a global constraint into local state by partitioning, instead of putting a shared lock or counter on the hot path. Also whether you know the rules around the limit, such as robots.txt, backoff and shared IP addresses.

Show the model answer, follow-ups and checklist

Model answer

I would not solve this with a shared rate limiter that all 200 machines consult. That puts a round trip and a failure dependency on every fetch. I would make the limit local by giving each host exactly one owner.

Ownership. Hash the host name to a frontier shard, with consistent hashing so membership changes move few hosts. Only the owning shard ever schedules that host. When a parser on another machine finds a link to it, the URL is forwarded to the owner.

Inside a shard. There is one queue per host and a min-heap keyed by the earliest time each host may next be contacted. A fetcher pops the heap and gets a host only when its time has come. The host stays out of the heap while the request is in flight, so there is never more than one connection to it. When the response arrives, the host is pushed back with “now plus delay”. Measuring from the end of the request matters, because a slow server then gets more rest automatically.

The delay is a policy per host. One second by default, longer if the site asks for it or responds slowly, and multiplied on a 429 or 503.

Edge cases. When a shard takes over hosts, it waits a full delay before contacting each, because it does not know when the previous owner last did. And per-host limits are not enough for shared hosting, where thousands of sites sit on one IP address. I would add a second limit per IP, applied to the resolved address.

Finally I would measure it: log the gap between consecutive requests per host and alert if any gap is below the policy. A politeness guarantee that is not monitored will be broken by a later change.

Likely follow-ups

Why not keep a token bucket per host in Redis and have every fetcher check it?
It works at small scale, but it adds a network round trip to every fetch and makes Redis a hard dependency of the crawl. It also limits without scheduling. Fetchers pull URLs they are then not allowed to fetch, so they spin or block. A heap of next-contact times only hands out work that is due.
A frontier shard crashes and restarts. Could it break the delay?
The next-contact times were in memory, so the restarted shard does not know when each host was last contacted. The safe rule is to wait one full delay before the first request to any host after a restart. Leases held by fetchers expire before those URLs are handed out again.
A site starts returning 429 or 503. What does the crawler do?
It treats that as a signal about the host, not about the page. It honours Retry-After if present, otherwise it multiplies that host's delay and retries later. Repeated errors pause the host for hours. It never retries immediately on another worker.
The business wants a 50-million-page site crawled within a week. Can you do it?
Not at one request a second, which yields about 600,000 pages a week. A week needs about 83 requests a second, and that is not something to decide alone. Ask the site for a higher rate, use its sitemaps and conditional requests to skip unchanged pages, and spend the budget on its most important pages.

Common mistakes

  • Taking a distributed lock or calling a shared counter for every fetch.
  • Partitioning by URL hash, which spreads one host across every machine.
  • Measuring the delay from when a request starts, so a slow response overlaps with the next request.
  • Forgetting that thousands of small sites can share one IP address.
  • Rebalancing shards without handing over each host's next-contact time.
  • Treating politeness as only a rate and ignoring robots.txt.

A strong answer includes

  • Partitions by host so one shard owns each host
  • Uses a per-host queue and a heap of next-contact times, with one request in flight per host
  • Forwards discovered URLs to the owning shard
  • Handles shard changes and restarts conservatively
  • Backs off per host on 429, 503 and slow responses
  • Mentions per-IP limits for shared hosting
  • Verifies the guarantee by measuring gaps between requests per host

Revise: Design a web crawler

9. A user with 100 million followers posts. What happens in your news feed system, and what breaks?

Seniornews-feedfan-outcaching

What the interviewer is really testing

Whether you can put numbers on fan-out, see that the average case hides a tail that breaks the design, and propose a hybrid without losing the benefits of precomputed feeds.

Show the model answer, follow-ups and checklist

Model answer

Start with what pure fan-out on write would do. The post is stored, an event is published, and workers insert the post id into every follower’s cached feed. For 100 million followers that is 100 million cache writes. If the fleet normally handles about 90,000 inserts a second in total, this one post is around 18 minutes of everything it can do.

The author does not notice, because fan-out is asynchronous. Everyone else does. Posts from ordinary accounts queue behind the burst, so feeds across the product go stale. The cache shards take a write spike, and most of the writes go to feeds of people who will not open the app for days.

So I would not push this post. The design is a hybrid:

  • Ordinary accounts are pushed. A post costs a few hundred inserts and reads stay a single cache lookup.
  • Accounts above a follower threshold are not fanned out. Their posts go to the post store and to a per-author list of recent posts.
  • At read time the feed service takes the user’s cached feed, fetches the recent posts of the few celebrities that user follows, merges by time, deduplicates by post id and hydrates.

This is affordable because of the shape of the data. A user follows a handful of celebrities, and each celebrity’s recent-posts list is requested by millions of readers, so it is always hot in cache. The expensive list is computed once and shared, instead of copied 100 million times.

What still needs care: the celebrity’s post itself is read at a very high rate, so the post cache and its counters must absorb that. Notifications for the post are a separate fan-out with the same problem and usually go only to followers who opted in. The threshold is a tuning decision, set where a single post’s burst begins to delay other posts.

Likely follow-ups

How does the feed service know which of the accounts I follow are celebrities?
An account is flagged when its follower count crosses the threshold. Each user has a small cached list of the flagged accounts they follow, updated when they follow or unfollow and when an account's flag changes. The feed service reads that list alongside the feed.
An account crosses the threshold tomorrow. What happens to its posts that were already pushed?
Nothing. They stay in follower feeds and age out. New posts are pulled. The merge deduplicates by post id, so a post that appears in both lists is shown once. Use two thresholds, one to switch on and a lower one to switch off, so accounts near the line do not flip back and forth.
Why not just add fan-out workers until 100 million inserts is fast?
The cost is proportional to followers whatever the speed, and most of it is wasted on people who will not open the app before the post is buried. The burst also has to be provisioned for but is idle most of the time. Pulling costs one cached read per viewer who really loads their feed.
Someone follows 2,000 celebrity accounts. Is their feed read slow again?
It is more work, but each list is short and already in cache, so it is a few batched multi-gets and a merge of small sorted lists. Set a ceiling and measure it. If it matters, push celebrity posts for those few heavy followers, or cap how many pulled sources are merged per request.

Common mistakes

  • Saying "put it on a queue" as though making the work asynchronous makes it smaller.
  • Running fan-out inside the post request.
  • Proposing pull for everyone without costing 23,000 feed reads a second.
  • Forgetting to deduplicate when merging pushed and pulled posts.
  • Ignoring the read load on the celebrity's own post list.

A strong answer includes

  • Quantifies the fan-out for one post and compares it with total capacity
  • Explains that other users' posts are delayed, not only the celebrity's
  • Pushes for ordinary accounts and pulls for accounts above a threshold
  • Merges pulled posts with the cached feed at read time and deduplicates
  • Caches the celebrity's recent posts, since millions read the same list
  • Mentions skipping inactive followers
  • States that the threshold is a tuning choice

Revise: Design a news feed or timeline

10. In a chat app, a user taps send, sees no confirmation, and taps retry. How do you make sure the recipient gets the message once and in the right order?

Mid-levelchatidempotencyordering

What the interviewer is really testing

Whether you understand that retries are unavoidable, that exactly-once delivery is built from at-least-once plus idempotency, and that ordering must come from the server and not from client clocks or the network.

Show the model answer, follow-ups and checklist

Model answer

The retry itself is correct behaviour. The user’s phone cannot tell “the message never arrived” from “the message arrived and the acknowledgement was lost”, so it must send again. The design has to make that safe.

One id for all attempts. Before the first attempt, the client generates a unique id for the message and stores the message in a local outbox. Every retry, automatic or manual, sends the same id.

Persist, then acknowledge. The server writes the message to durable storage and only then acknowledges. If it crashes first, no acknowledgement was sent and the retry does the work.

Deduplicate on the server. The server records the client id with the message. When a send arrives with an id it has already stored for that sender and conversation, it stores nothing and returns the original acknowledgement. The check and the write must be atomic, for example a unique constraint or a conditional insert, or two concurrent retries could both pass.

Order on the server. When the message is first stored, the server gives it the next sequence number in the conversation. A duplicate gets the same number back. The order therefore reflects when the server first accepted the message, not when a retry happened to arrive and not what the sender’s clock said.

Deduplicate on the receiver. Delivery to the recipient can also repeat, for instance if their acknowledgement is lost. The recipient’s app ignores any sequence number it already has.

So the guarantee is at-least-once delivery on both hops, with idempotent handling at both ends. Nothing is lost, because every hop retries until acknowledged, and nothing shows twice, because every repeat is recognised.

Likely follow-ups

Two people send to a group at the same instant. Who decides the order?
The server does. Sends for one conversation are sequenced by a single writer, and whichever it processes first gets the lower number. Every client sorts by sequence number, so all members converge on the same order even if a sender briefly saw their own message first.
How long do you keep client message ids for deduplication?
The id is stored with the message, so in principle for ever, but looking it up needs an index. A cheaper option is a deduplication cache with a TTL of a day or so, on the grounds that clients stop retrying long before that. Say which you chose and what a retry after the window would do.
The recipient's device has messages up to 41 and receives 43. What does it do?
It knows 42 is missing, because sequence numbers have no gaps. It asks the server for everything after 41 and applies the result, ignoring anything it already holds. It can show 43 once the gap is filled, or straight away with the gap filled in behind it.
TCP already delivers bytes in order without duplicates. Why is that not enough?
TCP's guarantees cover one connection. A retry after a reconnect arrives on a different connection, possibly at a different gateway, and a user's devices each have their own. Ordering and deduplication across connections must be done by the application.

Common mistakes

  • Generating a new message id on each retry, which makes every retry a new message.
  • Acknowledging before the message is durably stored.
  • Ordering by the sender's device clock.
  • Relying on TCP or on the WebSocket for ordering and deduplication across reconnects.
  • Deduplicating only on the server and letting the recipient's device show a redelivered message twice.

A strong answer includes

  • The client generates the message id once and reuses it for every retry
  • The server persists before acknowledging
  • The server maps the client id to the stored message and returns the same result on a repeat
  • The server assigns a per-conversation sequence number
  • Receivers ignore sequence numbers they already hold and detect gaps
  • Names the guarantee as at-least-once delivery with idempotent handling

Revise: Design a chat system

11. A WebSocket gateway holding 250,000 chat connections dies. Walk me through the next five minutes.

Staffchatwebsocketfailure-modes

What the interviewer is really testing

Whether you can reason about a failure in a stateful tier end to end, covering what is lost, how each party finds out, the secondary overload that follows, and how the design limits the blast radius.

Show the model answer, follow-ups and checklist

Model answer

What is lost and what is not. The sockets are gone, along with any frames in the gateway’s buffers. No message is lost. A message is acknowledged to its sender only after it is in the message store, and every device catches up from the store by cursor.

Detection. If the process crashed but the host is up, clients see the connection reset straight away. If the host vanished, nothing tells them, and they find out when a heartbeat goes unanswered, perhaps 30 to 60 seconds later. On the server side, the session registry still says those devices are on the dead gateway. The chat service’s delivery calls fail, so it treats those devices as offline and queues push notifications. Registry entries expire by TTL.

Reconnect. Now 250,000 clients want new connections. Each needs a TLS handshake and token validation, then sends a sync request. Across 99 remaining gateways that is about 2,500 extra connections each, which is fine in steady state. The danger is the arrival rate. Clients must use exponential backoff with jitter so the reconnects spread over tens of seconds. Each gateway caps handshakes per second and sheds the excess with a “retry later” response.

Resync. Each device sends its cursors. For most conversations nothing was missed, so the server compares cursors with last sequence numbers and returns only the gaps. Senders with unacknowledged messages resend them with the same client id, and the server deduplicates.

Presence. Presence expires by TTL and is not deleted on disconnect, so users who reconnect within the grace period never appear offline.

After five minutes the fleet is balanced again, slightly fuller. The follow-up is prevention: enough headroom to lose several gateways, draining for planned restarts, and a load test of exactly this event, because the reconnect path is the one that never gets exercised in normal operation.

Likely follow-ups

Now a whole availability zone with a third of the gateways goes. What changes?
Eight million clients reconnect to a fleet that has lost a third of its capacity. That only works if the fleet normally runs with enough headroom to carry the full load on two zones. Gateways must cap new handshakes per second and tell excess clients to retry later, and client backoff must stretch to minutes.
How does the chat service learn that the gateway is gone?
Its calls to that gateway fail or time out, and a circuit breaker stops further attempts quickly. Service discovery health checks remove the instance. Registry entries carry the gateway's instance id, so entries from a dead or restarted instance are recognised as invalid even before their TTL expires.
How do you deploy new gateway code without causing this yourself?
Drain instead of kill. The gateway stops accepting new connections and asks its existing clients to reconnect in small batches over several minutes. Clients reconnect to other gateways with jitter. Keeping logic out of the gateway means such deploys are rare.
A client was halfway through sending a message when the gateway died. Is the message lost or duplicated?
Neither. The client never received an acknowledgement, so it resends with the same client-generated id after reconnecting. If the server had already stored the message, it recognises the id and returns the original sequence number.

Common mistakes

  • Saying clients reconnect and stopping there, without the load that reconnection creates.
  • Assuming clients notice at once, when a vanished host sends no close frame.
  • Retrying immediately or on a fixed interval, which synchronises 250,000 clients.
  • Treating messages in flight as lost, when they are in the store or will be resent.
  • Marking a quarter of a million users offline and then online again within seconds.

A strong answer includes

  • Separates what is lost (sockets, unacknowledged frames) from what is safe (stored messages)
  • Explains how clients, the registry and the chat service each detect the failure
  • Routes messages for affected users to push until they reconnect
  • Uses exponential backoff with jitter on reconnect
  • Protects the remaining gateways with admission control on handshakes
  • Makes resync cheap by comparing cursors before fetching
  • Describes draining for planned restarts and capacity headroom for unplanned ones

Revise: Design a chat system

12. A marketing campaign to 50 million users goes out and login codes start arriving ten minutes late. What went wrong, and how do you fix the design?

Seniornotificationsqueuespriority

What the interviewer is really testing

Whether you can diagnose head-of-line blocking in a shared pipeline, find every shared stage and not only the obvious one, and design isolation between traffic classes that have different deadlines.

Show the model answer, follow-ups and checklist

Model answer

Ten-minute delays during a campaign mean urgent and bulk messages are waiting in the same line somewhere. I would find where by looking at the age of the oldest message at each stage. There are usually four candidates:

  • The channel queue. If codes and promotions share one SMS or push queue, a code enqueued behind 50 million messages waits for them.
  • The worker pool. Even with separate queues, shared workers can all be busy with bulk batches.
  • The provider rate limit. If the campaign consumes the whole allowance, codes are throttled with it.
  • The stages before the channel queues. The intake queue and the router are shared too. Fixing the channel queue while everything still funnels through one router just moves the bottleneck.

The fix is isolation by traffic class from the API to the provider.

Lanes. At least two lanes through every stage: high for login codes and security alerts, bulk for marketing. Each has its own queue and its own reserved workers. The API assigns the lane from the category, and callers cannot promote themselves.

Provider capacity. The high lane has first claim on the provider’s rate limit and bulk gets what remains. For SMS I would consider a separate sender or account for codes.

Shape the bulk. A campaign should not arrive as 50 million messages at once. Expand the audience in batches and release at a rate the bulk lane can drain, spread over an hour or more.

Deadlines. A login code has a time to live of a few minutes. If it has not been sent by then, drop it. A late code confuses the user, who has usually asked for another.

Monitoring. Alert on message age per lane, not on total queue depth. A deep bulk lane during a campaign is normal. A high-priority message that is two seconds old is an incident.

Likely follow-ups

Why not one queue with a priority field on each message?
Many brokers have no priority at all, Kafka and SQS among them. Where it exists, messages already handed to a consumer are not reordered, and a worker that is busy with bulk sends is busy whatever arrives. Separate lanes with reserved consumers are simpler to reason about and to monitor.
The SMS provider allows 100 messages a second in total. How do you share that?
Split the token bucket. The high lane has first claim on all 100, and the bulk lane may use only what is left, so capacity is not wasted when there are no codes to send. Alternatively give login codes their own provider account or sender, so the two limits are independent.
The campaign is already queued and codes are late right now. What do you do in the next ten minutes?
Pause the bulk consumers with a switch so the queue stops feeding the provider, and let urgent traffic drain. If both kinds share one queue and cannot be separated, stand up a new queue for login codes, point the login service at it, and give it dedicated workers. Then resume the campaign at a controlled rate.
How would you have caught this before users did?
Define an objective for high-priority notifications, such as reaching the provider within two seconds at p99, and alert on the age of the oldest message per lane. A synthetic login code sent every minute and timed end to end catches what queue metrics miss. Load test with a campaign running.

Common mistakes

  • Blaming the provider without checking where messages were waiting.
  • Fixing only the channel queue and leaving the intake queue and router shared.
  • Adding workers, which drains the campaign faster into the same provider limit.
  • Using one priority queue and assuming it reorders work already in progress.
  • Retrying late codes for ever instead of expiring them.

A strong answer includes

  • Identifies head-of-line blocking in a shared queue, worker pool or provider quota
  • Checks every stage of the pipeline for sharing, including intake and routing
  • Separates lanes by priority with reserved workers
  • Reserves provider rate limit for the high lane
  • Shapes bulk traffic at the source
  • Gives login codes a short time to live
  • Monitors message age per lane and tests with synthetic traffic

Revise: Design a notification service

13. A creator uploads a two-hour 4K video and it takes six hours to become watchable. How do you get that down to minutes?

Seniorvideo-streamingtranscodingpipelines

What the interviewer is really testing

Whether you can find where elapsed time goes in a batch pipeline, restructure the work so it runs in parallel, and separate "watchable" from "fully processed". Also whether you know the costs of chunked encoding.

Show the model answer, follow-ups and checklist

Model answer

Six hours says the pipeline is treating the video as one job. A single worker is encoding two hours of 4K source into every rendition, one after another, and high-resolution encoding runs slower than real time. Elapsed time grows with the length of the video. I would change the structure so that it depends on the number of workers.

Split. Cut the source into chunks of about a minute, at existing keyframes so the split is a fast copy and not a re-encode. Two hours becomes 120 chunks.

Encode in parallel. Each chunk and rendition pair is an independent task on a queue. With five renditions that is 600 tasks. Given enough workers, the encode stage takes roughly as long as the slowest single task, a few minutes, plus queueing. The pool scales on queue depth.

Package. When all the chunks of a rendition are done, a packaging task produces the segments and that rendition’s playlist, and adds it to the master playlist.

Publish progressively. “Watchable” does not need every rendition. Schedule the lowest rendition first and publish as soon as it is packaged. A 360p encode of 120 chunks finishes quickly, so the video plays within minutes. The 1080p and 4K renditions appear in the manifest as they complete, and players pick them up.

Keep it robust. Tasks are idempotent and leased, so a lost worker costs one chunk. An orchestrator stores the task graph and decides what can run next.

Two costs to state. Chunked encoding gives up a little quality at chunk boundaries. And a two-hour upload now creates hundreds of tasks at once, so the scheduler needs a per-video concurrency cap or fair queueing, or one creator’s upload delays everyone else’s.

If minutes is still too slow, the remaining wait is the upload itself. Processing could start on parts as they arrive, which is a larger change to the upload protocol.

Likely follow-ups

A worker dies 90 seconds into encoding a chunk. What happens?
The worker held a lease on the task and stopped renewing it. When the lease expires the task returns to the queue and another worker runs it. The output key is derived from the video, rendition and chunk, so the rerun overwrites any partial object. After a fixed number of failures the video is marked failed with a reason.
How do you stop one two-hour upload starving a thousand short clips?
Its hundreds of tasks would fill a single first-in, first-out queue. Cap the number of tasks per video that may run at once, or schedule fairly across videos. Give first renditions of short videos their own lane, so a quick clip is watchable in seconds whatever else is in progress.
Does encoding in chunks hurt quality?
Slightly. Every chunk must begin with a keyframe, and the encoder cannot spread bits across a chunk boundary, so quality can step at the joins. Encoding to a constant quality target instead of a fixed bitrate per chunk reduces this. Audio is encoded once for the whole file, since it is cheap and joins are audible.
Would hardware encoders help?
For speed, yes. GPU and dedicated hardware encoders are much faster than software. They generally need more bitrate for the same quality than a slow software preset, so they suit the fast first pass. Popular videos can be re-encoded later in software, where the bandwidth saving repays the compute.

Common mistakes

  • Suggesting a bigger machine, which helps a little and still restarts from zero on failure.
  • Parallelising across renditions only, which leaves the slowest rendition as a multi-hour job.
  • Waiting for every rendition before the video can be played.
  • Splitting at arbitrary byte offsets instead of at keyframes.
  • Forgetting that one large job can now starve everyone else's uploads.

A strong answer includes

  • Identifies sequential, single-worker encoding as the cause
  • Splits the source at keyframes into independent chunks
  • Encodes chunk by rendition tasks in parallel and packages at the end
  • Publishes the lowest rendition first and adds higher ones later
  • Makes tasks idempotent with leases and retries
  • Adds fairness or per-video concurrency limits
  • Names the quality cost of chunk boundaries

Revise: Design video streaming

14. Two devices edit the same file offline in your Dropbox-style sync system. What happens when both reconnect?

Seniorfile-syncconflict-resolutionversioning

What the interviewer is really testing

Whether you detect the conflict from version information and not from clocks, make the server-side check atomic, and choose a resolution that never destroys a user's work without them knowing.

Show the model answer, follow-ups and checklist

Model answer

I would separate detecting the conflict from resolving it.

Detection. Each device keeps a local database recording the revision it last synced for every file, say revision 41. Every commit carries that parent revision. Laptop A reconnects first and commits with parent 41. The server sees that 41 is the latest, and records revision 42. Laptop B then commits with parent 41. The server sees the latest is now 42, so B never saw A’s edit, and it rejects the commit. That check and the journal write happen in one transaction, so it is a compare-and-set and two simultaneous commits cannot both pass.

I would not use modified times. Device clocks are wrong often enough to make that dangerous.

Resolution. The server holds opaque blocks. It does not understand a spreadsheet, so it cannot merge, and choosing a winner would silently destroy someone’s work. So I keep both. B’s client renames its version to something like “budget (B’s conflicted copy 2026-03-01).xlsx”, commits it as a new file, and downloads revision 42 to the original path. Both versions now sync to every device and a person decides.

This is cheap. B’s blocks were uploaded before the commit was attempted, because blocks go first and metadata second. Creating the conflicted copy is a metadata change only.

Edge cases. If B’s block list is identical to revision 42, both made the same change and there is no conflict. If one side deleted and the other edited, the edit wins and the file returns. A rename on one device and an edit on the other combine cleanly if files have a stable id independent of path.

The trade-off. Users occasionally have to tidy up conflicted copies. That is the price of never losing an edit. If the requirement were several people typing in one document at the same moment, I would say this design is the wrong tool and move to operational transforms or CRDTs.

Likely follow-ups

Why not resolve it with last writer wins, using the files' modified times?
Device clocks are not trustworthy, so a laptop whose clock runs a day fast would win every conflict. Even with perfect clocks, last writer wins silently discards the other person's edits, and they find out days later. A sync product is judged on never losing data.
Both commits reach the server in the same millisecond. What stops both being accepted?
The commit is one transaction on the shard that owns the folder. It checks that the parent revision is still the latest for that path and inserts the next journal row, under a row lock or a unique constraint on path and revision. The second transaction sees the first one's row and fails the check.
One device deleted the file while the other edited it. Which wins?
The edit. The delete was based on the old content, and bringing a file back is harmless while discarding new edits is not. The deleted version is still in version history either way.
Could you merge the two versions automatically?
Only for formats the service understands. Plain text can be three-way merged against the common ancestor, which version history still holds. For binary formats such as slide decks a block-level merge would produce a corrupt file, so sync products keep both. Live co-editing needs a different design based on operational transforms or CRDTs.

Common mistakes

  • Deciding the winner by wall-clock timestamp.
  • Letting the second upload silently overwrite the first.
  • Proposing a block-by-block merge of binary files.
  • Forgetting that the revision check and the write must be one atomic step on the server.
  • Re-uploading the whole file to create the conflicted copy when its blocks are already on the server.

A strong answer includes

  • Detects the conflict from the parent revision carried in the commit, not from timestamps
  • Makes the check and the journal append a single transaction
  • Keeps both versions as a conflicted copy and explains why the server cannot merge
  • Handles edit against delete
  • Notes that identical content is not a conflict
  • States the cost (users tidy up copies) and when a different design applies

Revise: Design file sync (Dropbox-style)

15. In your ride-sharing design, how do you guarantee a driver is never dispatched to two riders at once?

Seniorride-sharingconcurrencymatching

What the interviewer is really testing

Whether you can spot a check-then-act race between concurrent matchers and close it with an atomic conditional write on one source of truth, including expiry and the races around accepting and cancelling.

Show the model answer, follow-ups and checklist

Model answer

The risk is a check-then-act race. Two riders a street apart request at the same moment. Two matcher instances query the geo index, both see driver D as available and nearest, and both send an offer. The geo index cannot prevent that. It is an in-memory copy that is updated a moment later, and any read followed by a separate write leaves a gap.

So I keep one authoritative status record per driver in a durable store, and I reserve the driver with a single conditional write before any offer is sent:

UPDATE drivers
SET status = 'offered', trip_id = ?, offer_id = ?, offer_expires_at = now() + 15s
WHERE driver_id = ? AND status = 'available'

Exactly one matcher’s update matches a row. The other gets zero rows and moves to its next candidate. Only the winner sends the offer. The geo index carries a copy of the status so that queries can filter, but it is a hint.

The reservation is a lease, so it needs an expiry. If the matcher crashes or the driver ignores the offer, the driver becomes available again after 15 seconds.

Accepting is two more conditional writes. The trip moves from matching to driver assigned only if it is still in matching. The driver moves from offered to on trip only if the offer id is still current. If the rider cancelled while the offer was out, the trip update matches nothing, and the driver is released and told the trip has gone. The trip’s own conditional update also covers the opposite fault, one trip with two drivers.

I prefer this to a separate lock service. A lock with a timeout can be held by a paused process that still believes it owns it. Storing the reservation on the record it protects means the check and the write are the same operation.

The cost is one durable write per offer, which is tiny next to the location stream.

Likely follow-ups

The matcher reserves a driver and crashes before sending the offer. What happens to the driver?
The reservation carries an expiry of about 15 seconds. A sweeper, or a rule that treats an expired offer as available, releases the driver. Without an expiry, a crashed matcher would leave drivers online but never offered a trip.
The driver taps accept just as the offer expires and a new offer has been made to them. What stops the old acceptance being applied?
The acceptance carries the offer id, and the conditional update requires the driver's current offer to be that id and the trip to still be in matching. The stale acceptance matches no rows, and the app shows that the offer expired.
Would batched matching remove the need for this?
It removes the race inside one batch, because a single solver assigns each driver once. It does not remove it between overlapping batches, neighbouring regions or two solver instances after a failover. I would keep the conditional write as the guard and treat batching as an optimisation on top.
Why not keep driver status only in the in-memory geo index?
The index is deliberately disposable and its replicas are not strongly consistent, so a failover could forget a reservation and allow a second offer. Status changes happen once per offer, not once per location update, so a durable store handles the rate easily.

Common mistakes

  • Reading the driver's status from the index and then writing it in a separate step.
  • Relying on the driver app to reject a second offer.
  • Reserving without an expiry, so a crash strands the driver.
  • Ignoring the race between a rider cancelling and a driver accepting.
  • Taking one global lock around matching, which serialises a whole city.

A strong answer includes

  • Describes the race between two matchers that read the same available driver
  • Uses one atomic conditional write on an authoritative driver record
  • Adds an expiry to the reservation and says who releases it
  • Makes acceptance conditional on the offer and the trip state
  • Covers the rider-cancels case
  • Explains why the geo index is only a filter

Revise: Design ride-sharing with geo-indexing

16. Your call to the payment provider times out. Was the customer charged, and what does your system do next?

Seniorpaymentsidempotencytimeouts

What the interviewer is really testing

Whether you understand that a timeout is an unknown outcome, and can design recovery that neither double charges nor loses a payment, using a pending state, idempotency keys and more than one way of learning the result.

Show the model answer, follow-ups and checklist

Model answer

I do not know whether the customer was charged, and the design has to admit that. The request may never have arrived, it may have been declined, or the card may have been charged and the response lost. A timeout looks the same in all three cases.

Two things done before the call make this recoverable. The payment row was written as pending, with the client’s idempotency key, before the provider was called, so there is a record whatever happens. And the provider call carried its own idempotency key derived from the payment id.

On the timeout I leave the payment pending and return 202 to the client, which shows “processing”. I do not report a failure.

Then the payment is resolved by evidence, through whichever path gets there first:

  1. Retry the same call with the same key, a few times with backoff. If the first call succeeded, the provider returns that result and does not charge again. If it never arrived, this performs the charge once.
  2. Query the provider for the payment by our reference.
  3. The webhook arrives.

A sweeper job runs the query for anything pending for more than about a minute, so resolution does not depend on the client coming back.

When evidence arrives, the state machine moves once: to captured, with ledger entries and an event for the order, or to declined, after which the customer can start a new attempt with a new key.

On the customer side, a retry of the same checkout sends the same key and gets the same payment back. If they abandon it and pay through a fresh checkout, a rule allowing one successful payment per order catches the case where both succeed, and the extra one is voided or refunded automatically.

The trade-off is that a customer sometimes waits several seconds for an answer. That is far better than charging twice. Daily reconciliation against the provider’s settlement report is the backstop for anything all of this misses.

Likely follow-ups

The customer taps Pay again while the first attempt is still pending. What happens?
The checkout reuses the same idempotency key for the same purchase, so the server returns the existing pending payment and creates nothing new. If a second tab sends a different key, an order-level rule allowing one active payment per order returns the existing payment instead of starting another.
Your service crashed after the provider returned success but before the database commit. How is that different?
It is not. The row still says pending and nothing in our system knows the result. The sweeper's status query and the provider's webhook both resolve it, which is why the pending row is written before the call.
The provider only remembers idempotency keys for a limited time. What if the payment is still pending after that?
After the window, repeating the create call could charge again, so the system stops retrying and only queries by its own reference. A payment pending that long also raises an alert for a person to look at.
Why not put the provider call and the database write in one transaction?
The provider is an external HTTP API and cannot take part in a database transaction. Holding a transaction open across a network call that may take 30 seconds also ties up locks and connections. Recording intent first, calling with an idempotency key and recovering afterwards gives the same safety.

Common mistakes

  • Treating the timeout as a failure and inviting the customer to pay again.
  • Retrying the provider with a new idempotency key, or with none.
  • Calling the provider before anything is recorded locally.
  • Relying only on webhooks, which can be delayed for hours, with no status query.
  • Keeping a database transaction open across the provider call.

A strong answer includes

  • Says the outcome is unknown and lists the three possibilities
  • Has a pending payment recorded before the provider call
  • Retries with the same provider idempotency key
  • Adds a status query and the webhook as further resolution paths, with a sweeper
  • Tells the customer it is processing, not failed
  • Handles the customer paying again
  • Names reconciliation as the backstop

Revise: Design a payment system

17. Reconciliation shows payments the provider settled that your ledger records as failed. How do you investigate and fix it?

Staffpaymentsreconciliationledger

What the interviewer is really testing

Whether you treat reconciliation as part of the system, can reason backwards from a discrepancy to the code path that produced it, and can repair money records without rewriting history.

Show the model answer, follow-ups and checklist

Model answer

This mismatch means customers were charged while we told them the payment failed. Some will have paid twice and some will have paid for nothing, so I treat it as an incident.

Scope first. How many payments, starting when, and what do they share: one provider, one region, a deployment date, a window that matches a known outage? This is not a cut-off timing gap, because our records say failed and not missing.

Fix the customers and the books. For each payment, check whether the order was later paid by another attempt. If so, the settled one is a duplicate and is refunded. If not, the default is to refund and tell the customer, unless the business would sooner fulfil the order. I never edit the failed rows or their ledger entries. I post the capture that should have been recorded, linked to the provider’s reference, then the refund. The payment gets an audited correction transition based on provider evidence.

Find the cause. Failed should be reachable only when the provider says declined. So I take one affected payment and rebuild its timeline from our request logs and the stored webhook events. The usual suspects are:

  • a timeout handler that marks the payment failed
  • a sweeper that gives up after several attempts and marks it failed
  • a success webhook that arrived after we had marked it failed, and was discarded as an invalid transition
  • a status query that returned “not found” before the provider had finished processing

Prevent it. Remove every path to failed that is not backed by provider evidence. Treat a success event for a failed payment as an alert and an automatic correction, not something to drop. Reconcile hourly against the provider’s API as well as daily against the file. Add a test that drops provider responses on purpose and checks that payments end in the right state.

Reconciliation did its job here. The fault is in the recovery paths, and the response should strengthen both.

Likely follow-ups

How do you correct the ledger without editing entries?
Post new transactions. First the capture that should have been recorded, linked to the provider reference and marked as a correction, then the refund if the money is going back. The ledger then shows what really happened, which is that money arrived and later left.
What about the opposite mismatch, where your ledger says captured and the provider has no record?
First rule out timing, since a payment near the cut-off appears in the next file. If it is truly absent, goods may have been released without payment. I would look for a response wrongly treated as success, such as a payment still awaiting customer authentication, and check that webhook signatures are verified, because a forged webhook would look exactly like this.
Daily reconciliation found this 20 hours late. How do you find it sooner?
Reconcile during the day against the provider's API instead of waiting for the file, and add live invariants. Every success webhook should match a payment that reaches captured within minutes, and a success event for a payment in a terminal failed state should raise an alert immediately.
How do you make the repair job safe to run?
Make it idempotent with a key per payment and correction type, so running it twice changes nothing. Run it as a dry run first, in small batches, with a second person reviewing the output, and reconcile again afterwards to confirm the discrepancy has closed.

Common mistakes

  • Updating the failed payment rows or ledger entries in place.
  • Dismissing the difference as a provider error or a timing gap without checking.
  • Fixing the affected records without finding the code path, or the reverse.
  • Refunding without first recording the capture, so the ledger shows money leaving that never arrived.
  • Assuming the payments found so far are the only ones affected.

A strong answer includes

  • Establishes scope and looks for a common factor before acting
  • States what it means for customers (charged and told it failed)
  • Repairs with new ledger transactions, never edits
  • Lists plausible causes tied to the timeout and webhook paths
  • Uses the stored provider events to rebuild one payment's timeline
  • Proposes prevention (evidence-only failure state, faster reconciliation, alerts)

Revise: Design a payment system

18. Your flash sale gates stock with a Redis counter. The Redis primary fails mid-sale. Can you oversell, and what do you do?

Seniorflash-saleredisinventory

What the interviewer is really testing

Whether you know the limits of Redis durability and replication, keep a system of record behind the fast path, and deliberately make failures lean towards underselling.

Show the model answer, follow-ups and checklist

Model answer

With Redis alone, yes. Redis replication is asynchronous, so the replica that gets promoted may be missing the last few hundred decrements and the matching entries in the buyers set. Its counter is then higher than the truth, and it would admit buyers for units that are already claimed. A restart from disk has the same problem: with the append-only file synced once a second, up to about a second of writes can be lost.

That is why Redis is only the gate in my design and never the record. Every claim that passes Redis becomes a message, and a worker writes the reservation to the database with a conditional update that only succeeds while remaining stock is above zero, plus a unique constraint on sale and user. After a bad failover Redis over-admits, the database refuses the excess, and those buyers are told it has sold out. Confirmed reservations can never exceed stock.

For the buyer’s sake, the response after the Redis step is “confirming your reservation”, and it becomes “reserved” only once the database row exists.

Operationally, at failover I would do three things:

  1. Fail closed. While Redis is unreachable the sale service answers “try again shortly”. It does not fall back to the database for every request, because that sends the whole crowd to the hot row.
  2. Pause admission. The waiting room stops advancing “now serving”. A pause of a few seconds mid-sale is acceptable.
  3. Rebuild. Let the reservation queue drain, set the counter to the database’s remaining stock, rebuild the buyers set from the reservations table, then resume.

The principle behind all of it is to lean towards underselling. If a claim is lost between Redis and the queue, a unit sits unclaimed until reconciliation returns it, and it sells a few minutes late. That is a small cost. Selling a unit twice means cancelling a customer’s order, and no reconciliation job can undo that.

Likely follow-ups

Why not make the database the only gate and drop Redis?
With a strict waiting room that admits about a thousand buyers a second, you could. The conditional update is correct on its own. Redis earns its place by rejecting duplicates and the sold-out crowd in memory, so the database's hot row and connection pool only see likely winners.
Would the WAIT command or fsync on every write close the gap?
They narrow it. Appending to the AOF with fsync on every write makes a single node durable at a large cost in throughput. WAIT blocks until replicas acknowledge, but the Redis documentation is explicit that it does not make the system strongly consistent, because a failover can still promote a replica that lacks the write. The database check is still needed.
The service crashes after the Redis decrement and before the reservation message is queued. What then?
A unit is claimed with no reservation, so the sale undersells by one until reconciliation compares the database with Redis and returns it. To shrink the window, the same script can push the reservation onto a Redis list or stream, making the claim and the hand-off atomic in one store.
What do you tell the buyer between the Redis decrement and the database write?
That the reservation is being confirmed. The client polls or is pushed the result, normally within a second. Saying 'it is yours' before a durable record exists turns a Redis failover into broken promises.

Common mistakes

  • Assuming Redis replication is synchronous or that a Sentinel or Cluster failover loses nothing.
  • Treating the Redis counter as the system of record.
  • Sending all traffic straight to the database when Redis is unavailable.
  • Confirming the purchase to the buyer before a durable record exists.
  • Having no way to pause admission during the sale.

A strong answer includes

  • States that Redis replication is asynchronous and a promoted replica can be behind
  • Keeps a conditional update and unique constraint in the database as the final authority
  • Fails closed while Redis is unreachable
  • Pauses admission and rebuilds the counter from the database
  • Distinguishes oversell (unacceptable) from undersell (repairable)
  • Says when the buyer is told the reservation is confirmed

Revise: Design flash-sale inventory

19. In your food delivery design, a customer has paid but the restaurant never confirms the order. What does the system do?

Mid-levelfood-deliverystate-machinesagas

What the interviewer is really testing

Whether you model the order as a state machine with deadlines and compensation instead of assuming every participant responds, and whether you think about the customer's money and what they are told.

Show the model answer, follow-ups and checklist

Model answer

I would start from the state the order is in. It is placed, the payment is authorised but not captured, and the order event has been sent to the restaurant. Nothing else should happen until the restaurant accepts. In particular, no courier is dispatched for an order nobody is cooking.

Knowing whether the order arrived. The restaurant’s tablet holds an open connection, and the app acknowledges receipt of each order automatically. That is separate from a person tapping accept. If there is no receipt after about 30 seconds, the tablet is probably offline, and the system retries and falls back to a push notification. This tells us whether we are dealing with a dead device or a busy kitchen.

Escalation on a timer. A durable timer follows each placed order. After a couple of minutes the tablet sounds a louder alert. A little later an automated phone call goes to the restaurant. At a final deadline, somewhere between 5 and 10 minutes depending on the platform, the order is cancelled.

Cancelling is a compensation. The order moves from placed to cancelled with a conditional update, so if the restaurant accepted a moment earlier the cancel simply does not apply. The payment authorisation is voided with an idempotent call. The customer is told plainly, with similar restaurants suggested.

Being honest with the customer. While waiting, the status says “waiting for the restaurant to confirm”, not “preparing”. The ETA they saw before ordering was a promise, and they should learn early that it is at risk.

Protecting the next customer. A restaurant that has missed orders is marked as not responding in the live state store, so search stops showing it until it reconnects or staff confirm they are back.

The deadline is a trade-off. Too short and you cancel orders a busy kitchen would have accepted a minute later. Too long and a hungry customer waits for food that was never going to come.

Likely follow-ups

The restaurant taps accept at the same moment the deadline cancels the order. What happens?
Both are conditional updates that require the order to still be in the placed state, so the database applies exactly one. If the cancel wins, the tablet shows the order as cancelled. If the accept wins, the cancel job matches no rows and does nothing.
Why authorise the payment at order time instead of capturing it?
A cancelled order then needs only a void, and no money ever moves. A refund of a captured payment can take days to appear on the customer's statement. The cost is that the saga has one more step, the capture on acceptance.
How do you implement the deadline reliably?
With something durable, such as a delayed message per order or a sweeper that scans an index on status and placed time. A timer held in a server's memory is lost when that server restarts. The handler is idempotent, so firing twice is harmless.
How could you catch an offline tablet before anyone orders?
The tablet holds an open connection and sends heartbeats. If they stop for a few minutes during opening hours, the restaurant is marked unavailable in the live state store, and search stops offering it until it reconnects.

Common mistakes

  • Leaving the order waiting indefinitely with the customer watching a spinner.
  • Dispatching a courier before the restaurant has accepted.
  • Capturing the payment up front and then needing a refund.
  • Using in-memory timers for the deadline.
  • Not removing an unresponsive restaurant from search, so the next customer hits the same problem.

A strong answer includes

  • Describes the order's state and that payment is only authorised
  • Separates the tablet acknowledging receipt from a person accepting
  • Escalates before cancelling (alert, phone call)
  • Cancels with a conditional update and voids the authorisation
  • Tells the customer honestly at each stage
  • Marks the restaurant unavailable afterwards
  • Uses a durable timer

Revise: Design food delivery