Shelves / Observability and SRE
OB·104
Reliability Engineering
The engineering patterns that keep services up, viewed as a system: redundancy and independence (N+1, cells, shuffle sharding), health checks that don't cause outages, timeouts and deadline budgets, retries with backoff, jitter and budgets, circuit breakers, graceful degradation and the fallback trap, load shedding and admission control, autoscaling and its failure modes, failover, and disaster recovery from backups to multi-region active-active, with code in Java, Go, Python and Rust and pointers to the deeper treatments in earlier volumes.
Start here: failures spread unless you stop them
The problem: a slow dependency is worse than a dead one
A service has 10 workers. /order calls the kitchen service; /menu doesn't need kitchen at all. Then kitchen starts hanging instead of answering:
no timeout, shared workers /menu: p50 3000 ms, failed 91/100 ← a page that doesn't even use kitchen
500 ms timeout, shared workers /menu: p50 47 ms, failed 0/100
no timeout, bulkhead of 4 for kitchen /menu: p50 3 ms, failed 0/100
Without a timeout, every worker ends up stuck waiting on kitchen, so the healthy /menu page fails too. One sick dependency took down the whole service. That's how cascading failures start. Two simple defences fixed it:
- a timeout: give up on a call after a set time, so workers come back;
- a bulkhead: let at most 4 workers wait on kitchen at once (named after a ship's watertight compartments); the rest of the service keeps working.
Retries help, and can also multiply the damage
Retrying a failed call often succeeds (the failure was brief). But three layers of services that each retry three times:
retries at all 3 layers (3 attempts each): 1 user request → 27 requests reached the failing dependency
retries only at the top layer: 1 user request → 3 requests reached the failing dependency
When the dependency is struggling because of load, 27× more load is the last thing it needs. Retry at one layer, cap attempts, and wait a random amount between tries:
300 clients retrying while a dependency recovers (it can handle 30 requests per 100 ms):
fixed 1 s retry interval busiest 100 ms after recovery: 191 requests, last client done at 9.2 s
exponential backoff, full jitter busiest 100 ms after recovery: 18 requests, last client done at 6.6 s
Retrying in lockstep, every client hit the recovering service at the same instant, overloading it again; random jitter spread them out, so they all finished sooner with fewer total requests.
Stop calling something that's down
A circuit breaker counts failures; after several in a row it "opens" and fails calls immediately (serving a fallback) instead of waiting, then lets one trial request through every few seconds to see if the dependency has recovered:
without breaker: the hanging dependency received 289 calls in 6 s; each request waited 1001 ms
with breaker: the hanging dependency received 53 calls in 6 s; requests got a fallback in under 1 ms
How deep to go in reliability engineering
Volume 17 defines six mastery levels. For this chapter they look like this; the chapter aims at L3 everywhere, and its lab at L4.
| Level | What you can do |
|---|---|
| L1 | Explain timeouts, retries, circuit breakers, bulkheads, redundancy and backups |
| L2 | Configure timeouts, retries with backoff and health checks in a service |
| L3 | Combine patterns correctly; design graceful degradation, load shedding and failover |
| L4 | Diagnose cascading failures, retry storms and bad health checks; test with fault injection |
| L5 | Design a system's reliability architecture: cells, multi-region, DR with tested RPO/RTO |
| L6 | Run a reliability programme: chaos engineering, DR exercises, resilience standards |
Reliability as a system property
Reliability is the probability that a system performs its required function, for its users, over time. It emerges from design, operations and culture together:
- Design: redundancy, isolation, timeouts, idempotency, graceful degradation (this chapter; Vol. 3 ch. 52; Vol. 5 ch. 78).
- Operations: SLOs, alerting, incident response (chapters 102–103), safe change management (Vol. 6 ch. 84, Vol. 8).
- Culture: blameless learning, error budgets, ownership.
Most outages come from changes (deploys, configuration) and from overload and dependency failures that cascade. The patterns here target those.
Redundancy
Removing single points of failure
Redundancy means having more capacity or copies than the minimum needed, so that a failure is absorbed:
| Pattern | Meaning |
|---|---|
| N+1 | One more instance than needed at peak: survives one failure |
| N+2 | Survives one failure during maintenance of another (or two failures) |
| Active-passive | A standby takes over on failure (database primary/standby); simpler, but failover takes time and the standby may be untested |
| Active-active | All copies serve traffic; failure removes capacity rather than requiring a switch; needs load balancing and (for stateful data) replication and conflict handling |
Redundancy only helps if failures are independent. Watch for correlated failures: replicas in the same AZ, the same rack, behind the same load balancer, with the same bad config pushed to all at once, sharing a dependency, or all hitting the same bug at the same input ("poison" request). Spread across failure domains (Vol. 7 ch. 85) and stagger changes.
Isolation: bulkheads, cells and shuffle sharding
- Bulkheads (Vol. 3 ch. 52): separate thread pools, connection pools or instances per dependency or customer class, so one can't exhaust shared resources.
- Cell-based architecture: run multiple independent copies (cells) of the whole stack, each serving a subset of customers; a bad deploy or poison request affects one cell, not everyone. Deploy changes cell by cell. (AWS uses this widely; Vol. 12 covers it.)
- Shuffle sharding: assign each customer to a small random combination of workers (e.g. 2 of 8). Two customers rarely share both workers, so a customer whose requests crash workers takes down only their shard, while almost every other customer still has a healthy worker. With 8 workers and shards of 2, there are 28 combinations.
Health checks
Health checks drive load balancers, orchestrators and failover, so badly designed ones cause outages:
| Check | Purpose | Should include |
|---|---|---|
| Liveness | "Restart me if I'm wedged" | Process responsive only. Never dependencies (a DB outage would restart everything) |
| Readiness | "Send me traffic?" | Initialised, warm, not shutting down, maybe critical local resources |
| Deep / dependency health | Diagnostics for humans and dashboards | Status of each dependency, versions; not wired to automatic eviction |
| Synthetic checks | "Does the user journey work end to end?" | Real requests through the public path, from outside |
Failure modes to avoid:
- Cascading ejection: a shared dependency fails → every instance fails its health check → the load balancer removes all instances → total outage, even for requests that didn't need that dependency. Mitigate with health checks that don't depend on shared dependencies, plus fail-open behaviour (many load balancers route to all targets if all are unhealthy; Envoy's panic threshold; cap ejection percentages).
- Health check storms: frequent expensive checks from many load balancers overload the service.
- Flapping: use thresholds (N consecutive failures to mark unhealthy, M successes to recover).
- Lying health: a check that returns 200 while the service can't serve (a gray failure, Vol. 5 ch. 78). Make readiness exercise the real serving path cheaply.
Timeouts
Every remote call needs a timeout; without one, a slow dependency holds threads and connections until the caller collapses (Vol. 3 ch. 52, Vol. 5 ch. 65).
Setting them:
- Base on data: around the dependency's p99.9 latency plus margin, not a round number.
- Separate connect timeout (short: ~1 s or less inside a region) from request/read timeout.
- Deadline budgets: a request that must answer within 2 s gives each downstream call a portion of the remaining budget, and propagates the deadline (gRPC deadlines,
context.WithTimeoutin Go,Deadlineheaders) so downstream services stop working on requests the caller has abandoned. - Layering: outer timeouts larger than inner ones (client > gateway > service > database), so inner failures surface as clean errors rather than everything timing out together.
Retries
Retries recover from transient failures, and amplify overload (Vol. 5 ch. 78). The rules:
- Retry only idempotent operations (or use idempotency keys).
- Retry only retryable errors: connection failures, 503, 429 with
Retry-After, gRPCUNAVAILABLE; not 400, 401, 404, or validation failures. - Exponential backoff with jitter (full jitter: sleep a random time between 0 and
min(cap, base × 2^attempt)) to avoid synchronised waves. - Bounded attempts (2–3) and a total time limit within the caller's deadline.
- Retry at one layer of the stack, not every layer.
- Retry budgets: retries may add at most ~10% extra load; when exceeded, fail fast.
- Respect circuit breakers and server signals (
Retry-After).
// Java: Resilience4j composition: timeout → retry (with jittered backoff) → circuit breaker → bulkhead
RetryConfig retryCfg = RetryConfig.custom()
.maxAttempts(3)
.intervalFunction(IntervalFunction.ofExponentialRandomBackoff(Duration.ofMillis(100), 2.0, 0.5))
.retryOnException(e -> e instanceof IOException || e instanceof ServiceUnavailableException)
.build();
CircuitBreakerConfig cbCfg = CircuitBreakerConfig.custom()
.failureRateThreshold(50).slowCallRateThreshold(50).slowCallDurationThreshold(Duration.ofMillis(800))
.slidingWindowSize(50).waitDurationInOpenState(Duration.ofSeconds(20)).build();
Supplier<Quote> call = Decorators.ofSupplier(() -> pricingClient.quote(cart)) // client has its own timeout
.withBulkhead(Bulkhead.of("pricing", BulkheadConfig.custom().maxConcurrentCalls(40).build()))
.withCircuitBreaker(CircuitBreaker.of("pricing", cbCfg))
.withRetry(Retry.of("pricing", retryCfg))
.withFallback(List.of(CallNotPermittedException.class, BulkheadFullException.class),
e -> Quote.cachedOrDefault(cart)) // graceful degradation
.decorate();
// Go: deadline-aware retry with full jitter, respecting the caller's context
func callWithRetry(ctx context.Context, attempts int, base, maxDelay time.Duration,
fn func(context.Context) error) error {
var err error
for i := 0; i < attempts; i++ {
attemptCtx, cancel := context.WithTimeout(ctx, 800*time.Millisecond) // per-try timeout
err = fn(attemptCtx)
cancel()
if err == nil || !isRetryable(err) { return err }
backoff := min(maxDelay, base<<i)
sleep := time.Duration(rand.Int64N(int64(backoff))) // full jitter
select {
case <-time.After(sleep):
case <-ctx.Done():
return ctx.Err() // overall deadline wins
}
}
return err
}
# Python: tenacity with exponential jitter, stop on attempts or total time, retry only transient errors
from tenacity import retry, stop_after_attempt, stop_after_delay, wait_random_exponential, retry_if_exception_type
import httpx
@retry(stop=(stop_after_attempt(3) | stop_after_delay(2.0)),
wait=wait_random_exponential(multiplier=0.1, max=1.0),
retry=retry_if_exception_type((httpx.ConnectError, httpx.ReadTimeout)),
reraise=True)
def quote(client: httpx.Client, cart: dict) -> dict:
r = client.post("/quote", json=cart, timeout=httpx.Timeout(0.8, connect=0.3))
if r.status_code == 503:
raise httpx.ConnectError("unavailable") # treat as transient
r.raise_for_status()
return r.json()
// Rust: tower middleware stack: timeout, concurrency limit, load shedding, retry policy
use tower::{ServiceBuilder, timeout::TimeoutLayer, limit::ConcurrencyLimitLayer, load_shed::LoadShedLayer};
let svc = ServiceBuilder::new()
.layer(LoadShedLayer::new()) // reject immediately when not ready (overloaded)
.layer(ConcurrencyLimitLayer::new(64))
.layer(TimeoutLayer::new(Duration::from_millis(800)))
.retry(RetryOnceForIdempotent::default()) // custom tower::retry::Policy
.service(pricing_client);
Circuit breakers
A circuit breaker stops calling a dependency that's failing, giving it time to recover and making callers fail fast instead of waiting on timeouts:
- Closed: calls flow; failures and slow calls are counted over a sliding window.
- Open: when the failure (or slow-call) rate exceeds a threshold, calls fail immediately (or go to a fallback) for a cool-down period.
- Half-open: a few trial calls are allowed; success closes the breaker, failure reopens it.
Configure per dependency; monitor breaker state as a metric; alert when breakers open for critical dependencies. Service meshes and proxies (Envoy outlier detection and circuit breaking) provide similar protection at the network layer.
Graceful degradation
When something fails, do less, but keep the core working:
| Degradation | Example |
|---|---|
| Serve stale data | Product prices from cache if the pricing service is down (with a TTL limit) |
| Disable optional features | Hide recommendations, reviews, personalisation; keep browsing and checkout |
| Reduce quality | Lower-resolution images, fewer search results, approximate counts |
| Queue for later | Accept the order, process payment asynchronously, email confirmation later |
| Read-only mode | Allow reads during a database failover; reject writes clearly |
| Static fallback | Serve a cached or static page from the CDN when the origin fails |
Design degradation in advance: classify features as critical or optional, make optional ones fail independently (timeouts, bulkheads, flags), and test degraded modes (chaos experiments, game days).
Beware the fallback trap (from the Amazon Builders' Library article "Avoiding fallback in distributed systems"): fallback paths that are rarely exercised are often broken or overloaded when finally used, and can make outages worse (falling back to a database that can't handle the extra load). Prefer designs where the "fallback" is exercised constantly (e.g. always serving from cache and refreshing in the background), or make the primary path more reliable instead.
Load shedding and admission control
When demand exceeds capacity, reject some work deliberately and cheaply so the rest completes (Vol. 5 ch. 76):
- Shed early: reject at the edge or the first middleware, before expensive work.
- Prioritise: critical traffic (checkout, health checks, internal control traffic) over sheddable traffic (prefetch, analytics, batch).
- Bound queues and drop work that has waited longer than its deadline; adaptive concurrency limits (AIMD, gradient) find the right limit automatically.
- Signal: 503 with
Retry-After(or 429 for per-client limits) so well-behaved clients back off. - Without shedding, overload causes congestion collapse: everything slows, everything times out, goodput drops to near zero (chapter 105 shows why with queueing theory).
Autoscaling
Autoscaling (Vol. 6 ch. 83, Vol. 7 ch. 86) adds capacity as load grows, but it's not an instant defence:
- Lag: metrics are averaged over windows, scaling decisions have cooldowns, nodes take minutes to provision, applications take time to warm up (JIT, caches, connection pools). A sudden spike can overwhelm the system before new capacity is ready.
- Wrong signals: CPU may not reflect the bottleneck (I/O-bound services, thread-pool exhaustion); scale on concurrency, queue depth or latency where possible.
- Scaling into a bottleneck: adding app instances in front of a saturated database makes things worse (more connections, more contention).
- Scale-down too aggressively and you're caught short on the next spike; thrashing if thresholds are close.
- Cold starts in the new capacity: slow first requests can trip health checks or timeouts.
Mitigations: keep headroom (scale before saturation), set sensible minimums (especially across AZs), pre-scale for known events, use predictive scaling, load-test the scaling behaviour, and pair autoscaling with load shedding for spikes faster than scaling.
Failover
Failover moves work from a failed component to a healthy one:
| Level | Mechanism |
|---|---|
| Instance | Load balancer health checks, orchestrator rescheduling |
| Database | Primary → standby promotion (RDS Multi-AZ, Patroni, consensus-based databases); clients reconnect via DNS or proxy |
| Zone | Multi-AZ deployments absorb zone loss if statically stable (enough capacity in remaining zones) |
| Region | DNS or anycast traffic shifting (Route 53 ARC, Global Accelerator, Front Door), with data already replicated |
Design questions:
- Automatic or manual? Automatic failover is fast but risks false positives and split brain (Vol. 5 ch. 71); manual failover is slower but deliberate. Many teams automate zone-level and keep region-level as a one-click human decision with pre-checked runbooks.
- Fencing: ensure the old primary can't keep writing (epochs, STONITH).
- Client behaviour: connection retry, DNS TTLs, cached connections that point at the old primary.
- Failback: returning to the original is a second failover; plan and test it too.
- Test regularly: an untested failover path is a hope. Run planned failovers in production during quiet hours.
Disaster recovery
Backup and restore
Backups protect against logical disasters (deletion, corruption, ransomware, bad migrations) that replication faithfully copies:
- Automated, frequent backups plus point-in-time recovery (database WAL/binlog archiving).
- Immutable (object lock, vault lock) and isolated (separate account, restricted access) copies, in another region.
- Restore testing: regularly restore to a scratch environment and verify data integrity and timing. Measure actual RTO. Untested backups fail exactly when needed.
RPO and RTO
- RPO (recovery point objective): maximum acceptable data loss, measured in time. Determines backup frequency and replication mode (asynchronous replication → seconds of potential loss; synchronous → zero, at a latency cost).
- RTO (recovery time objective): maximum acceptable downtime. Determines how much infrastructure must be pre-provisioned in the recovery location.
Set them per workload with the business; they drive cost.
Strategies
Vol. 7 ch. 91 described the ladder: backup and restore → pilot light → warm standby → multi-site active-active. In more depth:
| Active/passive (pilot light, warm standby) | Active/active | |
|---|---|---|
| Traffic | One region serves; the other waits | All regions serve |
| Data | Replicated one-way (async, or sync if close enough) | Replicated multi-directionally, or partitioned by home region; conflicts must be designed for (Vol. 5 ch. 71) |
| Failover | A switch (promote DB, scale up, shift DNS): minutes to hours; risky if untested | Remove a region from rotation: capacity loss, no switch |
| Cost | Lower (standby scaled down) | Higher (full capacity everywhere, plus headroom to absorb a region's traffic) |
| Complexity | Moderate | High: data consistency, routing, testing |
| Confidence | Only as good as the last test | Exercised continuously by real traffic |
Multi-region design checklist:
- Data: which data must be in every region? Replication lag and consistency (strong global databases like Spanner, Aurora DSQL, CockroachDB, DynamoDB global tables with MRSC, versus asynchronous replicas)?
- Routing: how do users reach a healthy region (latency-based DNS, anycast), and how fast does it shift?
- Dependencies: are all dependencies (identity, secrets, queues, third parties, CI/CD for emergency deploys) available in each region? Avoid hidden single-region dependencies (Vol. 7 ch. 85, control planes and global services).
- Capacity and quotas in the surviving region(s) to absorb the full load.
- Runbooks and drills: practice regional evacuation; measure real RTO and RPO.
Lab: timeouts, bulkheads, retries and breakers under fault
One Python process runs every service with aiohttp 3.14 on localhost; a controllable dependency can answer normally (5 ms), fail fast (HTTP 503) or hang (10 s). Each experiment is a real HTTP workload; only the "worker pool" is modelled, as an asyncio.Semaphore(10) that every request must hold (like a 10-thread server).
Experiment 1: retry amplification
Three services in a chain (edge → api → domain → dependency); the dependency fails every call.
retries at all 3 layers (3 attempts each): 1 user request → 27 requests reached the failing dependency (status 503)
retries only at the top layer: 1 user request → 3 requests reached the failing dependency
Amplification is attempts ^ layers. With five layers and three attempts it's 243. During an overload-driven outage, every caller's retries add load exactly where it hurts. Rules: retry at one layer (usually the one closest to the user, or the client library of the service that owns the call), cap attempts, retry only idempotent operations or those with idempotency keys, and use a retry budget (for example, retries may add at most 10% to normal traffic; gRPC and Envoy implement this) so retries switch off when failure is widespread.
Experiment 2: timeouts and bulkheads
10 orders and 10 menu views per second for 5 seconds; kitchen hangs throughout. The client gives up after 3 s.
no timeout, shared workers /menu: p50 3000 ms, failed 91/100 | /order: failed 100/100
500 ms timeout, shared workers /menu: p50 47 ms, failed 0/100 | /order: failed 100/100
no timeout, bulkhead of 4 for kitchen /menu: p50 3 ms, failed 0/100 | /order: failed 100/100
/order failed in every case: kitchen was down and nothing could change that. The patterns decide whether the failure stays contained. With no timeout, the 10 workers filled with hung kitchen calls within a second, and /menu queued behind them until the client gave up. A timeout returned workers after 500 ms (menu's 47 ms p50 is the time spent queueing for a free worker). The bulkhead did better still: kitchen calls could occupy at most 4 workers, extra orders were rejected immediately ("kitchen busy"), and the other 6 workers served menus at full speed.
Setting timeouts in practice: base them on the dependency's observed latency (a little above its p99.9), make sure the caller's timeout is longer than the sum of what it waits for (or propagate a deadline, as gRPC does, so downstream services stop work the caller has already abandoned), and remember that libraries often default to no timeout (Python requests, many JDBC drivers) or very long ones.
Experiment 3: a circuit breaker
class Breaker:
def __init__(self, threshold=5, cooldown=2.0): self.fail, self.state, self.opened, self.th, self.cd = 0, "closed", 0, threshold, cooldown
def allow(self):
if self.state == "open" and time.monotonic() - self.opened > self.cd: self.state = "half-open"; return True # one probe
return self.state == "closed"
def ok(self): self.fail, self.state = 0, "closed"
def bad(self):
self.fail += 1
if self.state == "half-open" or self.fail >= self.th: self.state, self.opened = "open", time.monotonic()
50 requests per second; the dependency hangs for 6 s, then recovers. Calls time out after 1 s; a failed call serves a fallback.
without breaker: dependency (hanging) received 289 calls in 6 s; request p50 while it hung 1001 ms; fallbacks served 289
with breaker: dependency (hanging) received 53 calls in 6 s; request p50 while it hung 0 ms; fallbacks served 345
The breaker turned a second of waiting into an instant fallback for most requests and cut traffic to the sick dependency by 82%. Why 53 and not 5? The breaker learns of failures only when calls time out, so the ~50 calls already in flight during the first second all went through; after that, only one probe every 2 s. Real breakers (Resilience4j, Polly, Envoy outlier detection, Istio) also open on slow-call rate and concurrency, which would have reacted sooner. A first version of this lab's breaker let every request through in half-open state and sent 100 calls; a half-open breaker must admit a limited number of probes.
Experiment 4: retry timing while a dependency recovers
300 clients; the dependency fails for 3 s, then recovers but can only handle 30 requests per 100 ms (more get 503). Each client retries up to 12 times.
fixed 1 s retry interval : 1915 requests in total; after recovery, busiest 100 ms: 191 requests; last client done at 9.2 s
exponential backoff, no jitter : 1722 requests in total; after recovery, busiest 100 ms: 171 requests; last client done at 24.7 s
exponential backoff, full jitter : 1493 requests in total; after recovery, busiest 100 ms: 18 requests; last client done at 6.6 s
Without jitter, clients that failed together retry together: each wave of ~190 requests overloaded the recovering service, so most failed again and came back in the next wave. Exponential backoff alone made it slower (clients waited longer between the same synchronised waves). Full jitter (sleep(random(0, min(cap, base × 2^attempt))), from AWS's analysis of backoff strategies) spread retries so the service never exceeded its capacity, finishing fastest with the fewest requests.
Try it yourself
- Add a retry budget to experiment 1: allow a retry only if retries in the last second are under 10% of requests.
- Change experiment 3's breaker to also open when more than 50% of the last 20 calls took longer than 500 ms, and compare the in-flight burst.
- In experiment 2, combine the 500 ms timeout with the bulkhead. What happens to
/orderlatency?
Revision sheet: reliability engineering
Key ideas
- Redundancy without single points of failure; isolation with bulkheads, cells and shuffle sharding.
- Health checks: liveness (restart me) vs readiness (send me traffic); don't let dependency failures fail liveness.
- Timeouts and deadlines on every remote call; retries with backoff, jitter, caps and budgets, only for idempotent work.
- Circuit breakers, graceful degradation and fallbacks; load shedding and admission control.
- Autoscaling (with limits), failover (tested), disaster recovery with RPO/RTO and restore tests.
Numbers to remember
- Retry amplification = attempts^layers (3 layers × 3 attempts = 27).
- Lab: no timeout → /menu 91% failed; 500 ms timeout → 0%; breaker cut calls to a hung dependency 289 → 53; full jitter peak 18 vs 191 per 100 ms.
Pitfalls
- Missing or infinite default timeouts; caller timeout shorter than callee's.
- Retries at every layer; retrying non-idempotent operations.
- Synchronised retries (no jitter); unbounded queues.
- Health checks that cascade (liveness depending on the database).
- Failover and backups never tested.
Glossary
- Deadline propagation: passing the remaining time budget downstream.
- Retry budget: cap on retries as a share of traffic.
- Bulkhead: resource partition per dependency or tenant.
- Shuffle sharding: assigning each customer a random subset of workers to limit blast radius.
- RPO / RTO: maximum acceptable data loss / time to restore.