Sub topic 12
Plan for failure
This chapter assumes you have read the earlier chapters on requirements, the high-level architecture, and scaling with replication, partitioning, and caching. You should also be comfortable reading short Python snippets. The goal is to take a design that works when everything is healthy and describe what happens when parts of it break.
Why failure belongs in the design
At scale, failure is routine. A fleet of 10,000 machines will lose several of them on an ordinary day. Networks drop packets, disks fill up, deployments ship bugs, and a dependency slows down without ever going fully down.
Your requirements chapter should already contain an availability target. This chapter turns that target into design decisions. For each component on your diagram, ask three questions:
- How would I know it has failed?
- What does the user see while it is failed?
- How does it recover, and how much data can it lose?
Turn availability targets into numbers
Availability is the fraction of time the system serves requests correctly. Convert a percentage into allowed downtime so the target means something.
| Availability | Downtime per year | Downtime per 30-day month |
|---|---|---|
| 99% | 3.65 days | 7.2 hours |
| 99.9% | 8.77 hours | 43.2 minutes |
| 99.99% | 52.6 minutes | 4.3 minutes |
| 99.999% | 5.26 minutes | 26 seconds |
Each extra nine costs more engineering. A design that needs 99.99% usually needs automatic failover, because a human paged at 3 a.m. cannot reliably respond within four minutes.
Two rules govern how components combine:
- Components in series (a request needs all of them) multiply their availabilities. Two 99.9% components in a chain give about 99.8%.
- Redundant components in parallel (any one can serve the request) fail only when all fail. Two independent 99.9% replicas give 1 − 0.001² = 99.9999%.
def serial(*availabilities: float) -> float:
result = 1.0
for a in availabilities:
result *= a
return result
def parallel(*availabilities: float) -> float:
all_down = 1.0
for a in availabilities:
all_down *= (1.0 - a)
return 1.0 - all_down
load_balancer = parallel(0.999, 0.999)
app_tier = parallel(0.999, 0.999, 0.999)
database = parallel(0.999, 0.999)
print(f"single chain: {serial(0.999, 0.999, 0.999):.6f}")
print(f"redundant: {serial(load_balancer, app_tier, database):.6f}")The parallel formula assumes failures are independent. Two replicas in the same rack, on the same power feed, or running the same buggy build fail together, so the real number is lower. Spread replicas across failure domains such as racks and availability zones.
Find single points of failure
A single point of failure (SPOF) is a component whose loss stops the whole system. Walk the request path in your diagram from the client to the data and mark every box that exists only once.
Common SPOFs:
- One load balancer or one DNS provider.
- A single primary database with no standby.
- A single message broker node.
- A configuration service, or a shared dependency such as authentication, that every request calls.
- A single region or availability zone.
For each SPOF, either add redundancy or state that you accept the risk and why. Accepting a SPOF is a legitimate decision for a low-stakes internal tool. It is a gap if you never mention it.
Detect failure
Redundancy only helps if the system notices a dead component and stops sending it traffic.
- Health checks. A load balancer probes each instance. A shallow check ("process is up") is fast but misses a broken database connection. A deep check ("can query the database") catches more but can take every instance out of rotation at once when a shared dependency is slow. Use a shallow check for liveness and a deeper one for readiness, and be careful about what a failed deep check does.
- Timeouts. Every network call needs one. A call without a timeout turns a slow dependency into exhausted threads and connections in the caller.
- Heartbeats and leases. A node sends periodic signals. If they stop, the cluster assumes the node is dead. This is a guess. A slow node and a dead node look the same, so the system must tolerate a wrong guess, for example by preventing two nodes from both acting as primary.
Handle failure in the request path
Retries with backoff and jitter
Retrying fixes transient errors, but naive retries make outages worse. If 1,000 clients all retry immediately, a struggling server receives 2,000 requests. The fix is exponential backoff (wait longer after each failure) plus jitter (randomize the wait so clients do not retry in lockstep).
import random
import time
def call_with_retry(operation, max_attempts=4, base_delay=0.1, max_delay=2.0):
for attempt in range(1, max_attempts + 1):
try:
return operation()
except TimeoutError:
if attempt == max_attempts:
raise
ceiling = min(max_delay, base_delay * 2 ** (attempt - 1))
time.sleep(random.uniform(0, ceiling))
calls = {"count": 0}
def flaky():
calls["count"] += 1
if calls["count"] < 3:
raise TimeoutError("simulated slow dependency")
return "ok"
print(call_with_retry(flaky), "after", calls["count"], "calls")Set a retry budget. If every layer in a three-tier system retries three times, one user request can become 27 calls to the database. Retry at one layer, usually the one closest to the user, and cap the total.
Idempotency
A retry is only safe if repeating the operation does not repeat its effect. A timed-out POST /v1/items may have succeeded on the server. Retrying it could create a duplicate. The usual fix is an idempotency key: the client generates a unique ID per logical operation and sends it with the request. The server stores the result under that key and returns the stored result for repeats. Reads and operations such as "set the value to X" are naturally idempotent. "Add 1" is not.
Circuit breakers
A circuit breaker stops calling a dependency that is clearly failing. This protects the caller's resources and gives the dependency room to recover.
While the breaker is open, calls fail immediately or return a fallback instead of waiting for a timeout.
Graceful degradation and load shedding
Decide in advance what the system drops first. A feed service can show cached or slightly stale content when the ranking service is down. A shop can disable recommendations but keep checkout working. Classify features as critical or optional, and make sure optional ones cannot take down critical ones.
When load exceeds capacity, load shedding rejects some requests early (for example with HTTP 503 and a Retry-After header) so the rest finish in time. Serving everyone slowly usually means serving no one, because clients time out and retry.
Protect the data
Stateless servers are easy to replace. Data is where failure costs the most. Two numbers define your recovery goals:
- RPO (recovery point objective): how much recent data you can afford to lose.
- RTO (recovery time objective): how long recovery may take.
Replication choices set the RPO:
| Approach | Data loss on primary failure | Cost |
|---|---|---|
| Asynchronous replication | Writes not yet copied are lost | Low write latency |
| Synchronous replication | None for acknowledged writes | Higher latency, and writes may block if the replica is down |
| Quorum writes (for example 2 of 3 replicas) | None if a majority survives | Moderate latency, more coordination |
Replication is not a backup. A bad deployment or an accidental DELETE replicates to every copy within seconds. Keep point-in-time backups, store them separately from the primary, and restore from them on a schedule. A backup you have never restored is an untested assumption.
For failover, decide how a replica becomes primary. Automatic promotion reduces RTO. It also risks split brain, where the old primary comes back and both accept writes. Fencing (revoking the old primary's ability to write) or consensus-based leader election prevents this.
Queues add their own failure handling. A consumer may crash after reading a message and before finishing the work. Most queues therefore deliver at least once, and consumers must be idempotent. Messages that fail repeatedly go to a dead-letter queue, where they can be inspected without blocking the rest of the stream.
Watch for correlated and cascading failure
Many large outages share a pattern:
- Retry storms. Clients retry a failing service and keep it down after the original fault clears.
- Cache stampede. A popular cache entry expires and thousands of requests hit the database at once. Mitigate with request coalescing, staggered expiry, or serving stale data while one worker refreshes.
- Cold start. A restarted cache is empty, so the database takes full load. Warm caches before shifting traffic.
- Shared fate. Redundant components sit behind the same configuration push, certificate, or deployment. Roll changes out gradually, and keep the ability to roll them back.
A practical checklist
Apply this to your high-level diagram:
- Mark every component that exists once.
- For each dependency call, name the timeout, the retry policy, and the fallback.
- For each write operation, state whether a retry is safe and how.
- Set an RPO and RTO for each data store, and match replication and backups to them.
- Name what you shed or disable first under overload.
- Say what you monitor: error rate, latency percentiles, saturation, and replication lag, with alerts tied to user impact.
Exercise
Your service calls a payment provider with a 2-second timeout and retries up to 3 times with no delay. During a provider slowdown, your own service also becomes slow and users start seeing duplicate charges. Name two changes that address this and explain why each helps.
Show answer
First, add an idempotency key to each payment request so a retry of a request that actually succeeded returns the original result instead of charging again. Second, change the retries to exponential backoff with jitter and a cap on total attempts, and add a circuit breaker. Immediate retries multiply load on the already slow provider and tie up your threads. Backoff with jitter spreads the load out, and the breaker fails fast so your service stays responsive while the provider recovers.