Resilience Patterns
- Set timeouts from latency data and propagate an end-to-end deadline across services
- Design retries that help instead of hurt: retryable errors only, exponential backoff with jitter, a single retry layer and a retry budget
- Explain circuit breaker states, bulkheads, load shedding and backpressure, and where each sits in a request path
- Plan graceful degradation and hedged requests for latency-sensitive paths
- Diagnose a cascading failure and name the patterns that would have contained it
TL;DR
- Every remote call needs a timeout, derived from the caller's remaining deadline, not a hard-coded 30 s. Propagate the deadline (gRPC does it with
context) so downstream services stop work nobody is waiting for. - Retries only for transient errors and only for idempotent operations (or with idempotency keys). Use exponential backoff with full jitter, retry at one layer, and cap total retries with a retry budget (≈ 10% of traffic) so retries cannot multiply load during an outage.
- Circuit breakers stop calling a failing dependency (closed → open → half-open), turning slow failures into fast ones and giving the dependency room to recover.
- Bulkheads isolate resources (pools, concurrency limits) per dependency or priority so one slow PSP cannot exhaust capacity for everything else.
- Load shedding and backpressure keep a service at its maximum useful throughput when demand exceeds capacity: reject early, cheaply and by priority, rather than queueing until everything times out.
- Graceful degradation decides in advance what to turn off (recommendations, promo badges) so the core path (checkout, payment) survives. Hedged requests cut tail latency for idempotent reads.
Why it matters
Most large outages are not caused by the first failure but by the system's reaction to it. A dependency gets slow; callers wait; their goroutines, connections and memory fill up; they get slow; their callers retry; load multiplies; health checks fail; orchestrators restart pods, reducing capacity further. Within minutes a 200 ms slowdown in a promotion service has become a full checkout outage — on the busiest day of the year.
For a bank, the same dynamics turn a slow core-banking mainframe link into failed card authorizations across all channels. For an e-commerce platform, a flash sale is precisely the scenario where demand exceeds capacity by design. Resilience patterns are how you make the system degrade predictably: some requests are rejected quickly, non-critical features turn off, and money-moving paths keep working. Interviewers for architect roles expect you to apply them with numbers, not list them.
Core concepts
Timeouts
- No timeout is a bug. Go's
http.DefaultClienthas no timeout; a hung connection holds a goroutine forever. Always set one. - Set timeouts from data: start near the dependency's p99.9 latency plus margin, not "30 seconds because that's the default". A call that normally takes 40 ms at p99 rarely deserves more than a few hundred ms.
- Separate phases: connection timeout (short: the host is unreachable), TLS handshake, time to first byte, total request time. Go exposes these via
net.Dialer.Timeout,http.Transport.TLSHandshakeTimeout,ResponseHeaderTimeoutand the request context. - Timeouts produce unknown outcomes. A timed-out payment call may have succeeded. That's why timeouts and idempotency go together.
Deadline propagation
A user waits a bounded time. Give each request an end-to-end deadline at the edge, and pass the remaining budget to every downstream call.
- In Go, derive every outgoing call's context from the incoming one:
ctx, cancel := context.WithTimeout(r.Context(), 300*time.Millisecond)takes the earlier of the two deadlines. - gRPC sends the deadline in the
grpc-timeoutheader and the server'sctxcarries it automatically. For HTTP you propagate it yourself (a header with the remaining milliseconds, or the absolute deadline). - Downstream services should check the deadline before expensive work and give up early when the remaining budget is smaller than the work's typical latency.
Retries, backoff and jitter
Retries recover from transient failures — a dropped connection, a leader election, a pod restart. Done naively, they cause outages.
Retry only when it can help:
- Retryable: connection errors, timeouts (for idempotent calls), 503, 429 (honoring
Retry-After), gRPCUNAVAILABLE. - Not retryable: 400, 401/403, 404, 409, 422, business declines ("insufficient funds", "card declined"). Retrying a decline at a PSP can also trigger issuer fraud rules.
Back off exponentially with jitter: wait base × 2^attempt, capped, and randomize. Without jitter, every client that failed at the same moment retries at the same moment, producing synchronized waves. "Full jitter" — sleep a random duration between 0 and the capped exponential value — spreads them out well (see Marc Brooker's "Exponential Backoff and Jitter" on the AWS Architecture Blog).
Retry at one layer. If the app, the service mesh and the client SDK each retry 3 times, a failing call is attempted up to 3 × 3 × 3 = 27 times. Across a call chain of depth d with n attempts per layer, load on the deepest dependency multiplies by up to n^d. Pick one layer — usually the caller closest to the failing dependency — and disable the others.
Retry budgets
Even well-behaved retries add load exactly when the dependency is struggling. A retry budget caps retries to a fraction of normal traffic: e.g., retries may not exceed 10% of requests over a sliding window. When a dependency is fully down, traffic to it rises by at most ≈ 10% instead of 200%. The Google SRE book describes this combination of a per-request attempt cap and a per-client retry ratio; gRPC's retry throttling and Finagle's retry budgets implement token-bucket versions.
Circuit breakers
A circuit breaker wraps calls to one dependency and tracks failures (errors and timeouts) over a window.
- Closed: calls flow; failures are counted.
- Open: calls fail immediately (or use a fallback) without touching the dependency. This frees the caller's resources and gives the dependency room to recover.
- Half-open: after a cool-down, a few probe calls are allowed; success closes the breaker, failure re-opens it.
Configure on failure rate with a minimum request volume (e.g., open if ≥ 50% of at least 20 calls in 10 s fail), not on a raw count. Keep breakers per dependency — and per host or per PSP when one instance can fail independently. Michael Nygard's Release It! popularized the pattern; in Go, sony/gobreaker is a common implementation.
Bulkheads
Named after ship compartments: a breach floods one compartment, not the whole hull.
- Separate connection pools and concurrency limits per dependency. If PSP-A hangs, it can tie up at most its 50 slots; calls to PSP-B and the ledger proceed.
- Separate capacity per priority or tenant. Checkout and payment callbacks get their own pods or worker pools, isolated from catalog browsing and report downloads.
- Cells: at larger scale, split the whole stack into independent cells (by merchant or customer segment) so a bad deploy or poison request affects one cell.
Load shedding
When demand exceeds capacity, something will be rejected. Choose what, and reject early and cheaply:
- Signal: in-flight requests over a concurrency limit, queue wait time, CPU, or latency above target. Adaptive concurrency limiters (e.g., Netflix's concurrency-limits approach, inspired by TCP congestion control) adjust the limit automatically.
- Priority: keep
POST /payments/authorizeand PSP callbacks; shed product recommendations, search suggestions and statement PDFs first. - Response:
429or503withRetry-After, in microseconds, before any expensive work. - Queue discipline: a request that has already waited longer than its client's timeout is worthless — drop it. Under overload, LIFO or deadline-aware queues serve requests that can still succeed.
Backpressure
Backpressure is load shedding's cooperative cousin: the consumer signals the producer to slow down instead of silently dropping work.
- Bounded queues and channels everywhere; an unbounded queue only converts overload into memory exhaustion and latency.
- Pull-based consumption: Kafka consumers pull at their own pace; lag grows instead of the consumer falling over. Monitor lag.
- Propagate it upstream:
429withRetry-After, gRPCRESOURCE_EXHAUSTED, TCP flow control, or reduced credit in the protocol. Rate limiting at the edge is a form of backpressure on clients (see Rate Limiting).
Graceful degradation
Decide before the incident which features are optional, and build switches for them:
- Serve the catalog from cache or a static snapshot when the catalog service is down (see CDN & Edge).
- Hide recommendations, reviews and "people also bought" widgets.
- Skip a non-critical fraud enrichment call and fall back to a simpler rules check — with a risk-owner's agreement and a lower transaction limit.
- Accept an order and confirm stock asynchronously only if the business accepts the oversell risk; otherwise keep stock checks synchronous and shed elsewhere.
- Feature flags and "brownout" modes let operators flip these quickly; test them in game days.
Hedged requests
For tail latency (Dean & Barroso, "The Tail at Scale"): send the request to one replica; if no response arrives within, say, the p95 latency, send a second copy to another replica and use whichever returns first, cancelling the other. Load rises by only a few percent (only slow requests are hedged), while p99 drops sharply. Only for idempotent reads — never hedge a payment authorization. A variant, tied requests, enqueues on two servers and cancels the duplicate when one starts work.
Case study: a cascading checkout failure
A composite of a common incident pattern, during a midnight flash sale:
What happened, step by step:
- A hot row in the promotion database (everyone applying the same voucher) slows the promotion service to seconds.
- Checkout calls it with a 30-second timeout and three immediate retries. Each checkout request now holds a goroutine and a database connection for up to two minutes.
- Checkout's connection pool and memory fill; its own latency climbs; the API gateway retries checkout calls too.
- Liveness probes, which check the database, time out; Kubernetes restarts pods, cutting capacity while load keeps rising.
- PSP payment callbacks are served by the same pods and pool, so payments that succeeded at the PSP aren't recorded — creating reconciliation work after the incident.
What would have contained it:
- Deadline-based timeouts: promotion lookup capped at ≈ 200 ms within a 3-second request budget.
- Retry discipline: one retry layer, jittered backoff, a 10% retry budget; gateway retries disabled for non-idempotent
POST. - Circuit breaker on promotions with a fallback: proceed without the voucher (or with cached promotion rules) and show a message, rather than fail checkout.
- Bulkheads: separate pool and concurrency limit for promotion calls; PSP callbacks on their own deployment.
- Load shedding at the gateway by priority: protect payment callbacks and checkout, shed browse traffic.
- Probes: liveness checks only the process itself; readiness may consider dependencies; avoid restart storms.
- Fix the root cause: voucher redemption counters sharded or kept in Redis with atomic decrements (see Inventory & Flash Sales).
Trade-offs
| Pattern | Strengths | Weaknesses | Choose when |
|---|---|---|---|
| Timeouts + deadlines | Bound resource use; stop wasted work | Too tight causes false failures; unknown outcomes | Always, on every remote call |
| Retries with backoff + jitter | Hide transient faults | Amplify load; duplicate side effects without idempotency | Transient errors on idempotent or keyed operations |
| Retry budget | Caps amplification during outages | Some recoverable requests not retried | Any service with retries at scale |
| Circuit breaker | Fast failure; protects dependency; enables fallback | Tuning; can open on noise; needs per-host granularity | Calls to dependencies that can fail or slow down |
| Bulkhead | Contains blast radius | Unused capacity in idle compartments | Multiple dependencies or priorities sharing a process |
| Load shedding | Keeps goodput near max under overload | Some users rejected; needs priority model | Flash sales, traffic spikes, overload |
| Backpressure | Stable pipelines; no memory blow-ups | Pushes delay upstream; needs protocol support | Queues, streams, batch pipelines |
| Graceful degradation | Core path survives | Product decisions and testing needed upfront | Features with clear "nice to have" status |
| Hedged requests | Large tail-latency reduction | Extra load; only safe for idempotent reads | Read-heavy, latency-sensitive fan-out |
In practice
Retry with full jitter, deadline awareness and a budget:
package resilience
import (
"context"
"math/rand/v2"
"sync"
"time"
)
// RetryBudget allows retries up to ratio × successes (token bucket).
type RetryBudget struct {
mu sync.Mutex
tokens float64
max float64
ratio float64 // e.g. 0.1: one retry earned per ten successes
}
func NewRetryBudget(max, ratio float64) *RetryBudget {
return &RetryBudget{tokens: max, max: max, ratio: ratio}
}
func (b *RetryBudget) onSuccess() {
b.mu.Lock()
b.tokens = min(b.max, b.tokens+b.ratio)
b.mu.Unlock()
}
func (b *RetryBudget) tryWithdraw() bool {
b.mu.Lock()
defer b.mu.Unlock()
if b.tokens < 1 {
return false
}
b.tokens--
return true
}
// Do runs op with up to maxAttempts attempts. op must be idempotent.
func Do(ctx context.Context, b *RetryBudget, maxAttempts int, base, maxDelay time.Duration,
retryable func(error) bool, op func(context.Context) error) error {
var err error
for attempt := 0; attempt < maxAttempts; attempt++ {
if err = op(ctx); err == nil {
b.onSuccess()
return nil
}
if attempt == maxAttempts-1 || !retryable(err) || !b.tryWithdraw() {
return err
}
backoff := min(maxDelay, base<<attempt)
sleep := time.Duration(rand.Int64N(int64(backoff) + 1)) // full jitter
if dl, ok := ctx.Deadline(); ok && time.Until(dl) < sleep {
return err // not enough time left for another attempt
}
t := time.NewTimer(sleep)
select {
case <-t.C:
case <-ctx.Done():
t.Stop()
return ctx.Err()
}
}
return err
}
A bulkhead that sheds instead of queueing:
var ErrBulkheadFull = errors.New("bulkhead full")
type Bulkhead struct{ slots chan struct{} }
func NewBulkhead(n int) *Bulkhead { return &Bulkhead{slots: make(chan struct{}, n)} }
func (b *Bulkhead) Do(ctx context.Context, fn func(context.Context) error) error {
select {
case b.slots <- struct{}{}:
defer func() { <-b.slots }()
return fn(ctx)
default:
return ErrBulkheadFull // map to 503 + Retry-After, count as shed
}
}
Knobs and rough starting points (tune with real data):
- Attempts: 2–3 total for interactive calls; more only for background work with longer deadlines.
- Backoff: base ≈ 50–100 ms, cap ≈ 1–2 s for interactive paths.
- Retry budget: ≈ 10% of requests.
- Circuit breaker: open at ≈ 50% failures over ≥ 20 requests in 10 s; cool-down ≈ 5–30 s; a handful of half-open probes.
- Bulkhead size: from Little's law — concurrency ≈ throughput × latency. 200 req/s × 0.25 s ≈ 50 slots, plus headroom.
- Service meshes (Envoy/Istio) can provide timeouts, retries, outlier detection and circuit breaking without code changes — but then disable the same retries in application code.
Observability for resilience: expose breaker state, shed counts by priority, retry rate vs budget, timeout counts per dependency and saturation of each bulkhead. Alert on breakers opening and on sustained shedding (see Observability & SLOs).
Common pitfalls
- Default or missing timeouts. Symptom: goroutine counts climbing to hundreds of thousands during a dependency slowdown.
- Retrying non-idempotent calls. Symptom: duplicate orders or double authorizations after a network blip.
- Retries at every layer. Symptom: a dependency's traffic jumps 10–30× the moment it starts failing, preventing recovery.
- No jitter. Symptom: periodic synchronized load spikes after an outage ("thundering herd" on recovery).
- One breaker for many hosts. One bad instance opens the breaker for all of them, or a breaker never opens because healthy hosts dilute the failure rate.
- Liveness probes that check dependencies. Symptom: a database blip restarts the whole fleet.
- Unbounded queues. Symptom: latency rises to minutes, then OOM kills, then data loss of in-memory work.
- Fallbacks never tested. Symptom: the fallback path itself throws when first used in a real incident.
Interview angle
- Typical prompts: "Your PSP is slow during a sale — what happens to checkout?" "How do you set timeouts and retries between services?" "Explain circuit breakers." "How do you survive 10× traffic for 15 minutes?"
- Strong answer: start from the user-facing deadline; budget timeouts per hop; retries only for idempotent/keyed calls at one layer with jittered backoff and a budget; breakers per dependency with fallbacks; bulkheads separating payment from browse; load shedding by priority at the edge; graceful degradation list agreed with the business; mention the unknown-outcome problem for timed-out payments and reconciliation.
- Follow-ups: "How do you pick the timeout value?" (latency percentiles + budget). "What's the retry amplification across 4 layers?" "What do you shed first?" "How do breakers interact with autoscaling?"
- Red flags: "retry 3 times" with no backoff or idempotency; 30-second timeouts everywhere; a breaker as the only answer; no notion of priorities under overload.
Self-check
1. Why should timeouts be derived from a propagated deadline rather than fixed per call?
A fixed per-call timeout ignores how much time the user is still willing to wait; a downstream call might be allowed 5 s when only 200 ms remain, wasting resources on work whose result nobody will receive. Deriving from the remaining deadline bounds total latency end to end and lets services skip work that cannot finish in time.
2. A request path has four layers, each retrying up to 3 attempts. What is the worst-case load on the bottom dependency and how do you fix it?
Up to 3^4 = 81 attempts per original request. Fix by retrying at only one layer (usually closest to the dependency), using jittered exponential backoff, enforcing a retry budget, and making upper layers fail fast on errors that already exhausted retries below them.
3. Describe the three circuit breaker states and what triggers each transition.
Closed: calls flow and failures are counted; it opens when the failure rate exceeds a threshold over a window with a minimum volume. Open: calls fail fast or use a fallback; after a cool-down it moves to half-open. Half-open: a few probe calls are allowed; success closes the breaker, a failure re-opens it.
4. What's the difference between load shedding and backpressure?
Load shedding is the overloaded service deciding unilaterally to reject some work early and cheaply, ideally by priority. Backpressure is a cooperative signal to the producer to slow down — bounded queues, pull-based consumption, 429 with Retry-After — so work is delayed upstream rather than dropped or piled up.
5. When are hedged requests appropriate, and when must you never use them?
They suit idempotent, latency-sensitive reads with multiple replicas — product lookups, search shards, cache reads — where sending a second copy after the p95 latency cuts the tail at a small load cost. Never hedge non-idempotent operations such as payment authorization or order creation, because both copies may execute.
6. Scenario: during a flash sale the promotion service slows to 4 s. Which three changes most quickly stop checkout from collapsing?
Cap the promotion call with a short timeout derived from the request deadline; put a circuit breaker on it with a fallback (no voucher or cached rules) so checkout fails over fast; and bulkhead promotion calls with their own small concurrency limit so they cannot exhaust checkout's goroutines and connection pool. Then disable stacked retries and shed low-priority traffic at the gateway.
7. Why should liveness probes not depend on downstream services?
If a shared dependency like the database blips, every pod's liveness fails at once and the orchestrator restarts the whole fleet, turning a short dependency issue into a full outage with cold caches. Liveness should only detect a wedged process; readiness can reflect dependency health to steer traffic.
Exercise
Run a cascading-failure experiment:
- Build three Go services:
gateway → checkout → promotion, plus apayment-callbackendpoint on checkout. Add Toxiproxy (or a sleep flag) in front of promotion. - Load test with
k6orvegetaat a steady rate. Inject 4 s latency into promotion. Record goroutines, latency percentiles, error rate and callback success — with naive settings (30 s timeouts, 3 retries in gateway and checkout). - Apply, one at a time: deadline propagation, single-layer retries with jitter and a budget, a circuit breaker with fallback, a bulkhead for promotion calls, separate callback handling, priority shedding at the gateway. Re-run after each.
- Plot goodput (successful checkouts/s) and callback success for each configuration.
Done when: you have a table showing which pattern contributed most, and the final configuration keeps callbacks at 100% success and checkout goodput near its pre-fault level (degraded only by the missing voucher feature).
Further reading
- Michael Nygard, Release It!, 2nd ed. — stability patterns and anti-patterns.
- Betsy Beyer et al., Site Reliability Engineering (Google), chapters "Handling Overload" and "Addressing Cascading Failures".
- Marc Brooker, "Exponential Backoff And Jitter" — AWS Architecture Blog (2015).
- Jeffrey Dean & Luiz André Barroso, "The Tail at Scale" — CACM, 2013.
- Amazon Builders' Library: "Timeouts, retries, and backoff with jitter" and "Using load shedding to avoid overload".
- Martin Fowler, "CircuitBreaker" (bliki).
- gRPC documentation: deadlines and retry policy / retry throttling.
Related
- Idempotency & Exactly-Once — what makes retries safe.
- Observability & SLOs — signals to tune and alert on these patterns.
- Rate Limiting — admission control at the edge.
- Load Balancing — outlier detection and health checks.
- Flash Sale System — resilience under deliberate overload.
- High Availability & Disaster Recovery — cells, failover and blast-radius reduction.
- Building Production Services — timeouts and contexts in Go services.
Do the self-check first. Marking it complete schedules spaced reviews (1, 3, 7, 14, 30… days).