Interviewers who ask about resilience are rarely checking whether you know pattern names. They want to know whether you can reason about what happens when a dependency gets slow, when traffic doubles, or when two requests update the same row in the same millisecond. Good answers name the failure mode first, then the mechanism that contains it, then the trade-off it introduces. This guide covers the core tools: bounding time, retrying safely, making operations repeatable, isolating failures, refusing work you cannot finish, limiting clients, handling concurrent writes and protecting caches. Each concept comes with a small invented system and a short TypeScript or SQL snippet you can reason about out loud. The pitfalls lists are where most candidates lose points, so read them carefully.
Study order
If time is short, go in this order.
- Timeouts and deadline propagation
Every other pattern assumes calls are bounded in time; without timeouts, retries, breakers and bulkheads cannot work.
- Retries with exponential backoff and jitter
Retries are asked about constantly, and amplification and jitter are where interviewers separate mid from senior answers.
- Idempotency keys for safe repetition
Safe retries depend on it, and payment-style double-charge scenarios are a favourite interview topic.
- Optimistic concurrency and lost updates
Lost updates and check-then-act races show up in nearly every high-concurrency question about shared data.
- Load shedding and backpressure
Understanding congestion collapse and why rejecting work early helps is core to reasoning about overload.
- Bulkheads and concurrency limits
Explains how one slow dependency takes down healthy features and how Little's law sizes the fix.
- Circuit breakers
Well-known pattern; you need to explain its states, trip conditions and fallback, not just name it.
- Rate limiting with a token bucket
A common design question; know the algorithm, its O(1) cost and the distributed atomicity problem.
- Cache stampede protection
A concrete failure mode at high read volume that ties together concurrency, caching and load spikes.
Timeouts and deadline propagation
Every network call without a timeout is a potential resource leak. If a downstream service hangs, your callers keep sockets, threads, memory and connection-pool slots tied up until something else breaks. A timeout turns an unbounded wait into a bounded failure you can handle.
Per-call timeouts are not enough in a chain of calls. If the checkout of an invented shop called Parcelo has an 800 ms budget and calls pricing, then inventory, then payments, each with its own 500 ms timeout, the total can reach 1.5 s while the client has already given up. A deadline is an absolute point in time computed once at the edge and passed down, so each hop uses only what is left.
Pick timeout values from measured latency, typically a little above the dependency's p99 under normal load, not from round numbers. Also make sure the timeout actually cancels the work: abandoning a promise while the request keeps running wastes the very capacity you were trying to protect.
TypeScript
async function withTimeout<T>(fn: (signal: AbortSignal) => Promise<T>, ms: number): Promise<T> {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(new Error(`timed out after ${ms}ms`)), ms);
try {
return await fn(controller.signal);
} finally {
clearTimeout(timer);
}
}
async function checkout(cartId: string): Promise<unknown> {
const deadline = Date.now() + 800;
const remaining = () => Math.max(0, deadline - Date.now());
const price = await withTimeout(
(signal) => fetch(`https://pricing.internal/carts/${cartId}`, { signal }).then((r) => r.json()),
Math.min(300, remaining()),
);
const stock = await withTimeout(
(signal) => fetch(`https://inventory.internal/carts/${cartId}`, { signal }).then((r) => r.json()),
Math.min(300, remaining()),
);
return { price, stock };
}Each hop gets the smaller of its own cap and what is left of the 800 ms checkout budget; aborting the signal cancels the underlying fetch.
Traps
- Relying on library defaults: many HTTP clients and database drivers default to no timeout or to minutes.
- Setting an inner timeout longer than the outer one, so the caller gives up while the callee keeps working.
- Racing a promise against a timer without cancelling the operation, which leaves the request running in the background.
- Forgetting connect timeouts and pool-acquire timeouts; a full connection pool hangs just like a slow server.
Retries with exponential backoff and jitter
Retries fix transient failures: a dropped connection, a 503 during a deploy, a leader election. They also multiply load at exactly the moment a system is struggling, so a retry policy has to be bounded and spread out.
Exponential backoff grows the wait after each failure (100 ms, 200 ms, 400 ms...) up to a cap. Jitter randomises the wait so that thousands of clients that failed at the same instant do not all come back at the same instant. With full jitter you sleep a random time between zero and the current backoff ceiling, which spreads retries well.
Only retry errors that can succeed on a second try: timeouts, connection resets, 429 and 503. A 400 or a validation error will fail forever. And only retry operations that are safe to repeat, which is why retries and idempotency are almost always discussed together.
TypeScript
const sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));
async function retry<T>(
op: () => Promise<T>,
isRetryable: (err: unknown) => boolean,
maxAttempts = 4,
baseMs = 100,
capMs = 2000,
): Promise<T> {
for (let attempt = 1; ; attempt++) {
try {
return await op();
} catch (err) {
if (attempt >= maxAttempts || !isRetryable(err)) throw err;
const ceiling = Math.min(capMs, baseMs * 2 ** (attempt - 1));
await sleep(Math.random() * ceiling);
}
}
}Full jitter: the sleep is uniformly random between 0 and an exponentially growing ceiling, capped at 2 s, with at most 4 attempts.
Traps
- Retry amplification: if three layers each try 4 times, one user request can become 64 calls to the bottom service. Retry at one layer, usually the one closest to the failure.
- Retrying non-idempotent operations such as charging a card without an idempotency key.
- Backoff without jitter, which keeps clients synchronised and produces waves of load.
- Ignoring the overall deadline: a retry that starts after the caller has given up is pure waste.
- No retry budget: under a full outage every request retries, so cap retries to a small share of total traffic.
Idempotency keys for safe repetition
An operation is idempotent if doing it twice has the same effect as doing it once. GET and PUT are idempotent by design; "create a payment" is not. When a client times out it cannot know whether the server did the work, so without idempotency a retry can double-charge.
The usual fix is a client-generated key sent with the request. The server records the key with the result. A repeat with the same key returns the stored result instead of redoing the work. In an invented payments service, Tillwise, the mobile app generates a UUID per checkout attempt and reuses it for every retry of that attempt.
In production the record lives in a database with a unique constraint on the key, written in the same transaction as the side effect, so two concurrent requests with the same key cannot both pass. Store a fingerprint of the payload too: the same key with a different amount is a client bug and should be rejected, not silently answered with the old result.
TypeScript
type Charge = { id: string; amountCents: number };
type Entry = { amountCents: number; result: Promise<Charge> };
const seen = new Map<string, Entry>();
async function chargeOnce(
key: string,
amountCents: number,
charge: (amount: number) => Promise<Charge>,
): Promise<Charge> {
const existing = seen.get(key);
if (existing) {
if (existing.amountCents !== amountCents) {
throw new Error("idempotency key reused with a different payload");
}
return existing.result;
}
const result = charge(amountCents);
seen.set(key, { amountCents, result });
try {
return await result;
} catch (err) {
seen.delete(key);
throw err;
}
}Concurrent duplicates share the same in-flight promise; failures are forgotten so the client may retry. A real service persists this behind a unique index.
Traps
- Generating the key on the server: it must come from the client so retries carry the same value.
- Checking for the key and then inserting it in two separate steps, which lets two concurrent duplicates both proceed.
- Keeping keys forever; give them a retention window that is longer than any client's retry window.
- Assuming message queues deliver exactly once. Most give at-least-once, so consumers must deduplicate too.
Circuit breakers
When a dependency is clearly down, continuing to call it wastes your threads and time and keeps hammering a service that is trying to recover. A circuit breaker tracks failures and, past a threshold, fails fast without making the call.
It has three states. Closed: calls pass through and failures are counted. Open: calls are rejected immediately for a cooldown period. Half-open: after the cooldown, a limited number of probe calls go through; success closes the circuit, failure reopens it.
The breaker is most useful when paired with a fallback. In an invented food delivery app, Forklane, if the recommendations service trips the breaker, the home screen shows a static list of popular restaurants instead of an error. Real implementations usually trip on a failure rate over a sliding window with a minimum request count, rather than a raw counter, so a handful of errors at low traffic does not open the circuit.
TypeScript
type State = "closed" | "open" | "half-open";
class CircuitBreaker {
private state: State = "closed";
private failures = 0;
private openedAt = 0;
private probeInFlight = false;
constructor(private readonly threshold = 5, private readonly cooldownMs = 10_000) {}
async call<T>(op: () => Promise<T>): Promise<T> {
if (this.state === "open") {
if (Date.now() - this.openedAt < this.cooldownMs) throw new Error("circuit open");
this.state = "half-open";
}
const isProbe = this.state === "half-open";
if (isProbe) {
if (this.probeInFlight) throw new Error("circuit half-open, probe running");
this.probeInFlight = true;
}
try {
const result = await op();
this.failures = 0;
this.state = "closed";
return result;
} catch (err) {
this.failures++;
if (isProbe || this.failures >= this.threshold) {
this.state = "open";
this.openedAt = Date.now();
}
throw err;
} finally {
if (isProbe) this.probeInFlight = false;
}
}
}Five consecutive failures open the circuit for 10 s; then exactly one probe decides whether to close or reopen it.
Traps
- Counting client errors such as 404 or 422 as failures; they say nothing about the dependency's health.
- One global breaker for a dependency that has many independent hosts or endpoints, so one bad endpoint blocks healthy ones.
- Letting all traffic through in half-open, which can knock the recovering service over again.
- Tripping the breaker with no fallback and no alert, so users get fast errors and nobody notices.
Bulkheads and concurrency limits
A bulkhead isolates resources so one failing part cannot sink the rest. The classic failure: an invented hotel booking API, Roomly, shares one pool of 200 outbound connections. The invoice PDF service slows to 10 s per call, all 200 connections end up waiting on it, and availability search, which is perfectly healthy, starts failing too.
The fix is separate, bounded pools per dependency or per workload: for example 20 concurrent calls for PDFs and 150 for availability. When the PDF pool is full, extra PDF requests are queued briefly or rejected, and search keeps working.
A semaphore is the simplest bulkhead inside one process. Size the limit with Little's law: required concurrency equals throughput times latency. If availability must handle 1,000 requests per second at 100 ms each, you need roughly 100 concurrent slots, plus headroom.
TypeScript
class Bulkhead {
private waiters: Array<() => void> = [];
private available: number;
constructor(permits: number, private readonly maxQueue: number) {
this.available = permits;
}
async run<T>(op: () => Promise<T>): Promise<T> {
if (this.available > 0) {
this.available--;
} else {
if (this.waiters.length >= this.maxQueue) throw new Error("bulkhead full");
await new Promise<void>((resolve) => this.waiters.push(resolve));
}
try {
return await op();
} finally {
const next = this.waiters.shift();
if (next) next();
else this.available++;
}
}
}
const pdfBulkhead = new Bulkhead(20, 50);
const searchBulkhead = new Bulkhead(150, 300);On release, a permit is handed directly to the next waiter; when no one waits, it goes back to the pool.
Traps
- Unbounded wait queues: they only move the overload into memory and latency.
- Sizing pools by guesswork instead of throughput times latency from real measurements.
- Isolating outbound calls but sharing one database connection pool across all workloads.
- Forgetting that a per-process limit multiplies by the number of instances when you reason about load on the dependency.
Load shedding and backpressure
Every system has a maximum throughput. Past it, accepting more work does not get more done; it makes every request slower until all of them time out. This is congestion collapse, and the fix is to refuse excess work early and cheaply.
Load shedding means rejecting requests at the door when a signal says you are saturated: in-flight count, queue length, or time spent waiting in a queue. A fast 503 with a Retry-After header is far better than a 30 s timeout. Smarter shedding drops low-priority traffic first, for example background sync before checkout.
Backpressure is the same idea pushed upstream: a slow consumer signals a fast producer to slow down instead of buffering without limit. Bounded queues, stream APIs that pause reading when the writer's buffer is full, and pull-based consumers on a message broker are all forms of backpressure.
TypeScript
import { createServer } from "node:http";
const MAX_IN_FLIGHT = 200;
let inFlight = 0;
async function handle(url: string): Promise<string> {
await new Promise((resolve) => setTimeout(resolve, 20));
return `ok ${url}`;
}
createServer(async (req, res) => {
if (inFlight >= MAX_IN_FLIGHT) {
res.writeHead(503, { "Retry-After": "1" });
res.end("overloaded");
return;
}
inFlight++;
try {
const body = await handle(req.url ?? "/");
res.writeHead(200, { "Content-Type": "text/plain" });
res.end(body);
} catch {
res.writeHead(500);
res.end();
} finally {
inFlight--;
}
}).listen(8080);Rejecting beyond 200 concurrent requests costs microseconds and keeps latency stable for the requests that are accepted.
Traps
- Shedding after doing expensive work such as parsing the body or querying the database; reject as early as possible.
- Using CPU percentage as the only signal; in I/O-bound services, queue time and in-flight count react faster.
- Processing requests that already sat in a queue past the client's deadline instead of dropping them.
- Clients that retry every 503 immediately, turning shedding into a retry storm.
Rate limiting with a token bucket
Load shedding protects you from total load; rate limiting protects you from individual clients. It enforces fairness and contracts: an invented public API, Meterly, allows each API key 50 requests per second with bursts up to 100.
The token bucket is the usual algorithm. A bucket holds up to capacity tokens and refills at a steady rate. Each request takes a token; if none is left, the request is rejected with 429. Capacity controls burst size, refill rate controls sustained throughput. It is O(1) per check and stores only two numbers per key.
Alternatives include fixed windows (simple but allow double bursts at window edges) and sliding window counters (smoother, slightly more state). Across many instances the bucket state must be shared, typically in Redis, and updated atomically with a script so concurrent requests cannot both spend the last token.
TypeScript
class TokenBucket {
private tokens: number;
private last = Date.now();
constructor(private readonly capacity: number, private readonly refillPerSec: number) {
this.tokens = capacity;
}
tryTake(cost = 1): boolean {
const now = Date.now();
const refill = ((now - this.last) / 1000) * this.refillPerSec;
this.tokens = Math.min(this.capacity, this.tokens + refill);
this.last = now;
if (this.tokens < cost) return false;
this.tokens -= cost;
return true;
}
}
const buckets = new Map<string, TokenBucket>();
function allow(apiKey: string): boolean {
let bucket = buckets.get(apiKey);
if (!bucket) {
bucket = new TokenBucket(100, 50);
buckets.set(apiKey, bucket);
}
return bucket.tryTake();
}Lazy refill on each call: no timers, constant time, burst of 100 and a sustained 50 requests per second per key.
Traps
- Per-instance buckets behind a load balancer: with 6 instances, the effective limit is six times what you intended.
- Read-then-write updates of shared counters without atomicity, which lets bursts slip through under concurrency.
- Returning 429 without Retry-After or rate-limit headers, so clients cannot back off correctly.
- Keeping a bucket per key forever in memory; evict idle keys.
Optimistic concurrency and lost updates
The lost update is the classic concurrency bug: two requests read the same row, both compute a new value and both write, and the first write disappears. In an invented ticketing service, Stagepass, two buyers read 3 seats left, each buys 2, and the database ends at 1 instead of rejecting one sale.
Optimistic concurrency adds a version column. You read the row with its version, then update with a condition that the version has not changed. If zero rows are affected, someone else won; you re-read and retry or report a conflict. No locks are held between read and write, which suits workloads where conflicts are rare.
When contention is high, such as a hot row everyone updates, optimistic retries waste work and pessimistic locking with SELECT ... FOR UPDATE can be better. Often the simplest fix is a single atomic conditional update that does the arithmetic in the database, with the business rule in the WHERE clause.
SQL
-- Read the current state
SELECT seats_left, version FROM concert_tickets WHERE id = 42;
-- returns seats_left = 3, version = 17
-- Write only if nobody changed the row since the read
UPDATE concert_tickets
SET seats_left = seats_left - 2,
version = version + 1
WHERE id = 42
AND version = 17
AND seats_left >= 2;
-- 1 row affected: purchase succeeded
-- 0 rows affected: conflict or not enough seats; re-read and decideThe version check detects concurrent writers; the seats_left condition enforces the invariant inside the same atomic statement.
Traps
- Check-then-act in application code (read, check, write) without a version or lock, which is a race even inside a transaction at READ COMMITTED.
- Ignoring the affected row count, so conflicts are silently treated as success.
- Unbounded retry loops on conflict under heavy contention.
- Assuming an in-process mutex protects data when several instances share the database.
Cache stampede protection
A cache hides a slow backend until a popular key expires. Then every concurrent request misses at once and hits the database together. If an invented storefront, Glowbox, serves its catalog page at 4,000 requests per second and recomputing it takes 200 ms, an expiry can send hundreds of identical queries to the database before the first one repopulates the cache.
Request coalescing, often called single-flight, makes concurrent misses for the same key share one load: the first caller starts it, the others await the same promise. Within one process this reduces the stampede to one query per instance.
Combine it with jittered TTLs so many keys do not expire at the same second, and with stale-while-revalidate: keep serving the old value while one request refreshes it in the background. For fleets of many instances, a short distributed lock or early probabilistic refresh limits the load to a handful of recomputations.
TypeScript
const inflight = new Map<string, Promise<unknown>>();
function singleFlight<T>(key: string, load: () => Promise<T>): Promise<T> {
const existing = inflight.get(key);
if (existing) return existing as Promise<T>;
const promise = load().finally(() => inflight.delete(key));
inflight.set(key, promise);
return promise;
}
const cache = new Map<string, { value: unknown; expiresAt: number }>();
async function getCached<T>(key: string, ttlMs: number, load: () => Promise<T>): Promise<T> {
const hit = cache.get(key);
if (hit && hit.expiresAt > Date.now()) return hit.value as T;
return singleFlight(key, async () => {
const value = await load();
const jitter = Math.random() * ttlMs * 0.1;
cache.set(key, { value, expiresAt: Date.now() + ttlMs + jitter });
return value;
});
}Concurrent misses share one load per key, and up to 10 percent TTL jitter spreads expirations over time.
Traps
- Caching errors or empty results for the full TTL, which turns a brief failure into a long outage; use a short negative TTL.
- Fixed TTLs on keys written together, so they all expire in the same instant.
- Single-flight without a timeout on the load: one hung call blocks every waiter for that key.
- Assuming in-process coalescing protects the database when hundreds of instances each send their own query.
Common questions
Short answers to the usual doubts.
What is the difference between rate limiting and load shedding?
Rate limiting enforces a per-client contract, such as 50 requests per second per API key, regardless of how busy the server is. Load shedding reacts to the server's own saturation and rejects work from anyone once capacity is reached. A healthy system usually has both: limits keep one client from hogging capacity, shedding protects you when the sum of well-behaved clients is still too much.
Should retries live in the client, a sidecar or the server?
Pick one layer and make the others pass errors through. Retrying at every layer multiplies attempts exponentially with depth. The layer closest to the failing dependency usually has the best information about whether an error is transient, and it should respect the deadline it received from its caller.
When should I choose pessimistic locking over optimistic concurrency?
Optimistic concurrency wins when conflicts are rare, because it holds no locks and costs only a version check. When many writers hit the same row, most optimistic attempts fail and retry, wasting work; then a short SELECT ... FOR UPDATE or a single atomic conditional UPDATE is better. Keep pessimistic lock scopes small and never hold a row lock across a network call.
How do these patterns fit together in one request path?
A typical outbound call is wrapped from the outside in: a deadline from the caller, a bulkhead limiting concurrency, a circuit breaker that fails fast when the dependency is down, retries with jittered backoff for transient errors, and a per-attempt timeout. The operation itself carries an idempotency key so retries are safe, and a fallback handles the case where everything fails.
How do I explain the sizing of a concurrency limit in an interview?
Use Little's law: average concurrency equals arrival rate times average latency. If a service handles 2,000 requests per second at 50 ms, about 100 requests are in flight on average. Set the limit somewhat above that to absorb bursts, then validate with load tests and watch queue time; if latency rises the same throughput needs more slots, which is exactly when you should shed rather than grow.
Now, practise it
Put it to work straight away.
Tests, exercises and problems that use what you've just read.
- Resilience and high concurrencyTake the test
- A slow or failing external providerSolve the exercise
- Retries with exponential backoffSolve the exercise