All posts
System Design Mastermind · F13
  • System design
  • Interview prep
  • Reliability
  • Disaster recovery

Reliability and disaster recovery

Foundations F13. What to say when the interviewer asks "what happens when this dies?": availability maths for chains and copies, failure domains, cells and shuffle sharding, timeouts and retries with backoff and jitter, circuit breakers and bulkheads, health checks and failover, static stability, backups vs replication with RPO and RTO, and the four disaster-recovery strategies and why you drill them. Each idea is told as a story you'll remember, with a lab that splits a year's downtime into its sources.

23 Oct 2026 · 25 min read · interactive

Share

Start here

"What happens when this box dies?" is the question every design gets, usually pointed at the database. A Senior answer doesn't stop at "we have a replica". It says how many nines the design really gets and where the downtime comes from, which failures take every copy at once, how calls give up and retry without making things worse, how a failing dependency is cut off, how fast a dead copy is noticed and replaced, what keeps working while the control systems are down, how much data a mistake can cost, and what happens if a whole region goes dark.

This page covers those eight ideas. Overload, load shedding and retry budgets were on the scaling page; leader election, leases and fencing on the coordination page. Monitoring, alerts and safe deploys come next, on the observability page.

The one story for this page

A monsoon night at a Mumbai hospital

It's a July night in Mumbai. The rain hasn't stopped for two days, the roads around the hospital are flooding, and at 2 am the power goes. Everything on this page happens in that hospital before morning:

  • The ICU needs power, oxygen and the lift all at once, and there are two power feeders so that one can fail. (availability maths: chains and redundancy)
  • Both feeders turn out to come from the same substation. (failure domains and blast radius)
  • Every ward phones the switchboard at the same second, again and again. (timeouts, retries, backoff and jitter)
  • An air conditioner shorts in Ward 3, and its breaker trips before the fault spreads. (circuit breakers and bulkheads)
  • The changeover panel has to decide: is this a flicker, or start the generator? (health checks and failover)
  • The generator runs on diesel already in the tank, not on a tanker someone must order through flooded roads. (static stability)
  • A nurse wrote the wrong dose in the register, and the photocopy in the annexe copied it too. (backups, RPO and RTO)
  • If the building floods, the sister hospital across town takes the patients, if anyone has ever practised it. (disaster recovery and drills)

The hospital is a teaching story. The incidents and numbers cited on this page are real, and the first one is close to home: on 12 October 2020, a grid failure cut power across the Mumbai region and stopped suburban trains, while the stock exchanges kept trading.

✅ Seen: a company said so (cited)🔶 Inferred / typical🧭 Interview choice

Availability maths: chains multiply, redundancy helps

A request that needs every one of several parts is less available than any of them (multiply the availabilities); independent copies of one part multiply their failure chances instead, but only if they truly fail independently.

The story · remember it like this

Power, oxygen and the lift

To move a patient from the emergency room to the ICU on the fourth floor, three things must all work: the power, the oxygen supply and the lift. Each is good on its own, 99% of the time. All three together work only 0.99 × 0.99 × 0.99 ≈ 97% of the time. Every thing the patient needs is another chance to fail.

So the hospital has two power feeders. The ICU goes dark only if both fail at once. If each fails 1% of the time, independently, both fail together 0.01 × 0.01 = 0.01% of the time. That's the deal redundancy offers: one more copy, about two more nines.

The small print is "independently". Hold on to that word for the next idea.

What it really is
  • Availability = share of time (or of requests) that succeed. Each "nine" divides allowed downtime by ten: 99.9% is about 8.8 hours a year, 99.99% about 53 minutes, 99.999% about 5 minutes.
  • In series (a request needs A and B and C): multiply. 30 dependencies at 99.99% each give about 99.7%. Add a dependency, lose availability.
  • In parallel (any one of n copies is enough): unavailability is (1 − a)^n if copies fail independently. Two copies at 99.5% → 99.9975%.
  • Availability also equals MTTF ÷ (MTTF + MTTR): you can raise it by failing less often or by recovering faster. Recovery time is often the cheaper lever (see failover below).

Rules that follow:

  • Fewer hard dependencies on the request path; make the rest optional (serve without them).
  • A critical dependency should be about one nine better than the service that uses it.
  • Measure what users see: successful requests ÷ all requests, per operation.
In a real system ✅ Seen · Netflix; AWS SLA

Netflix's Hystrix documentation spells out the series problem: an application that depends on 30 services, each at 99.99%, gets 99.99^30 ≈ 99.7% uptime; out of a billion requests that's 3,000,000 failures, or "2+ hours downtime/month even if all dependencies have excellent uptime."

Cloud promises show the parallel side. AWS's EC2 service-level agreement (May 2022) commits to 99.5% for a single instance, but 99.99% at region level for instances spread across two or more zones.

Google's "The Calculus of Service Availability" (ACM Queue, 2017) gives the rule of the extra nine, that "critical dependencies must offer one additional 9 relative to your service", and warns that three replicas at 99.9% could reach nine nines only in theory, because real failures are correlated.

Trade-offs
  • More copies raise availability but cost money and, for data, add replication lag or write latency; past three or so independent copies, shared failures dominate and more copies stop helping.
  • Removing a dependency from the request path (cache it, make it optional) often buys more nines than making the dependency itself more reliable.
Say it in the interview

Checkout calls five services in series, so at 99.95% each it's about 99.75% overall. I'll make recommendations and reviews optional, leaving three hard dependencies, and run each across three zones so no single copy failing shows up.

Trap

Multiplying (1 − a)^n for three replicas and announcing nine nines. Interviewers will ask what happens when the zone, the deploy or the config change hits all three at once.

