Interview Study Guide

Guide / System design Fundamentals

9. Failure and recovery — "what happens when X breaks?"

Created · Updated · 8 min read

Interviewers at senior level spend a third of the time here. For each failure, answer in four beats: detect (how you know), contain (stop it spreading), recover (get back to correct), prevent (so it doesn’t recur).

9.1 Resilience toolkit#

  • Timeouts everywhere: connect + read timeouts on every network call; set them from the downstream’s p99, not defaults (many clients default to infinite).
  • Retries with backoff + jitter, only for idempotent operations (section 6.5).
  • Circuit breaker: after N failures in a window, open (fail fast for a cool-down), then half-open (let a few requests test), then close. Prevents piling on a sick dependency.
  • Bulkheads: separate thread/connection pools per dependency so a slow recommendation service can’t exhaust the pool checkout needs.
  • Load shedding & rate limiting: drop low-priority traffic first under overload.
  • Graceful degradation / fallbacks: serve cached or default content (popular products instead of personalized), hide a non-critical widget, queue the write for later.
  • Redundancy: N+1 instances across availability zones; no single points of failure.
  • Health checks + auto-healing: Kubernetes liveness/readiness probes, auto-restart, autoscaling.

9.2 Scenario playbook#

ScenarioWhat to say
Client connection drops mid-request (mobile network)Client retries with the same idempotency key; server dedupes; client can poll GET /orders?idempotency_key= to learn the outcome.
WebSocket drops (chat, live cart, voice)Client reconnects with exponential backoff + jitter, re-authenticates, sends its last received sequence number/offset; server replays missed messages from a buffer or log (Kafka, Redis Stream) and re-syncs state (full snapshot if the gap is too big). Heartbeats/pings detect dead connections; a connection registry (Redis) tracks which gateway holds each user so messages route correctly after reconnecting to a different node.
Server dies mid-processing a queue messageMessage was not acked → redelivered to another consumer after visibility timeout; idempotent consumer makes the replay safe.
Service crashes after DB write, before publishing eventTransactional outbox: the event was in the same transaction; the relay publishes it on restart.
Database primary failsAutomated failover promotes a replica (seconds to a minute); app reconnects via DNS/proxy; writes in flight fail and are retried idempotently; async replication may lose the last few writes → sync/semi-sync for critical data.
Read replica lags badlyRoute reads needing freshness to primary; alert on lag; remove the replica from rotation past a threshold.
Cache cluster downFall back to DB with rate limiting/circuit breaker so the cold-cache load doesn’t kill the DB; warm cache gradually.
Downstream payment gateway slow or downTimeout + circuit breaker; mark payment PENDING, show “processing”; reconcile via webhook/polling; fail over to a second gateway if contracted.
Kafka broker downReplication factor 3 + ISR: a new partition leader takes over; producers with acks=all retry. If the whole cluster is down, producers buffer locally or write to outbox.
Poison messageRetry N times, then dead-letter queue + alert; partition keeps moving.
Network partition between regionsDecide per feature: CP features reject writes in the minority region; AP features accept writes and reconcile later (CRDTs, LWW, app merge).
Thundering herd after recoveryClients retry with jitter; server-side admission control; cache warm-up; staggered restarts.
Bad deployCanary or blue-green catches it on a small % of traffic; automatic rollback on error-rate SLO breach; feature flags as kill switches.
Whole region outageMulti-region active-passive (replicated data, DNS failover) or active-active (data replicated both ways, conflict handling).
Disk full / data corruptionMonitoring and alerts on disk; point-in-time recovery from backups + WAL; test restores regularly.
Clock skewDon’t rely on wall-clock ordering; use sequence numbers, logical clocks, or DB-assigned timestamps.
Retry stormRetry budgets, circuit breakers, and jittered backoff stop retries multiplying load.

9.3 Disaster recovery vocabulary#

  • RPO (Recovery Point Objective) = how much data you can lose (minutes of writes). RTO (Recovery Time Objective) = how long you can be down.
  • Strategies by cost: backup & restore (hours) → pilot light → warm standby → multi-site active-active (seconds, most expensive).
  • Backups are only real if restores are tested. Chaos engineering (kill instances deliberately) proves the system tolerates failure.

9.4 Graceful shutdown#

On SIGTERM: stop accepting new requests (fail readiness), finish in-flight requests, stop consuming from queues and commit offsets, close DB connections, then exit. Without this, every deploy drops requests.

9.5 Resilience patterns in detail#

