Reliability Patterns
Designing for failure — redundancy, timeouts, retries with backoff and jitter, circuit breakers, bulkheads, graceful degradation, health checks, and disaster recovery.
At scale, something is always broken: a disk, a node, a network link, a dependency. Reliable systems assume failure and contain it so one problem doesn't cascade into an outage.
Redundancy: no single points of failure
- Run multiple instances behind a load balancer, across availability zones.
- Replicate data; automate failover (and test it).
- For the highest availability, go multi-region (active-passive or active-active), accepting the complexity of cross-region data.
Availability of components in series multiplies (two 99.9% services → 99.8%); in parallel (redundant), failures must coincide (two 99% replicas → 99.99%).
Timeouts
Every network call needs a timeout. Without one, a slow dependency ties up threads and connections until the caller runs out of them, and the failure spreads upstream. Set timeouts from the dependency's observed latency (a bit above its p99) and make sure the overall request has a deadline that is propagated downstream (gRPC deadlines do this).
Retries with exponential backoff and jitter
Retry transient failures (timeouts, 503s, connection resets), never non-retryable ones (400, 401, validation errors). Retry only idempotent operations, or use idempotency keys.
<T> T withRetry(Callable<T> call, int maxAttempts) throws Exception {
long base = 100, cap = 5_000;
for (int attempt = 1; ; attempt++) {
try {
return call.call();
} catch (TransientException e) {
if (attempt == maxAttempts) throw e;
long backoff = Math.min(cap, base * (1L << attempt));
Thread.sleep(ThreadLocalRandom.current().nextLong(backoff)); // full jitter
}
}
}import random, time
def with_retry(call, max_attempts=5, base=0.1, cap=5.0):
for attempt in range(1, max_attempts + 1):
try:
return call()
except TransientError:
if attempt == max_attempts:
raise
backoff = min(cap, base * 2 ** attempt)
time.sleep(random.uniform(0, backoff)) # full jitterasync function withRetry<T>(call: () => Promise<T>, maxAttempts = 5): Promise<T> {
const base = 100, cap = 5000;
for (let attempt = 1; ; attempt++) {
try {
return await call();
} catch (e) {
if (!(e instanceof TransientError) || attempt === maxAttempts) throw e;
const backoff = Math.min(cap, base * 2 ** attempt);
await new Promise((r) => setTimeout(r, Math.random() * backoff)); // full jitter
}
}
}Circuit breaker
When a dependency is failing, stop calling it for a while: fail fast, save resources, and give it room to recover.
Libraries: Resilience4j (Java), Polly (.NET), opossum (Node), pybreaker (Python); service meshes provide outlier detection too.
Bulkheads
Like watertight compartments in a ship: isolate resources so one failing part can't sink the rest. Give each dependency its own thread pool or connection pool, and separate critical traffic from batch jobs. If the recommendations pool is exhausted, checkout still has its own.
Graceful degradation and fallbacks
Decide in advance what to do without each dependency:
- Serve cached or stale data.
- Return a default (generic recommendations, a placeholder avatar).
- Disable non-critical features with feature flags (kill switches).
- Shed load: reject low-priority requests early when overloaded, so important ones succeed.
Health checks
- Liveness: is the process alive? If not, restart it.
- Readiness: can it serve traffic now (warmed up, dependencies reachable)? If not, take it out of the load balancer.
- Keep liveness checks shallow: a liveness check that calls the database can restart every instance when the database blips.
Other patterns
| Pattern | Idea |
|---|---|
| Idempotency | Make retries safe (API design) |
| Queue-based load levelling | Buffer spikes in a queue (Message queues) |
| Hedged requests | Send a duplicate request to another replica if the first is slow (cuts tail latency) |
| Rate limiting | Protect services from overload (Rate limiting) |
| Static stability | Keep working with the last known config if the control plane fails |
| Cell-based architecture | Partition users into independent cells to limit blast radius |
Disaster recovery
- RPO (recovery point objective): how much data you can lose (time since the last good copy).
- RTO (recovery time objective): how long you can be down.
- Strategies, from cheapest to fastest: backup and restore → pilot light → warm standby → active-active multi-region.
- Test restores and failovers regularly — an untested backup is a hope, not a plan.
Chaos engineering and safe deploys
- Inject failures deliberately (kill instances, add latency, drop a zone) in controlled experiments to find weaknesses before users do (Chaos Monkey, Gremlin, AWS FIS).
- Most outages come from changes: use canary and blue-green deploys, progressive rollouts, feature flags and fast automated rollback.
- Run blameless postmortems and fix the systemic causes.
- Remove single points of failure with redundancy across zones.
- Always set timeouts and propagate deadlines.
- Retry transient errors with exponential backoff and jitter, at one layer, within a budget.
- Circuit breakers fail fast; bulkheads isolate resources; fallbacks degrade gracefully.
- Plan DR with RPO/RTO, test failovers, deploy progressively, practise chaos.
QA downstream service is slow and your service is falling over. What happened and how do you prevent it?medium
Threads or connections were held waiting on the slow dependency until the pool was exhausted, so even unrelated requests failed — a cascading failure. Prevent it with tight timeouts, a circuit breaker that fails fast once errors or latency cross a threshold, a separate bounded pool per dependency (bulkhead), limited retries with jitter, and a fallback such as cached data.