Failure domains, blast radius and cells

Redundancy only counts if the copies don't share what fails: put them in separate failure domains (machines, racks, zones, regions), and split users into cells so one failure hurts a slice, not everyone.

The story · remember it like this

Two feeders, one substation

The hospital paid for two power feeders. At 2 am both go dark together. The electrician checks the drawings: both feeders come from the same substation, and the substation flooded.

Two copies that share a cause aren't two copies. The fix isn't a third feeder from the same place; it's a feeder from a different substation, and a generator that needs no feeder at all.

The hospital also learned the second lesson that night. Every ward was on one big circuit, so the fault in the basement took the whole building. Next year they split the building into wings with their own supply, so a fault darkens one wing, not all of them.

What it really is
  • A failure domain is everything that fails together: a process, a machine, a rack (power, top-of-rack switch), a zone (a data centre or group of them), a region, and also things that aren't places: one config system, one deploy, one DNS provider, one certificate, one team's bad change.
  • Spread copies across domains: replicas in different zones, quorums that survive a zone (3 zones, majority of 3 or 5), and enough spare capacity in the survivors to carry the load (N+1 per zone).
  • Blast radius: how much one failure takes down. Shrink it with cells: independent copies of the whole stack, each serving a fixed slice of users (picked by a partition key), so a bad deploy or poison request hurts one cell.
  • Shuffle sharding: give each customer a random small set of workers, so two customers rarely share the same set and one noisy customer hurts very few others.
  • Deploy in waves: one cell or one zone at a time, so a bad change has a small blast radius before you stop it.
In a real system ✅ Seen · NSE 2021; AWS

India's National Stock Exchange learned the shared-cause lesson on 24 February 2021. NSE said all its links from both its telecom providers became unstable; that hit its online risk management system, itself "configured in a High Availability mode", and trading was halted from 11:40 am, resuming at 3:45 pm (Business Today, 25 Feb 2021). Two providers didn't fail independently.

AWS's Well-Architected guidance gives the numbers for cells: with eight cells split into four fixed shards of two, a problem affects 25% of customers; with shuffle sharding over the same eight cells there are 28 possible pairs, so the scope of impact is 1/28, "seven times better than regular sharding." Colm MacCárthaigh describes the technique as dealing shards "as we might deal hands from a deck of cards" (AWS Architecture Blog, 2014).

Trade-offs
  • More domains (zones, regions) reduce correlated failure but add latency between copies and cost for spare capacity in each.
  • Cells cap the blast radius and make each cell easy to test at its maximum size, but cross-cell features (global search, a user moving cells) need routing and extra work.
Say it in the interview

The three replicas sit in three zones, each zone sized to carry half the peak, so losing one zone needs no scaling. Users are split into cells by account ID, and deploys go cell by cell, so a bad change reaches a few percent of users first.

Trap

Saying "three replicas" without saying where. Same rack, same zone or same deploy pipeline means they can all fail at once.

Timeouts, retries, backoff and jitter

Every remote call needs a timeout derived from the caller's deadline; retry only what is safe, only where it helps, with exponential backoff and random jitter so retries don't arrive in synchronized waves.

The story · remember it like this

Fifty wards, one switchboard

When the power comes back for a moment, every ward picks up the phone to call the switchboard. Fifty calls at once; the operator can take three. Forty-seven wards hear the line ring out, and all forty-seven redial immediately. Then again. The switchboard is busier after the recovery than during the outage.

The senior nurse fixes it with two rules. First: if nobody answers, wait before redialling, and wait twice as long each time. Second: don't all wait the same amount; each ward rolls a die for the extra seconds. The calls spread out and the operator gets through them.

And a third rule: if the patient you were calling about has already been moved, stop calling. The answer isn't useful anymore.

What it really is
  • Timeouts: a call with no timeout can wait forever, holding a thread, a connection and memory. Set each call's timeout from the request's remaining time budget, not a round number per service.
  • Deadlines: pass the remaining time down the call chain, so a server stops working on a request whose caller has already given up.

Retries:

  • Only retry idempotent operations (or use an idempotency key, see the idempotency page).
  • Retry transient errors (timeouts, 503, connection reset), never 400s.
  • Retry at one layer, usually the edge or the client; retries at every layer multiply.
  • Cap attempts (2–3) and keep a retry budget, for example retries ≤ 10–20% of requests.

Backoff and jitter:

  • Exponential backoff: wait base × 2^attempt, capped.
  • Full jitter: wait a random time between 0 and that value, so clients that failed together don't retry together.
  • Backoff spreads out a short spike; it does not remove load. In a long overload, only sending fewer requests helps.
In a real system ✅ Seen · gRPC; Envoy

gRPC doesn't set a deadline by default, so a client can wait indefinitely; its guide says "you should always explicitly set a realistic deadline in your clients", and several gRPC languages pass the deadline on to downstream calls (grpc.io deadlines guide).

Envoy, the proxy under many service meshes, defaults to at most 3 concurrent retries per upstream cluster, and its optional retry budget caps concurrent retries at 20% of active and pending requests (Envoy circuit-breaker docs).

Marc Brooker (AWS) puts the limit of backoff plainly: "The only way to deal with long-term overload is to reduce load, deferring load does not work", and "Backoff is not a substitute for a good retry policy."

Trade-offs
  • Short timeouts free resources fast and fail over quickly, but too short turns slow-but-fine calls into errors and retries; set them from measured p99.9 plus margin, inside the deadline.
  • Retries hide brief blips from users but add load exactly when a system is struggling; a budget keeps the benefit and caps the harm.
Say it in the interview