Timeouts and deadlines. Set a budget per request and propagate it: if the client allows 2 s total, the gateway gives downstream calls the remaining time (gRPC deadlines, X-Request-Deadline). Each hop uses timeouts shorter than its caller’s, so work stops when the caller has already given up. Typical: connect 100–500 ms, read = downstream p99 × 1.5.

Circuit breaker states and numbers.

StateBehaviourTransition
ClosedRequests flow; failures counted in a rolling windowOpens when failure rate ≥ 50% over ≥ 20 calls in 10 s (or slow-call rate high)
OpenFail immediately (or fallback); no callsAfter a cool-down (e.g. 30 s) goes half-open
Half-openAllow a few probe callsSuccess → closed; failure → open again

Combine with a fallback (cached value, default, queue the work) and per-dependency breakers (not one global breaker).

Bulkheads. Separate pools per dependency or per tenant: thread pool for payments (20 threads), another for recommendations (10), so a hung recommender cannot consume the threads checkout needs. Semaphores bound concurrency for async code.

Retry rules. Retry at one layer; idempotent calls only; exponential backoff with jitter; budget (≤10% extra); never retry on 4xx except 408/429; respect Retry-After; hedged requests (send a second request after p95 latency) for tail latency on idempotent reads only.

Graceful degradation ladder. Define in advance which features go first: personalised recommendations → search suggestions → reviews → order history → checkout last. Use feature flags as kill switches so on-call can disable a feature in seconds.

Chaos and game days. Kill instances, inject latency, block a dependency, fail a zone, and verify alerts, failover and runbooks. Start in staging, then production with small blast radius. Test restores, not just backups.

Observability for failures. Golden signals (latency, traffic, errors, saturation), RED for services, USE for resources, distributed tracing with propagated trace IDs, structured logs with request IDs, SLO burn-rate alerts instead of raw thresholds.

Most asked questions#

1. What happens when a dependency is slow or down? Timeouts, circuit breaker, bulkhead, fallback or degrade, queue the work if possible, alert; never let it exhaust shared threads.

2. Explain the circuit breaker. Closed (normal), open (fail fast after a failure threshold), half-open (probe), then close when healthy; protects the caller and gives the dependency room to recover.

3. How do you design for high availability? Remove single points of failure: redundant instances across AZs, replicated data with failover, health checks, stateless services, graceful degradation, tested recovery; define SLOs.

4. What are RPO and RTO and how do they drive design? Data you can lose vs time you can be down; tight RPO needs synchronous replication, tight RTO needs warm standby or active-active; each costs more.

5. How do you do a zero-downtime deployment? Rolling, blue-green or canary with readiness checks, connection draining, backward-compatible schema (expand/contract), feature flags, automatic rollback on SLO breach.

6. What would you do if a database failover loses recent writes? Reconcile from the event log or upstream, use semi-sync replication for critical data, make clients retry idempotently, and alert on replication lag.

Senior-level questions#

1. “A single slow dependency took down the whole API. Post-mortem.” Missing timeouts and shared pools: add bulkheads, tight timeouts, circuit breakers, load shedding, and an SLO-based alert for dependency latency; test with fault injection.

2. “Retries made the outage 10× worse.” Retry amplification across layers; fix with a single retry layer, budgets, jitter, circuit breakers, and server-side admission control.

3. “Your multi-AZ setup still failed when one AZ went down. Why?” Capacity not sized for N−1 (the remaining AZs overloaded), a shared single-AZ dependency (a primary DB or NAT gateway), sticky connections not draining, or health checks that did not detect partial failure. Test AZ failures and size at N+1.

4. “How do you write a good runbook and postmortem?” Runbook: symptoms, dashboards, mitigation steps (rollback, flag, scale), owners, escalation. Postmortem: timeline, impact, root and contributing causes, what went well, action items with owners and dates, blameless tone.

5. “How do you decide which failures to design for?” Rank by likelihood × impact using SLOs and error budgets; handle the common (instance, dependency, deploy) cheaply and the rare catastrophic (region) with a defined RTO/RPO and a rehearsed plan.

Quiz#

1. Why propagate deadlines instead of fixed per-hop timeouts?

Downstream work should stop when the caller has given up; deadline propagation prevents wasted work and keeps total latency within the user’s budget.

2. Name the three circuit breaker states.

Closed, open, half-open.

3. What is a bulkhead?

Isolated resources per dependency or tenant so one failure cannot exhaust shared capacity.

4. When are hedged requests appropriate?

For idempotent reads, to cut tail latency: send a second request after the p95 delay and use whichever answers first.

5. Backups exist. Why is that not enough?

Only tested restores prove recoverability and RTO; schedule restore drills.

Finished this page?Mark it done to track your progress across the guide.
Pritam Ghosh · System design & AI engineering study notes