Sub topic 12
Plan for failure
This chapter assumes you have a high-level design and a scaling plan from earlier chapters: replicas, partitions, and a cache. It also assumes you know basic HTTP and database terms. Here you ask a different question about that design: what happens when each part stops working?
Assume every component fails
At scale, failure is routine. Disks fill, processes crash, networks drop packets, and deploys ship bugs. A design that works only when everything is healthy is incomplete.
Walk through your architecture one box at a time and ask three questions:
- What happens to users if this component is down?
- How will we detect that it is down?
- What recovers it, and how long does that take?
Do the same for each arrow between boxes. A slow dependency is often worse than a dead one, because callers wait on it and tie up their own resources.
Find single points of failure
A single point of failure (SPOF) is a component whose loss takes down the whole system. Typical examples are one database primary, one load balancer, or one message broker.
The usual fix is redundancy. Run at least two instances in separate failure domains, such as different servers, racks, or availability zones. Put a load balancer in front of stateless services. Replicate stateful stores and decide how a replica takes over.
Redundancy moves the problem rather than removing it. Something must decide that the primary is dead. That detector, often a health check plus a coordinator, must itself be redundant.
Handle failure in calls
Most failures show up as a failed or slow request. Four patterns cover most cases.
| Pattern | What it does | Watch out for |
|---|---|---|
| Timeout | Stops waiting after a fixed time | Too long wastes threads. Too short causes false failures. |
| Retry with backoff and jitter | Repeats a failed call after growing, randomized delays | Retries multiply load on a struggling service. |
| Circuit breaker | Stops calling a dependency that keeps failing, then probes it later | Needs a sensible fallback when open. |
| Graceful degradation | Serves a reduced result instead of an error | Decide in advance which features are optional. |
Retries are only safe when the operation is idempotent, meaning repeating it has the same effect as doing it once. A retried payment must not charge twice. Give write requests an idempotency key that the server remembers, so a duplicate is recognized and ignored.
import random
import time
def call_with_retry(operation, attempts=4, base_delay=0.1):
for attempt in range(attempts):
try:
return operation()
except ConnectionError:
if attempt == attempts - 1:
raise
delay = base_delay * (2 ** attempt)
time.sleep(delay + random.uniform(0, delay))The random jitter keeps many clients from retrying at the same instant and hitting the service in a wave.
Protect your data
Data loss is usually harder to forgive than downtime. Decide two numbers with the stakeholders:
- Recovery point objective (RPO): how much recent data you can afford to lose.
- Recovery time objective (RTO): how long the system can stay down.
Synchronous replication gives an RPO near zero but adds write latency and can block writes when the replica is unreachable. Asynchronous replication is faster, but a primary crash can lose writes that had not yet reached the replica. This is the trade-off from the previous chapter, applied to failure. Replication is also not a backup. A bad delete replicates instantly, so keep periodic snapshots and test restoring them.
Contain the damage
Limit how far a failure spreads. Use bulkheads, which are separate resource pools such as thread pools or queues per dependency, so one slow service cannot exhaust everything. Apply rate limiting and load shedding, which means rejecting some requests early to keep the rest healthy. Use queues to absorb bursts, and set bounds on them so they cannot grow without limit.
Finally, make failure visible. Track error rate, latency, and saturation, and alert on user-facing symptoms. In a design discussion, name what you would monitor and which alert would fire first.
Exercise
Your service calls a payment provider. The call sometimes times out, and you cannot tell whether the charge happened. Which two mechanisms make a retry safe, and what do you add to avoid overloading the provider?
Show answer
Make the charge idempotent by sending an idempotency key that the provider (or your server) stores, so a repeated request returns the original result instead of charging again. Retry with exponential backoff and jitter, and add a circuit breaker so a provider that keeps failing is not hit with more load.