The page has a 1 s deadline. Each downstream call gets a timeout from what's left, about 300 ms for pricing. Only the API gateway retries, once, with jittered backoff, for idempotent reads, under a 10% retry budget.

Trap

"We'll try three times" at every layer, with a fixed one-second wait. Three layers make that 3 × 3 × 3 = 27 calls per user action at the bottom, all arriving in lockstep.

Circuit breakers and bulkheads

A circuit breaker stops calling a dependency that keeps failing and fails fast instead, testing now and then whether it has recovered; bulkheads give each dependency its own limited pool so one slow dependency can't use up everything.

The story · remember it like this

The breaker in Ward 3

At 3 am the old air conditioner in Ward 3 shorts. Before the wires heat up, the breaker in the distribution board trips. Ward 3's AC is off, but the ward's lights stay on and the rest of the hospital never notices.

The electrician doesn't keep flipping the breaker back while the fault is still there. He waits, then flips it once. If it trips again, he waits longer. If it holds, the AC is back.

And because each ward has its own circuit, the fault couldn't pull the whole floor down with it. Ships do the same with watertight compartments, called bulkheads: one flooded compartment doesn't sink the ship.

What it really is
  • Circuit breaker (wrapped around calls to one dependency) has three states.
  • Closed: calls go through; count failures and timeouts.
  • Open: past a threshold (say 50% failures over 20+ calls), stop calling for a while and fail fast or use a fallback.
  • Half-open: after a cool-down, let a few trial calls through; success closes it, failure opens it again.

Why it helps: the caller stops wasting threads waiting on timeouts, the failing service gets room to recover, and the user gets a quick fallback (cached data, a default, "try later") instead of a slow error.

  • Bulkheads: separate, bounded pools (threads, connections, concurrent requests) per dependency or per kind of traffic. If the recommendations service hangs, it can use up only its own 20 connections, not the 200 that checkout needs.
  • Fallbacks decide the user experience: a stale price is fine for browsing, never for charging; agree on them per call.
  • Breakers live in libraries (Resilience4j, Polly) or in the proxy (Envoy, service meshes), where limits apply without code changes.
In a real system ✅ Seen · Fowler; Envoy

Martin Fowler's 2014 description is still the standard one: "You wrap a protected function call in a circuit breaker object, which monitors for failures", and once failures reach a threshold "the circuit breaker trips"; a half-open state lets a trial call through to see if the problem is fixed.

Envoy implements bulkhead-style limits per upstream cluster, with defaults of 1,024 connections, 1,024 pending requests and 1,024 concurrent requests; once a limit is reached, further requests fail immediately instead of piling up (Envoy circuit-breaker docs). Netflix's Hystrix made the pattern famous by running each dependency's calls in its own small thread pool, so one slow dependency could exhaust only its own pool.

Trade-offs
  • A breaker that trips too easily turns a blip into an outage of that feature; too lazy and callers drown in timeouts. Tune on error rate over a minimum number of calls, not on single failures.
  • Bulkheads waste some capacity (a pool can be idle while another is full), the price of isolation.
Say it in the interview

Calls to the recommendation service go through a breaker: past 50% errors over 20 calls it opens for 30 seconds and the page renders bestsellers from cache. It also has its own pool of 20 connections, so it can never starve checkout.

Trap

Adding a circuit breaker with no fallback, or one shared thread pool for every dependency. The first just changes the error message; the second lets one slow service take everything down.

Health checks and failover

Failover is only as fast as detection plus switch-over: health checks must notice a dead copy quickly without flapping on blips, and clients must actually move to the new copy.

The story · remember it like this

Flicker or failure?

The changeover panel in the basement watches the mains. When the voltage drops, it has to decide. Start the generator on every half-second flicker and it will be starting all night, wearing out the engine and blinking the ICU each time it switches back. Wait two minutes to be sure and the ventilators run on their batteries far longer than anyone would like.

So the panel waits a few seconds, then starts the generator, and the batteries (the UPS) carry the ICU through those seconds. Once the generator is steady, the panel switches over.

There's one more step people forget: each ward's equipment must actually pick up the new supply. A machine that only checks its power source when it's restarted stays dark.

What it really is

Failover time = detect + decide + switch + clients reconnect.

Health checks:

  • A liveness check asks "is this process stuck? restart it". A readiness check asks "can it take traffic right now? if not, take it out of the load balancer". Keep liveness shallow (the process itself); put dependency checks in readiness, or one slow database restarts every pod at once.
  • Detection time ≈ check interval × failures in a row before marking down. 10 s × 3 = 30 s; shorter is faster but flaps on blips.
  • Check from outside too (synthetic requests), because "the process is up" isn't "users can log in".

Failover kinds:

  • Stateless, active-active: the load balancer just stops sending to the dead copy. Fast; the gap is detection.
  • Stateful, primary + standby: detect, fence the old primary (see the coordination page), promote the standby, repoint clients (DNS or a proxy). Slower, and with async replication the last few writes can be lost.

Watch for:

  • Flapping: a copy bouncing in and out of service.
  • Split brain: two primaries at once.
  • Clients that cache DNS forever.
  • Failback: plan the return trip too.
In a real system ✅ Seen · AWS RDS; AWS 2025

Amazon RDS documents the database case: a Multi-AZ failover typically takes 60–120 seconds, triggered by things like a failed host, lost network or OS patching, and it works by changing the DNS record, so AWS recommends a JVM DNS cache TTL of no more than 60 seconds or the application keeps talking to the old address.

