Sub topic 12
Design patterns for higher availability
This chapter assumes you know how to convert nines into a downtime budget. It also assumes you know the series and parallel formulas, and that you can read short Python snippets. The earlier chapters gave you the arithmetic. This one covers the engineering patterns that move the numbers.
What the patterns are trying to do
Every availability pattern does at least one of four things:
- It lowers the chance that a component fails.
- It shortens the time to recover (MTTR).
- It limits how many users one failure can reach.
- It lets the service keep working, in a reduced form, while something is broken.
Keep these four goals in mind when you read about a pattern. If you can't say which goal a pattern serves, you probably don't need it yet.
Remove single points of failure
A single point of failure (SPOF) is a component whose failure takes the whole service down. In series math, a SPOF is a factor in the product that has no redundant partner. Finding SPOFs is the first design task. Walk the request path from the user to the data, and for each hop ask what happens if that one thing disappears.
Common SPOFs include one load balancer, one database primary, one DNS provider, one certificate that expires on a known date, and one engineer who knows how to deploy.
The usual fix is to run several copies behind a load balancer that stops sending traffic to unhealthy copies. There are two main layouts:
| Layout | How it works | Strength | Weakness |
|---|---|---|---|
| Active-active | All copies serve traffic at once | No failover step. Capacity is used all the time. | Each copy must be able to carry the extra load when others fail |
| Active-passive | One copy serves, a standby waits | Simple for stateful systems. Easy to reason about. | Failover takes time, and the standby is often untested |
An active-active pair only gives the benefit you computed with the parallel formula if the survivors can handle the full load. Two servers each running at 70% utilization are not redundant. When one fails, the other needs 140% of its capacity and fails too. This is called N+1 capacity planning: provision enough that losing any one unit still leaves you able to serve peak load.
Failover time is downtime
The parallel formula treats redundancy as instant. Real failover is not. The system has to notice the failure, decide, and redirect traffic. During that gap, requests fail.
Suppose a health check runs every 10 seconds and needs 3 consecutive failures before it marks a node dead. Detection alone takes up to 30 seconds. If clients then wait on a DNS record with a 60-second TTL, the total can reach about 90 seconds per failover. If your target is 99.99% over 30 days, your budget is 4.32 minutes, or about 259 seconds. Three such failovers use up the whole budget even though the redundancy "worked".
This is the MTTR lever from the earlier chapter applied to design. To shrink failover time:
- Use shorter health-check intervals, with care. Very aggressive checks cause false positives and make flapping worse.
- Fail over at the load balancer or with a virtual IP, which switches in seconds, not at the DNS layer.
- Let clients retry against another endpoint without waiting for any central decision.
Also test failover regularly. A standby that has never taken traffic is a hope, not a control.
Isolate failure domains
Redundancy only helps if the copies fail independently. Copies in the same rack, zone, or deployment share fate. A failure domain is a set of resources that can fail together because of a common cause. Spread copies across domains: separate hosts, racks, availability zones, regions, and even separate providers where the stakes justify it.
Two related patterns limit the blast radius:
- Bulkheads give each workload its own pool of resources, such as separate thread pools or connection pools per dependency. If one dependency hangs, it exhausts only its own pool, not everything.
- Cells (also called shards or pods) split the whole stack into independent copies, each serving a slice of customers. If one cell fails, only its slice is down. With 10 equal cells, a total failure of one cell is a 10% partial outage. That is much easier to keep inside an SLO than a 100% outage.
Notice that the router is still shared. Cell designs push the SPOF up to a thin layer, which you then keep small, simple, and heavily tested. A shared layer cannot be removed entirely, but it can be made much less likely to fail than the layers beneath it.
Timeouts, retries, and backoff
Most failures between services are transient: a dropped connection, a node restarting. A retry can hide them. If one attempt fails independently with probability 0.01, three attempts all fail with probability 0.01³.
def availability_with_retries(p_fail, attempts):
return 1 - p_fail ** attempts
print(availability_with_retries(0.01, 1)) # 0.99
print(availability_with_retries(0.01, 3)) # about 0.999999The result assumes independent failures. If the cause is a dead dependency or an overloaded server, every retry fails too, and the extra attempts only add load. Follow these rules:
- Always set a timeout. A call with no timeout can hang forever and tie up resources, turning a slow dependency into an outage.
- Retry only operations that are safe to repeat (idempotent), or attach an idempotency key.
- Use exponential backoff with random jitter, so thousands of clients do not retry in lockstep.
- Cap retries at one layer. If three layers each make 3 attempts, one user request can become 27 calls to the bottom service, which is how a small failure becomes a retry storm.
Circuit breakers
A circuit breaker stops calling a dependency that is clearly failing. It has three states. Closed means calls pass through. Open means calls fail immediately without touching the dependency. After a cool-down, the breaker goes half-open and allows a trial call. Success closes it. Failure reopens it.
Failing fast keeps threads free and gives the struggling dependency room to recover. This sketch takes the clock as a parameter so you can test it without sleeping.
import time
class CircuitOpenError(Exception):
pass
class CircuitBreaker:
def __init__(self, failure_threshold=3, reset_timeout=10.0, clock=time.monotonic):
self.failure_threshold = failure_threshold
self.reset_timeout = reset_timeout
self.clock = clock
self.failures = 0
self.opened_at = None
def call(self, func, *args, **kwargs):
if self.opened_at is not None:
if self.clock() - self.opened_at < self.reset_timeout:
raise CircuitOpenError("circuit is open")
# Cool-down is over: this call is the half-open trial.
try:
result = func(*args, **kwargs)
except Exception:
self.failures += 1
if self.opened_at is not None or self.failures >= self.failure_threshold:
self.opened_at = self.clock()
raise
self.failures = 0
self.opened_at = None
return result
now = [0.0]
breaker = CircuitBreaker(failure_threshold=2, reset_timeout=10.0, clock=lambda: now[0])
def broken():
raise ConnectionError("dependency down")
for _ in range(3):
try:
breaker.call(broken)
except CircuitOpenError:
print("rejected fast")
except ConnectionError:
print("call failed")
now[0] = 11.0
print(breaker.call(lambda: "ok"))The output is call failed, call failed, rejected fast, then ok. The third call never reached the dependency. A production version also needs thread safety and a limit of one trial call at a time in the half-open state. Most teams use a well-tested library instead of writing their own.
Graceful degradation
Series math punishes hard dependencies: if a request needs a component to succeed, that component's availability multiplies in. Graceful degradation turns a hard dependency into a soft one by defining what the service does without it. Examples are showing a cached or generic recommendation list, serving stale data, skipping a non-essential feature, or queueing a write for later.
from math import prod
web, database, recommendations = 0.999, 0.999, 0.99
hard = prod([web, database, recommendations])
soft = prod([web, database]) # page still renders with a fallback list
print(f"recommendations required: {hard:.4%}")
print(f"recommendations optional: {soft:.4%}")With the weakest component required, the page is up 98.80% of the time. When recommendations are optional, it is up 99.80% of the time. You gained a full nine's worth of improvement without touching the weak service.
Whether the degraded responses count as "up" is a definition question that belongs in your SLI. Decide it before the incident, not during.
Faster recovery through safer change
Many outages come from changes, not hardware. Patterns that reduce change risk improve both failure rate and MTTR:
- Canary releases send a small share of traffic to the new version first and compare error rates against the old one.
- Automatic rollback reverts when the canary's error rate crosses a threshold, so no human has to wake up and decide.
- Feature flags let you turn off a faulty feature in seconds without a redeploy.
- Staged rollouts by cell or zone stop a bad release from reaching every failure domain at once.
If a rollback takes 2 minutes instead of 40, the same bad release costs a fraction of the budget.
State is the hard part
Stateless services are easy to replicate. Data is not. Replicating a database raises the question of when a write counts as done. Synchronous replication waits for a second copy, so a failover loses no acknowledged writes, but each write is slower and the primary can stall if the replica is unreachable. Asynchronous replication is faster, but a failover can lose the most recent writes.
Neither is free, and the choice depends on whether the business would rather lose a few seconds of data or be unavailable. Automatic failover also risks split brain, where two nodes both believe they are primary and accept conflicting writes. Use a proper consensus or fencing mechanism rather than ad hoc scripts.
Summary of the patterns
| Pattern | Main goal | Main risk |
|---|---|---|
| Redundant copies | Lower failure chance | Shared failure domains, no spare capacity |
| Health-checked failover | Shorter recovery | Slow detection, flapping |
| Cells and bulkheads | Smaller blast radius | Shared router or control plane |
| Timeouts and retries | Hide transient errors | Retry storms |
| Circuit breakers | Protect callers and dependencies | Wrong thresholds |
| Graceful degradation | Soften hard dependencies | Unclear definition of "up" |
| Canary and rollback | Fewer and shorter change-caused outages | Weak canary signals |
Exercise
A service has a web tier (99.95%), a database (99.9%), and a recommendations API (99.5%). The page can render with a static fallback list when the recommendations API is down. Compute availability when the API is required and when it is optional. Then state one reason the optional figure might still be too optimistic.
Show answer
Required: 0.9995 × 0.999 × 0.995 ≈ 0.99353, about 99.35%. Optional: 0.9995 × 0.999 ≈ 0.99850, about 99.85%. The optional figure is still optimistic because it assumes the fallback itself never fails and that the failures are independent. A shared cause, such as one zone outage that takes down the web tier and the database together, would make the real figure lower. It also depends on whether degraded pages count as available in your SLI.
Exercise
Three service layers each retry a failed call up to 3 times (3 attempts in total). The bottom service starts failing completely. How many calls can one user request produce at the bottom service, and what two changes reduce the risk?
Show answer
Each layer multiplies attempts by 3, so one request can produce 3 × 3 × 3 = 27 calls at the bottom service, which can keep it from recovering. Reduce the risk by retrying at only one layer and by adding backoff with jitter and a circuit breaker so callers stop sending traffic to a failing dependency.