Fault Tolerance, High Availability, and Disaster Recovery Questions
Keeping a system serving despite failure, from code-level resilience to infrastructure-level recovery: circuit breakers, retries with backoff and jitter, timeouts, bulkheads, graceful degradation, and preventing cascading failures, alongside redundancy, failover (active-active versus active-passive), RPO and RTO objectives, backup and restore, and multi-region failover. Covers dependency-failure isolation, chaos engineering to validate resilience, failure-mode analysis, designing to nines of availability, cost-versus-availability tradeoffs, and recovery runbooks. Spans both the patterns that isolate partial failure and the disaster-recovery planning that restores a business-critical system after a major outage.
Implement a circuit breaker class with closed, open, and half-open states. It should open after a configurable run of consecutive failures, wait a cooldown period, then allow a single trial request in half-open before deciding whether to fully close again. Use whatever language you're comfortable in.
Sample Answer
Approach
A circuit breaker is a state machine with three states and two triggered transitions plus one time-based transition:
stateDiagram-v2
[*] --> CLOSED
CLOSED --> OPEN: consecutive_failures >= threshold
OPEN --> HALF_OPEN: cooldown elapsed
HALF_OPEN --> CLOSED: probe succeeds
HALF_OPEN --> OPEN: probe fails
CLOSED --> CLOSED: call succeeds, reset counter
The implementation needs: a counter for consecutive failures, a timestamp for when the breaker opened, a lock so state transitions are atomic under concurrent callers, and a guard in the HALF_OPEN state that only lets exactly one trial call through at a time (otherwise every thread that arrives during HALF_OPEN would fire its own trial simultaneously, defeating the point of testing recovery with a single probe). Work happens outside the lock so a slow downstream call doesn't block every other thread from checking the breaker's state.
Code (Python)
import time
import threading
from enum import Enum
class CircuitOpenError(Exception):
pass
class State(Enum):
CLOSED = "closed"
OPEN = "open"
HALF_OPEN = "half_open"
class CircuitBreaker:
def __init__(self, failure_threshold=5, cooldown_seconds=10.0):
self.failure_threshold = failure_threshold
self.cooldown_seconds = cooldown_seconds
self._state = State.CLOSED
self._consecutive_failures = 0
self._opened_at = None
self._half_open_probe_in_flight = False
self._lock = threading.Lock()
@property
def state(self):
with self._lock:
self._maybe_recover()
return self._state
def _maybe_recover(self):
# caller must hold self._lock
if self._state == State.OPEN and self._opened_at is not None:
if time.monotonic() - self._opened_at >= self.cooldown_seconds:
self._state = State.HALF_OPEN
self._half_open_probe_in_flight = False
def call(self, fn, *args, **kwargs):
with self._lock:
self._maybe_recover()
if self._state == State.OPEN:
raise CircuitOpenError("circuit is open, call rejected")
if self._state == State.HALF_OPEN:
if self._half_open_probe_in_flight:
raise CircuitOpenError("half-open probe already in flight")
self._half_open_probe_in_flight = True
try:
result = fn(*args, **kwargs)
except Exception:
with self._lock:
if self._state == State.HALF_OPEN:
self._trip()
else:
self._consecutive_failures += 1
if self._consecutive_failures >= self.failure_threshold:
self._trip()
raise
else:
with self._lock:
self._consecutive_failures = 0
self._state = State.CLOSED
self._half_open_probe_in_flight = False
return result
def _trip(self):
# caller must hold self._lock
self._state = State.OPEN
self._opened_at = time.monotonic()
self._half_open_probe_in_flight = False
Verified against pinned assertions (deterministic, no wall-clock claims beyond a fixed 0.05s cooldown used only to make the test itself run fast):
def run_test():
calls = {"n": 0}
def flaky(should_fail):
calls["n"] += 1
if should_fail:
raise RuntimeError("boom")
return "ok"
cb = CircuitBreaker(failure_threshold=3, cooldown_seconds=0.05)
# 3 consecutive failures trips OPEN
for _ in range(3):
try:
cb.call(flaky, True)
except RuntimeError:
pass
assert cb.state == State.OPEN
# calls are rejected without invoking fn while OPEN
calls_before = calls["n"]
try:
cb.call(flaky, False)
assert False, "expected CircuitOpenError"
except CircuitOpenError:
pass
assert calls["n"] == calls_before
# after cooldown, HALF_OPEN allows exactly one trial; success closes
time.sleep(0.06)
assert cb.state == State.HALF_OPEN
assert cb.call(flaky, False) == "ok"
assert cb.state == State.CLOSED
# a failing trial in HALF_OPEN re-opens immediately
for _ in range(3):
try:
cb.call(flaky, True)
except RuntimeError:
pass
time.sleep(0.06)
assert cb.state == State.HALF_OPEN
try:
cb.call(flaky, True)
except RuntimeError:
pass
assert cb.state == State.OPEN
print("all assertions passed")
run_test() # prints: all assertions passed
Key points
- State transitions and counter updates all happen inside
self._lock; the wrapped functionfnexecutes outside the lock so one slow call can't block every other caller from even checking the breaker's state. _half_open_probe_in_flightis what limits HALF_OPEN to a single trial call; without it, every thread that arrives during the cooldown window would fire its own simultaneous trial against a possibly-still-struggling dependency.- A failure while HALF_OPEN re-opens immediately, it does not require re-accumulating
failure_thresholdfailures again, because a single failed trial is already sufficient evidence the dependency hasn't recovered. time.monotonic()is used instead oftime.time()for the cooldown comparison, since wall-clock time can jump (NTP adjustment, manual clock change) but monotonic time cannot go backwards.
Complexity
Every operation (call, state, _maybe_recover, _trip) is O(1) time and the breaker holds O(1) state (a state enum, a counter, a timestamp, one boolean), independent of call volume or history length.
Edge cases
- Concurrent trial races in HALF_OPEN: handled by
_half_open_probe_in_flight; a second thread arriving while a trial is in flight gets rejected immediately rather than launching a second simultaneous probe. - Long-running trial call: the single-probe guard limits it to one concurrent trial, but a probe that hangs for a long time (rather than failing fast) delays recovery detection; a production version would typically pair the breaker with a timeout on the wrapped call itself so a hung probe can't block recovery indefinitely.
- Distributed instances: this implementation is single-process, in-memory state; if the same logical breaker needs to be shared across multiple service instances (so instance A tripping also stops instance B from hammering the same dependency), the state has to move to a shared store (Redis, or a sidecar) with the same atomicity requirement, which changes the performance and failure-mode profile (the shared store becoming a dependency of its own).
- Bulkhead-limited half-open probing: some implementations allow a small fixed number of concurrent HALF_OPEN trials (say 2 to 3) rather than exactly 1, trading a slightly larger blast radius during recovery testing for faster convergence back to CLOSED when the dependency genuinely has recovered; that's a one-line change to compare
_half_open_probe_in_flightagainst a max count instead of a boolean. - Success/failure classification: this implementation treats every exception as a breaker-relevant failure; a production breaker usually needs to distinguish exceptions that indicate the dependency is unhealthy (timeouts, connection errors, 5xx) from exceptions that are just normal application-level outcomes (a 404, a validation error) that shouldn't count against the breaker at all.
Design a chaos experiment to validate cross-region failover for a service running in two regions. Walk through how you'd define steady state with concrete SLIs, simulate a network partition isolating one region, control the blast radius, and validate correctness and availability once the experiment ends.
Sample Answer
Validating cross-region failover as a chaos experiment means proving, under controlled conditions, that isolating one region actually degrades gracefully instead of cascading, and doing that with a stated baseline, a bounded blast radius, and a predefined rollback trigger so the experiment itself never becomes the outage it's trying to prevent.
Experiment flow
flowchart TD
A[Capture steady-state baseline] --> B[State hypothesis]
B --> C[Pre-checks: runbook, on-call, dashboards ready]
C --> D[Canary: partition 1% of inter-region traffic]
D --> E{Within rollback thresholds?}
E -- No --> R[Rollback immediately]
E -- Yes --> F[Full partition: isolate target region]
F --> G[Observe against baseline]
G --> H{Within rollback thresholds?}
H -- No --> R
H -- Yes --> I[Restore connectivity]
I --> J[Validate consistency + replication catch-up]
R --> J
Steady state, with concrete SLIs
Pin illustrative baselines for a two-region service (established from a real 7-day traffic window in practice, stated here as inputs to the experiment plan): global p95 latency under 200 ms, regional availability at or above 99.95%, error rate at or below 0.1%, and cross-region replication lag with a median under 50 ms. These are the exact metrics the experiment will compare against during and after the fault injection, chosen because they're already the numbers the service's on-call would check during a real incident, not new ones invented for this experiment.
Hypothesis
"Isolating the target region from the rest of the network will not drop global availability below 99.8% or push p95 latency above 350 ms, because the load balancer's health checks detect the partition within N seconds and reroute traffic to the healthy region, and in-flight writes to the isolated region fail closed rather than silently succeeding." Stating it this way makes the experiment falsifiable: either the reroute happens fast enough and writes fail safely, or it doesn't, and either outcome is useful.
Fault injection design
Simulate the partition at the network layer (block inter-region traffic between the two regions while leaving each region's intra-region networking untouched) rather than manipulating DNS or client routing, since the goal is to test whether the system's own failure detection and reroute logic works, not to manually route around a fault that was never actually detected.
Blast-radius control
Run in two phases, never full-scale first:
- Canary phase: isolate a small fraction (for example 1%) of inter-region traffic, or run the test against synthetic/shadow traffic before any real user traffic, to catch an obviously broken assumption cheaply.
- Full phase: only after the canary phase stays within thresholds, isolate the target region fully, during a scheduled low-traffic window, with the on-call team aware and dashboards open.
Rollback criteria (defined before the experiment starts, not decided mid-experiment)
Immediate rollback if any of: global availability drops below 99.8% sustained for more than 2 minutes, p95 latency exceeds 350 ms sustained for more than 2 minutes, error rate exceeds 5x the steady-state baseline sustained for more than 2 minutes, or any write is observed to succeed on both sides of the partition (a split-brain signal, which is the most severe possible finding since it means the failure-detection assumption in the hypothesis is simply wrong).
Post-experiment validation
After restoring connectivity: confirm replication lag returns to its steady-state baseline (not just that it's decreasing), and run a consistency check on any writes accepted during the partition window, comparing record counts and using idempotency/version keys to detect and reconcile any conflicting writes rather than assuming the reconciliation logic worked silently. Only after both checks pass is the experiment considered closed; a rollback that "looked fine" on live dashboards but left an unreconciled write behind is a false negative that the consistency check exists specifically to catch.
Trade-offs and pitfalls
The most dangerous shortcut is skipping the canary phase and going straight to a full regional isolation "because staging already validated it": staging traffic patterns and real production traffic patterns diverge in exactly the ways that matter for a partition test (real geographic distribution, real retry storms from real clients), so the canary phase against a small slice of real traffic is not optional. A second pitfall is defining rollback thresholds around availability and latency alone and missing data-correctness signals: a partition that stays within latency and error-rate thresholds but produces a split-brain write is a worse outcome than one that trips the availability threshold and rolls back cleanly, so the rollback criteria need a correctness trigger, not just a performance one. This same experiment design, steady-state baseline, hypothesis, canary-then-full injection, predefined rollback, post-hoc consistency check, applies with the target system swapped: a checkout flow (does payment processing fail closed or silently double-charge during the partition), a payments-compliance path (does an audit trail stay complete), a GPU training job (does a worker resume cleanly from checkpoint or corrupt its gradient state), a primary database failover (does the promoted replica actually have every acknowledged write), or a task scheduler's dependency graph (do downstream jobs correctly wait rather than run against stale upstream data). The steady-state SLIs and the specific failure signal change per target; the shape of the experiment doesn't.
You're using DNS failover with a 5-minute TTL, but in practice you're seeing a 3-minute real-world failover window, and it's too slow. How would you redesign this to get failover under 30 seconds for most clients, and what do you give up to get there?
Sample Answer
Direct answer
The 5-minute TTL isn't the actual bottleneck: DNS caching in the real world (ISP resolvers with minimum-TTL floors, browser caches, persistent keep-alive connections that never re-resolve at all) means real failover time doesn't track the advertised TTL cleanly, which is exactly why you're seeing 3 minutes instead of something close to 5. Getting under 30 seconds for most clients means building an explicit time budget (detect, update, propagate) that sums under 30s for compliant clients, and accepting that DNS alone can't guarantee it for the tail of clients whose resolvers or connections don't re-check in time.
Building the time budget
Tfailover≤(k×interval)+Tpush+TTLwhere k is the number of consecutive failed health checks required before failing over (the detection threshold) and interval is the health-check period.
sequenceDiagram
participant C as Client
participant R as Resolver
participant D as Authoritative DNS
participant H as Health Monitor
participant A as Origin A
participant B as Origin B
H->>A: probe every 5s
A--xH: 2 consecutive failures (10s)
H->>D: update record to B
C->>R: resolve hostname
R->>D: query (TTL expired)
D-->>R: return B, TTL 10s
R-->>C: B
C->>B: connect
Worked example
Redesign inputs: health-check interval 5s, failure threshold k=2 (avoids single-blip flaps), API-driven record push under 1s, and TTL lowered from 300s to 10s.
TdetectTpushTttlTfailover≤2×5s=10s≈1s=10s≤10+1+10=21s<30sThat covers clients and resolvers that honor the lowered TTL, with about 9 seconds of margin. It does not cover the two categories that caused the original 3-minute number: resolvers that enforce a minimum TTL floor above what you set, and clients holding a persistent connection that has no reason to re-resolve DNS at all until it errors. For those, add a client-side backstop that's independent of TTL: short keep-alive and idle timeouts so connections periodically re-establish (and therefore re-resolve), and connect-level retry to a secondary IP on failure (a Happy-Eyeballs-style fallback) rather than trusting DNS to be the only failover signal.
Trade-offs and pitfalls
What you give up: a 10s TTL multiplies authoritative DNS query volume roughly 30x versus the 300s baseline, which is a real cost and load increase on your DNS infrastructure, and a false-positive failover (from setting k too low) now flips production traffic in as little as 5 to 10 seconds, so your health check needs to be more conservative about what counts as "down," not less. The pitfall that caused the original bug is assuming all clients and resolvers honor your TTL uniformly; they don't, and any redesign that only lowers the TTL without a client-side or network-level backstop will hit the same wall for the same tail of misbehaving resolvers, just with a lower number attached to it.
What's the difference between fault tolerance, high availability, and resilience? Give a concrete example of each, and explain how they show up in operational metrics like MTTR and MTBF.
Sample Answer
Fault tolerance, high availability, and resilience are related but answer different questions. Fault tolerance means a failure is masked entirely: the system keeps producing correct output with no visible interruption. High availability (HA) means downtime is minimized and recovery is fast, but a brief, bounded interruption is expected and acceptable. Resilience is the broadest term: the system's ability to keep delivering acceptable service under any kind of stress, not just component failure, including load spikes, bad inputs, or a slow dependency, usually by degrading gracefully rather than failing outright.
How each shows up architecturally
| Property | What it guarantees | Typical mechanism | Concrete example |
|---|---|---|---|
| Fault tolerance | No visible interruption during a failure | Redundant, synchronized components that vote or replicate in lockstep (RAID, dual power supplies, Raft/Paxos-replicated state) | A 3-node Raft cluster loses one node; the other two still form a quorum (a majority of the cluster, here 2 of the original 3 nodes, enough to safely keep operating and elect a leader if needed) and serve every request with zero downtime |
| High availability | Short, bounded interruption, fast automated recovery | Health-checked redundancy plus automated failover (active-passive DB failover, load-balanced app tier) | A primary database instance crashes; a monitor detects it in seconds and promotes a replica, so the outage is measured in seconds to low minutes, not zero |
| Resilience | Acceptable service continues even when something can't be masked or failed over cleanly | Circuit breakers, timeouts, bulkheads, graceful degradation, autoscaling | A recommendation service starts timing out; the product page serves without recommendations instead of failing the whole page load |
Fault tolerance and HA are usually about infrastructure failing; resilience is about the system's response to any kind of stress, including ones where nothing has technically "failed" yet (a slow but technically-up dependency, for instance).
Effect on MTTR and MTBF
MTTR (mean time to repair/recover) and MTBF (mean time between failures) combine into steady-state availability:
A=MTBF+MTTRMTBFFault tolerance mainly extends effective MTBF from the user's point of view: individual component failures still happen at whatever rate they happen, but they don't count as user-visible failures because they're masked, so the failure interval a customer would notice grows. High availability mainly drives MTTR down: the goal isn't to prevent the primary from ever failing, it's to make detection and recovery fast and automatic. Resilience patterns move both numbers in the same direction from a different angle: a circuit breaker doesn't prevent a dependency from failing (MTBF of the dependency is unchanged) but it prevents that dependency's failure from becoming your incident at all, which is a third way to improve the user-visible number.
Worked example
Take a service with a component MTBF of 720 hours and an MTTR of 30 minutes (0.5 hours) once a failure is detected and recovered:
A=720+0.5720=720.5720≈0.99931(99.931%)That converts to annual downtime using 525,600 minutes per year (365 days × 24 hours × 60 minutes):
(1−0.99931)×525,600≈364.8 minutes/year≈6.08 hours/yearNow compare two improvements starting from that baseline, holding the other variable fixed:
- Cut MTTR to 5 minutes (better HA: faster automated failover) with MTBF unchanged at 720h: A=720/720.083≈0.999884, about 61.0 minutes/year of downtime, a ~6x reduction driven entirely by faster recovery.
- Double MTBF to 1440 hours (better fault tolerance: the failure that used to happen now gets masked half as often) with MTTR unchanged at 30 min: A=1440/1440.5≈0.999653, about 182.4 minutes/year, a 2x reduction.
Neither number is "the metrics." They're two independent levers on the same availability formula, and which one is cheaper to pull depends on the system: automating failover (MTTR) is often cheaper than adding redundant hardware paths everywhere (MTBF).
Trade-offs and pitfalls
The common mix-up in interviews is treating "high availability" as if it means "never goes down," which is what fault tolerance actually promises, and at a much higher engineering cost (consensus protocols, lockstep replication) than HA's health-check-and-failover pattern. A resilient system is not automatically fault-tolerant or highly available either: a service with excellent circuit breakers and graceful degradation for its dependencies can still have a single database with no HA story of its own. These three properties are complementary, not substitutes, and a system typically needs different amounts of each depending on the blast radius of the component: mask failures (fault tolerance) for the smallest, cheapest, most critical primitives; fail over fast (HA) for stateful tiers where full masking is expensive; and degrade gracefully (resilience) at the edges where "reduced functionality" beats "hard failure." The same reasoning applies outside a classic web-service stack too: a GPU training job gets fault tolerance from checkpointing plus redundant nodes (a crashed worker resumes from the last checkpoint instead of restarting the whole job), and a data pipeline gets resilience from feature-store (a system that serves precomputed inputs to a machine-learning model) fallback values or a stale-but-served cache when an upstream API is delayed rather than hard-failing the request.
What does 'blast radius' mean when you're talking about a production failure? Name a few concrete engineering practices that reduce it, and what that costs you.
Sample Answer
Direct answer
Blast radius is the scope of impact when a component fails: how many users, tenants, or dependent services are affected, and how severely, not just whether the failure happened at all. Reducing blast radius means designing so a single failure touches the smallest possible slice of the system, which makes outages smaller, easier to detect, and faster to recover from, even if it doesn't reduce how often failures happen at all.
Practices that reduce it, and what they cost
| Practice | How it shrinks blast radius | What it costs |
|---|---|---|
| Circuit breakers | Stop repeated calls to a failing dependency, isolating the failure to the caller instead of letting it spread | Added latency and complexity in the failure path; a poorly tuned breaker can trip on transient blips |
| Finer-grained service decomposition | A failure or overload in one bounded service only affects its own consumers, not unrelated functionality | More services to deploy, monitor, and operate; cross-service calls add their own new failure modes |
| Bulkheads (per-tenant or per-dependency resource pools) | One tenant's or one dependency's exhaustion doesn't consume capacity meant for everyone else | More total resources provisioned (dedicated pools cost more than one shared pool sized for the average case) |
| Traffic shaping and rate limits | Caps how much load a single misbehaving client or spike can push into downstream systems | Legitimate bursty clients can get throttled unless limits are tuned carefully |
Worked example
Consider a service with 1,000 tenants sharing a single connection pool. If that pool exhausts, every tenant is affected. Now split that same total capacity into 10 isolated pools of 100 tenants each, so each pool serves 100 of the 1,000 tenants and only that pool's own tenants are affected if it exhausts:
1,000100=10% of tenants affected (isolated pools)vs.100% (shared pool)Splitting the same total capacity into 10 pools of 100 tenants each means a single pool's exhaustion now affects only 100 of the 1,000 tenants, 10% of the blast radius of the shared-pool design, for the same total resources. The cost is operational: 10 pools to monitor and size instead of one, and if traffic isn't evenly distributed across tenants, some pools may be under-utilized while others are tight, which the shared pool didn't have to worry about.
Trade-offs & pitfalls
Reducing blast radius is generally a trade of operational complexity and some resource inefficiency for smaller, more contained failures; it doesn't reduce the underlying failure rate of any individual component. The common mistake is treating blast-radius reduction as free: partitioning by tenant, region, or dependency multiplies the number of things to monitor and can hide a systemic bug (one that affects every partition equally) behind what looks like ten separate, unrelated small incidents instead of one clearly systemic one.
Unlock Full Question Bank
Get access to all Fault Tolerance, High Availability, and Disaster Recovery interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.