Health checks can also fail the wrong way. In AWS's 20 October 2025 us-east-1 event, new instances entered service before their network setup had propagated, so load-balancer "health checks would fail even though the underlying NLB node and backend targets were healthy", alternating between failing and healthy and pulling capacity out of service; engineers disabled automatic health-check failover at 9:36 am PDT and re-enabled it at 2:09 pm (AWS event summary).

Trade-offs
  • Aggressive checks fail over fast but risk false alarms, flapping and split brain; conservative checks are stable but every real failure costs more downtime.
  • Automatic failover handles the 3 am crash; for rare, large events (a region), many teams keep a human decision with a rehearsed runbook, because a wrong automatic regional failover is itself an outage.
Say it in the interview

API pods use a readiness check that's taken out after 3 failures 5 s apart; liveness only checks the process. The database is primary + synchronous standby in another zone, failover in about a minute behind a proxy, so clients don't depend on DNS caches.

Trap

Pointing the liveness probe at the database. When the database is slow, every pod fails liveness, gets restarted at once, and the outage grows.

Static stability: don't depend on what just broke

A statically stable system keeps working through a failure without having to change anything: capacity is already there, config is cached, and the data path doesn't need the control systems to stay up.

The story · remember it like this

Diesel in the tank

The hospital's first emergency plan said: when the power fails, call the diesel supplier and order a tanker. Tonight the roads are flooded and the supplier's phones are down too. The plan needed the very things the storm took away.

The new plan: the tank always holds 48 hours of diesel. Nobody has to order, drive or approve anything for the generator to run tonight. The tanker is for topping up after the storm.

The same goes for the staff roster. The night shift is already inside; the plan doesn't depend on calling people in through the flood.

What it really is
  • The data plane does the work (serves requests, moves packets, reads rows). The control plane changes the system (launches instances, updates config, changes DNS, scales). Control planes are more complex and fail more often; data planes must not need them to keep running.
  • Static stability: during a failure, keep operating in the state you're already in. Pre-provision capacity instead of launching it during the event; cache the last good config and keep using it if the config service is down; keep credentials and certificates valid well past the expected outage.
  • Pre-provisioned spare capacity: with three zones, run each zone with enough capacity that two can carry the peak (about 50% extra), so a zone loss needs no scaling at all.
  • Recovery storms: when a dependency comes back, everything reconnects, re-syncs and retries at once; limit, queue and jitter the recovery work, or the system can't make progress.
  • Ask of every recovery step: does it need something that might be down in this very failure?
In a real system ✅ Seen · AWS 2025

AWS's Fault Isolation Boundaries whitepaper defines static stability as systems that "continue to operate as normal without the need to make changes during the failure or unavailability of dependencies"; a running EC2 instance "does not depend on any control plane APIs in order to stay running", and pre-provisioned extra capacity avoids relying on the EC2 control plane to recover from a lost zone.

The October 2025 us-east-1 event shows both sides (AWS summary). DynamoDB's regional endpoint got an empty DNS record from a race condition at 11:48 pm PDT on 19 October; DNS was fixed by 2:25 am. Existing EC2 instances "remained healthy" throughout, but launching new ones failed until 10:37 am, with some network issues until 1:50 pm: the system that manages physical servers had depended on DynamoDB, and when DynamoDB returned, the backlog of work put it into "congestive collapse" until engineers throttled it. Designs that already had their capacity ran on; designs that needed to launch instances to recover waited.

Trade-offs
  • Static stability costs idle capacity (often 50% extra across three zones) and stale-but-usable config; reactive recovery is cheaper day to day and fails exactly when it's needed.
  • Caching config and credentials keeps you running through a control-plane outage but delays urgent changes (revoking a key); set explicit expiry and an override path.
Say it in the interview

Each of the three zones runs enough instances for 50% of peak, so losing a zone needs no autoscaling or new launches. Services keep the last good config and feature flags in memory if the config service is down, and reconnects after an outage are rate-limited with jitter.

Trap

A recovery plan that starts with "autoscaling launches replacement capacity" or "we update DNS". Both are control-plane actions that may be failing in the same event.

Backups, RPO and RTO: replication is not a backup

Replicas protect you from losing a machine; only backups protect you from losing data to a bug, a bad migration or a wrong command, and a backup counts only once a restore has been tested. RPO is how much data you can lose, RTO how long you can be down.

The story · remember it like this

The photocopy copied the mistake

At 4 am a tired nurse writes the wrong dose in the medicine register. The hospital is careful: every hour, the register is photocopied and sent to the annexe in case the ward floods. So the wrong dose is now in the annexe too.

The copy that saves the patient is the one from the night before, sealed in the records room, together with the slips for every dose given since. Start from last night's copy, replay the slips up to 3:59 am, and you have the register as it was just before the mistake.

Then the records officer asks the question that matters: has anyone ever opened one of those sealed copies to check it can be read?

What it really is
  • RPO (recovery point objective): the most data you can afford to lose, in time. RTO (recovery time objective): the longest you can be down. Set them per kind of data, with the business: payments may need RPO ≈ 0, analytics a day.
  • Replication (sync or async) copies every write, including the bad ones, within seconds. It's for availability. Async replication also loses its lag's worth of writes when the primary dies.
  • Backups are separate, older copies.
  • Snapshots: full or incremental copies, taken every few hours.
  • Point-in-time recovery (PITR): a snapshot plus archived transaction logs, replayed up to just before the mistake.
  • Logical exports: per table or tenant, slower but portable.
  • Delayed replica: a standby that applies changes an hour late, so you can stop it before a bad change lands.
  • Keep backups in another account or region, immutable for a while, so one compromised credential or one region can't delete both.
  • Restores are the product. Test them automatically, measure how long they take (that's your real RTO) and alert when a backup job fails or stops running.
In a real system ✅ Seen · GitLab 2017

GitLab's postmortem of 31 January 2017 is the classic case. An engineer accidentally removed about 300 GB of data on the primary database. The regular pg_dump backups had been failing because of a version mismatch, and the failure emails were being rejected, so nobody knew; disk snapshots weren't enabled for the databases, and the replica had just been wiped during a rebuild. The team restored from a staging snapshot taken about six hours earlier, losing roughly 5,000 projects, 5,000 comments and 700 new user accounts, and GitLab.com was down for about 18 hours.

Google's SRE book sums it up: "No one really wants to make backups; what people really want are restores", and "replication and redundancy are not recoverability." For the tooling, Amazon RDS uploads transaction logs to S3 every five minutes for point-in-time restore, and PostgreSQL's recovery_min_apply_delay keeps a standby deliberately behind, "offering opportunities to correct data loss errors."

Trade-offs
  • Lower RPO means more frequent snapshots or continuous log shipping (storage and I/O cost); lower RTO means smaller restore units, faster storage or a delayed replica ready to promote.
  • Synchronous replication gives RPO ≈ 0 for machine loss but adds write latency, and still doesn't help with a bad write.
Say it in the interview

Orders replicate synchronously to a standby in another zone, so a lost machine loses nothing. For mistakes, we keep PITR for 35 days (RPO about 5 minutes) plus a one-hour delayed replica, copy backups to another account daily, and restore one into staging every week to measure the real RTO.

Trap

"We have three replicas, so we're covered." A DROP TABLE or bad migration reaches all three in a second.

Try it: Where do your downtime minutes come from?

Pick a design and see a year's expected downtime split into its sources: all copies failing by chance, a shared zone or region, the gaps while failover happens, and separately what a bad write costs in lost data and restore time. The verdict flips across the presets: one server needs copies, three copies in one zone need spreading, a slow database failover eats the budget, a single region caps 99.99%, and a second region still can't undo a bad DELETE.

Start from

A small app on one server (99.5% on its own, like a single cloud instance), target 99.9% (8.8 hours of downtime a year).

Where the copies run
Who serves
Backups
What we're sizingNumberHow we got itSo we decide
1 · All copies down at once, by chance
Independent failuresCopies that fail independently multiply their failure chances, so each extra copy adds about two nines here. The catch is the word "independently".44 h a year
budget = (1 − 99.9%) × 525,600 min = 8.8 h a year
one copy is down 0.5% of the time; over a year = (0.5%) × 525,600 = 44 h (500% of budget)
Add copies: 2 independent copies fit this part in the budget.
2 · Shared failure domains
Zone and regionOne power fault, one bad network change or one bad deploy can hit every copy in a zone or region together. That's why step 1's tiny number is rarely the real one.4.8 h a year
every copy is in one zone, so a zone outage takes them all: 4 h × 60 = 4 h
region outage: everything is in one region, so it is down for all 45 min
shared total = 4.8 h (54% of budget)
The shared domains fit, but use most of the budget: little is left for failovers and deploys.
3 · Failover gaps
Time to notice and switchRedundancy isn't instant. Until health checks decide a copy is dead and traffic moves, requests fail. With one primary, every patch restart is a failover too.0 s a year
one copy: nothing to fail over to, so its downtime is all in step 1
Failover gaps fit comfortably.
4 · The year's total
Expected downtimeFix the biggest line first. Adding a fourth copy does nothing when the zone or the failover is what eats the budget.99.4458%
44 h + 4.8 h + 0 s = 2.0 days a year, against a budget of 8.8 h
availability = 1 − 2.0 days ÷ 525,600 min = 99.4458% (target 99.9%)
Over budget by 40 h.
5 · A bad write (not a crash)
Data you'd loseReplication protects you from losing a machine. Only backups (and a delayed copy) protect you from your own mistakes.5 min
a lost primary loses up to 1 s of writes (async replication lag)
a bad DELETE reaches every replica within 1 s, so replicas can't help; the restore point is any minute, up to the last ~5 min of logs → RPO 5 min (allowed 15 min)
restore = 60 min (allowed 4 h); one such day uses 11% of the year's downtime budget
Restore point and restore time both fit. Test them.
6 · Verdict for this design
What you getOne copy can't meet this target: add copiesA 99.5% copy is down about 44 h a year on its own, against a budget of 8.8 h. That's 90% of the downtime. 2 independent copies bring that part down to 13 min; then put them in different zones, or the shared zone becomes the new limit.

Try: on One server, set copies to 2. On 3 copies, 1 zone, switch to Across zones. On DB, slow failover, set health checks to 10 s and promotion to 20 s. On 2 regions, daily backup, switch to point-in-time logs. Model: expected minutes per year from rounded teaching values (zone and region outage hours are averages, not any cloud's figures); copies in different zones are treated as independent, one zone outage a year triggers a failover, and deploys and partial slowdowns aren't counted. Real outages are rarer and longer than averages suggest.

Disaster recovery strategies and drills

For losing a whole region, pick the cheapest strategy that meets your RTO and RPO (backup and restore, pilot light, warm standby, or active-active), then rehearse the switch, because a recovery site you've never used is a guess.

The story · remember it like this

The sister hospital across town

If the ground floor floods, the patients must go somewhere. The hospital has options, from cheap to expensive:

  • An agreement with a sister hospital: send them the records and the patients, and they'll find beds. Cheap, but it takes most of a day.
  • Spare beds kept clean and wired at the sister hospital, ready to be staffed when needed.
  • A small ward there that's always running, with a few staff on duty, which can grow quickly.
  • Two full hospitals sharing patients every day, so losing one just means a busier other one.

None of it matters if nobody has practised. So once a quarter the hospital runs a real drill: an ambulance, a patient (a volunteer), the records, the transfer, with a stopwatch.

What it really is

Four standard strategies, cheapest and slowest first:

  • Backup and restore: copy backups to another region; rebuild everything there when needed. RPO hours, RTO up to a day.
  • Pilot light: data replicated continuously; core infrastructure defined and minimal (databases running, app servers off). RPO minutes, RTO tens of minutes.
  • Warm standby: a scaled-down but fully working copy always running; scale it up and switch traffic. RPO seconds, RTO minutes.
  • Multi-site active-active: every region serves real traffic. RPO near zero, RTO near zero, at the highest cost and complexity (writes across regions, conflicts; see the consistency page).

Make it real:

  • Infrastructure as code, so the second region is built from the same definitions.
  • Data replicated across regions (usually async: say the RPO).
  • A runbook with a named person who declares the disaster.
  • Drills: fail over for real, on a schedule, including failing back. Game days and fault injection (killing instances, cutting a zone) in production find the gaps before a disaster does.

Choose per service: payments and login may need warm standby, while internal reports can wait for backup and restore.

In a real system ✅ Seen · AWS; SEBI 2021

AWS's Well-Architected framework lists exactly these four, with backup and restore at RPO "in hours" and RTO "in 24 hours or less", pilot light at RPO in minutes and RTO in tens of minutes, warm standby at RPO in seconds and RTO in minutes, and multi-region active-active at RPO near zero and RTO potentially zero, "in increasing order of complexity and cost".

Indian market rules show what "rehearse it" means. After NSE's four-hour halt in February 2021, SEBI (22 March 2021) required market infrastructure institutions to declare a disaster within 30 minutes and restore operations, including from the DR site, within 45 minutes of that declaration, with data loss of at most 15 minutes and quarterly DR drills (Business Standard). On Saturday 2 March 2024, NSE ran a special live trading session that switched mid-day from its primary site (from 9:15 am) to its disaster recovery site (11:30 am to 12:30 pm) to test that readiness (Business Today, 14 Feb 2024).

Trade-offs
  • Each step up (pilot light → warm standby → active-active) cuts RTO and RPO and roughly adds cost: idle or duplicated infrastructure, cross-region data transfer, and harder consistency.
  • Automated regional failover is faster but risks failing over on a false alarm; most teams automate the steps and keep a human decision to start them.
Say it in the interview

Payments run warm standby in a second region: async replication with about a second of lag (RPO), scale-up and DNS switch in under 15 minutes (RTO). Reports use backup and restore with a 24-hour RTO. We fail payments over to the other region every quarter and run from there for a day.

Trap

Drawing a second region and calling it DR, with no RTO, no RPO, no one who decides, and no drill. The first real failover is then the test.

Remember it

One line per idea. Read this the night before.

  1. Power, oxygen and the lift: dependencies in series multiply, so cut hard dependencies; independent copies add about two nines each.
  2. Two feeders, one substation: copies that share a cause aren't copies; spread across zones and cut users into cells.
  3. Fifty wards, one switchboard: timeouts from the deadline, retry once at one layer, backoff with jitter, under a budget.
  4. The breaker in Ward 3: stop calling what keeps failing, fail fast with a fallback, and give each dependency its own pool.
  5. Flicker or failure: failover = detect + switch + reconnect; readiness checks dependencies, liveness doesn't.
  6. Diesel in the tank: during a failure, don't need the control plane; pre-provision capacity and cache config.
  7. The photocopy copied the mistake: replication isn't backup; PITR for RPO, tested restores for RTO.
  8. The sister hospital: pick the cheapest DR strategy that meets RTO and RPO, and rehearse it.

Check yourself

Answer out loud, then open.

A service has 99.95% availability and calls six dependencies in series, each also at 99.95%. What availability can it expect, and what would you change?

Multiply: 0.9995^7 ≈ 99.65%, about 30 hours of failure a year instead of the 4.4 hours 99.95% allows.

Changes:

  • Make the non-essential dependencies optional (cache their last answer, render without them), so they leave the series chain.
  • For the hard ones, ask for one more nine (99.995%) or add redundancy in front of them (a cache, a second provider).
  • Put timeouts and fallbacks on every call so a slow dependency becomes a degraded response, not an error.

Say it every hard dependency costs availability; I'd keep three, each a nine better than the service.

Your team says the database is safe because it has three replicas. What questions do you ask?

Where are they, and what can take them all at once?

  • Same rack, zone or region? Same storage system? Same deploy pipeline and config?
  • Is replication sync or async, and how much does a failover lose (RPO)?
  • How fast does failover happen, and who decides: automatic, with fencing?

And the big one: what happens after a bad migration or a DROP TABLE? Replicas copy it within seconds. Ask for point-in-time recovery, backups in another account or region, and the date of the last tested restore.

A downstream service starts timing out. Within minutes your own service is down too, though it's healthy. What happened, and how do you prevent it?

Your threads (or connections) were all stuck waiting on the slow dependency, so nothing was left for other requests. Retries probably made it worse.

Prevent it:

  • Timeouts on every call, set from the request's deadline.
  • A circuit breaker that opens on a high error or timeout rate, failing fast with a fallback.
  • A bulkhead: a separate, small pool for that dependency, so it can't take every thread.
  • Retries at one layer, with backoff, jitter and a budget.
How would you set up health checks for an API running on Kubernetes that depends on Postgres and Redis?

Separate the two questions:

  • Liveness: is the process itself alive (an endpoint that doesn't touch Postgres or Redis)? Failing it restarts the pod, so it must not fail just because a dependency is slow.
  • Readiness: can it serve now (warm, connected, not overloaded)? Failing it takes the pod out of the load balancer without restarting it.
  • A startup probe for slow starts, so liveness doesn't kill a pod still warming up.

Then tune detection: interval × failure threshold, about 15–30 s, and watch for flapping. Add an external synthetic check that logs in, because pods can be ready while users still fail.

Your plan for a zone outage is "autoscaling will launch replacement instances in the other zones". What's wrong with it?

It depends on the control plane (instance launches, scaling decisions, maybe DNS) exactly when the event may be impairing it, and when every other customer is launching too. It also needs boot time.

Better, statically stable:

  • Run each of three zones with enough capacity for half the peak, so two zones carry the full load with no launches.
  • Keep config and feature flags cached, so services run if the config service is down.
  • Rate-limit reconnects and recovery work after the outage.

Autoscaling is then for growth, not for surviving the failure.

An engineer runs a migration that deletes a column's data for all users at 2:10 pm. What do you need to have set up beforehand to recover, and how long will it take?

Not the replicas: they applied the change within seconds.

You need:

  • Point-in-time recovery: a snapshot plus transaction logs, so you can restore to 2:09 pm (RPO about 5 minutes, or less).
  • Or a delayed replica (for example one hour behind): stop it before it applies 2:10, and copy the column back.
  • A rehearsed restore whose time you've measured; that's your real RTO.

Then restore to a separate instance, copy back only the damaged data, and keep writes made after 2:10.

Say it replication is for availability, backups are for mistakes.

The business wants payments to survive a full region outage with at most a minute of lost data and 15 minutes of downtime. Which strategy, and what does it cost?

RPO 1 minute and RTO 15 minutes point to warm standby (or active-active if they want near zero).

Warm standby:

  • Async cross-region replication (lag of seconds, inside the 1-minute RPO).
  • A scaled-down copy of the stack always running, scaled up and given traffic within 15 minutes.
  • A runbook, a named decision-maker, and a quarterly failover drill that runs real traffic there.

Costs: the always-on standby, cross-region data transfer, and the work of keeping both regions identical (infrastructure as code). Backup and restore (hours) or pilot light (tens of minutes) would be cheaper but miss the RTO.

Where you'll use this in the series

Sources

Checked October 2026. Theory and guidance come from Google's SRE book (2016) and ACM Queue (2017), AWS's Well-Architected framework and fault-isolation whitepaper, Martin Fowler (2014) and the Envoy, gRPC, Kubernetes, Amazon RDS and PostgreSQL docs; incidents and rules are as published on the dates shown (GitLab 2017, Mumbai 2020, NSE and SEBI 2021, NSE 2024, AWS October 2025). The lab uses rounded teaching values, not any provider's outage figures.

System Design Mastermind · Foundations

Series home

All of Foundations

18 publishedStart here: the concepts every design uses, each told as a story you'll remember.

F01

How a request travels: DNS, load balancers, gateways and open connections

Name → address (DNS) → open a secure line once and reuse it (TCP, TLS) → nearby copies for static files (CDN) → spread and guard the work (load balancer, gateway) → find colleagues inside (discovery) → keep a line open for live updates.

20 min · interactive Preview
F02

The interview framework: requirements, numbers and scope before boxes

Agree what users must do (three core requirements) → put numbers on how well (p99 latency, availability, durability, staleness) → say what's out of scope → sketch the simple end-to-end design → go deep only where a number breaks it.

22 min · interactive Preview
F03

Back-of-envelope estimation: from users to servers in one minute

Users × actions ÷ 86,400 (≈10⁵) = average per second → × peak factor → split reads and writes → storage = count × size × time × copies → bandwidth × 8 bits → in flight = rate × latency → servers = peak ÷ (capacity × 60%) + 2 spares.

20 min · interactive Preview
F04

APIs and real-time communication: REST, gRPC, retries, webhooks and live updates

Nouns + HTTP verbs (user from the token) → REST outside, gRPC inside → cursor pagination → POST with an Idempotency-Key, retries with backoff and jitter → add, don't change → poll for rare updates, SSE for one-way live, WebSockets for both ways → webhooks are at-least-once → thin connection gateways with resume and push fallback.

22 min · interactive Preview
F05

Databases: data models, indexes and transactions

Relational by default (each fact once, keys, constraints) → key-value / document / wide-column / graph only for a named access pattern → B-tree for reads, LSM for heavy writes → composite index with equality columns first, then the sort → one transaction per local change, made durable by the write-ahead log → know your isolation level → win races with a conditional write and a unique constraint.

24 min · interactive Preview
F06

Replication and sharding: copying and splitting your data

Copies scale reads and survive failures (leader + followers); splits scale writes and size (shards). Replicate first; shard only when data size or write rate outgrows one leader → pick the shard key from the main query → hash it into many fixed slots so growth moves ~1/(N+1) → name your hot key and your one cross-shard query.

25 min · interactive Preview
F07

Caching: hit ratios, invalidation and stampedes

Cache what is read far more than it changes → say the expected hit ratio and size the database for the misses → cache-aside with a TTL; on writes, update the database then delete the key → coalesce misses on hot keys and jitter TTLs → plan for the cache failing or restarting empty, because by then the system depends on it.

24 min · interactive Preview
F08

Consistency, CAP and quorums: what replicas promise

Say what each operation needs, not what the system is: strong (linearizable) for money, stock, seats and uniqueness; read-your-writes for a user's own data; eventual for counts, feeds and pages → during a partition, strong operations fail on the minority side, the rest keep serving (CAP) → on a normal day, strong costs a round trip to a quorum (PACELC) → with N copies, W + R > N makes reads overlap the latest write, but it isn't linearizability.

25 min · interactive Preview
F09

Coordination: clocks, leaders, locks and consensus

Don't order events across machines by wall-clock time; let one leader assign the order → elect that leader by majority vote with increasing terms, so a split network can't elect two → give it a lease so a dead leader is replaced without anyone proving it died → and a fencing token the storage checks, so a paused old leader can't do harm → use consensus (Raft) for the few decisions that must be agreed, not for every request.

25 min · interactive Preview
F10

Queues and event streams

Put a queue between work that can wait and the caller, so a spike becomes lag instead of an outage → use a task queue for jobs and an event log (Kafka) when many consumers need every event, replay or per-key order → key by the entity whose order matters and size partitions for peak consumers → deliver at least once and make consumers idempotent → retry a few times with backoff, then dead-letter → scale on lag → publish through an outbox, never "save, then publish".

25 min · interactive Preview
F11

Idempotency, exactly-once and sagas

Treat a timeout as unknown, never as failed → make writes idempotent by design (set, don't add; client IDs; conditional writes) → for the rest, an idempotency key per intent, stored with the result in the same transaction as the effect → consumers deduplicate by message ID in the same transaction → exactly-once holds only inside one boundary → across services, use a saga of local steps with compensations, not 2PC → compensable steps first, the pivot (capture payment) next, retryable steps last, on a durable orchestrator.

25 min · interactive Preview
F12

Scaling and performance

State latency as a percentile at a stated load → size each tier to the utilisation where its p99 is still flat (pooled, least-request balancing lets you run hotter) → budget fan-out calls against the page deadline, hedge stragglers → scale up first, scale out stateless tiers → name the shared resource (database, lock, connections) that caps the speed-up → find the saturated resource and cut work per request → pre-scale known peaks, autoscale on the signal that saturates → under overload, shed the lowest-priority work fast and budget retries.

24 min · interactive Preview
F13

Reliability and disaster recovery

Turn the target into a downtime budget → cut hard dependencies, because chains multiply → spread copies across zones (cells for blast radius) → timeouts from the deadline, one layer of jittered retries under a budget → circuit breakers with fallbacks and a bulkhead per dependency → fast, non-flapping health checks (readiness checks dependencies, liveness doesn't) → statically stable: spare capacity already running, config cached → PITR plus tested restores, because replicas copy mistakes → the cheapest DR strategy that meets RTO and RPO, drilled.

You're reading this Preview
F14

Observability and safe deployments

Metrics to notice, traces to locate, logs to explain (joined by a trace ID) → watch latency percentiles, traffic, errors and saturation → set an SLO per user journey and treat 1 − SLO as an error budget → page on burn rate over two windows, not on CPU → canary every change on a slice with automated analysis against a baseline → keep every version compatible with its neighbours (expand, migrate, contract) so rollback is always possible → ship dark behind flags, and stage config like code → when it breaks: one commander, mitigate first, blameless postmortem.

25 min · interactive Preview
F15

Security essentials for system design

Prove who the caller is (slow salted hashes, MFA, passkeys, rate-limited login) → carry identity in short-lived signed tokens with revocable refresh tokens, or in sessions you look up → delegate with OAuth code flow + PKCE, sign in with OpenID Connect → check this user against this object on every request, least privilege for people and services, audit logs → TLS 1.3 at the edge, mTLS inside, no trust from network location → envelope encryption with a KMS, secrets in a vault, tokenise what you needn't keep → treat all input as data (parameterise, encode, CSRF tokens, no user-chosen fetches) → absorb floods and abuse at the edge.

26 min · interactive Preview
F16

Search, feeds and geo building blocks

Search: analyse text into terms → inverted index of sorted postings → BM25 or hybrid (BM25 + vectors via RRF) retrieval of ~1,000 candidates → learned ranker → shards with replicas, fed from the database by CDC, refreshed every second. Typeahead: precomputed top-k per prefix in memory. Feeds: push IDs into followers' timelines, pull celebrities at read time, hydrate, filter, rank, page with cursors. Geo: index by cell (geohash, S2, H3), search the cell plus neighbours, exact distance on the few candidates.

27 min · interactive Preview
F17

Data pipelines: batch and stream

Pick batch or stream by how fresh each output must be. Get data in with log-based CDC (snapshot, then the WAL) and schemas that evolve safely; land raw events as Parquet in lakehouse tables partitioned by date. Batch jobs map, shuffle and reduce one partition and overwrite it, so retries and backfills are safe. Stream jobs window by event time, fire on watermarks, decide whether late events wait, correct or drop, and checkpoint state with offsets for exactly-once effect, with transactional or idempotent sinks. Reprocess by replaying retained data (Kappa) rather than keeping two codebases (Lambda).

28 min · interactive Preview
F18

AI foundations: inference, RAG and agents

Latency is time to first token (prefill reads the prompt, compute-bound) plus output tokens × time per token (decode, memory-bound), so stream answers and limit by tokens. GPU memory is weights plus a KV cache per request; long prompts, not users, fill it. Continuous batching shares each weight read across many requests, cutting cost per token by 10× or more until time per token hits its target. Route easy requests to small models, cache shared prompt prefixes, quantize carefully. RAG retrieves, reranks and cites a few permission-filtered chunks; agents are tool-calling loops with budgets, idempotent tools and approval for irreversible steps. Evaluate every change on an eval set, and design so a model fooled by prompt injection still can't do damage.

30 min · interactive Preview

More posts