BE·52
Resilience
Keeping services up when their dependencies aren't. Covers timeouts and deadline propagation, retries with exponential backoff and jitter, retry amplification and budgets, why non-idempotent retries are dangerous, circuit breakers, bulkheads, rate limiting algorithms (token bucket, leaky bucket, windows, GCRA), load shedding and adaptive concurrency limits, graceful degradation, fallbacks and hedging. Shown with Resilience4j and Spring Framework 7's resilience annotations, and compared with Go, Rust's tower, .NET Polly, Python tenacity and service-mesh policies.
Start here: staying up when a dependency doesn't
Failure is normal
A backend calls databases, caches, payment providers, SMS gateways and other teams' services. Each one, at some point, will be slow, return errors, or not answer at all. With 20 dependencies that are each 99.9% available, something is broken about 2% of the time. Resilience is the set of techniques that keep your service useful while that happens, and stop one failing dependency from taking everything down with it. There are five basic tools, each answering one question:
| Tool | Question it answers | Without it |
|---|---|---|
| Timeout | How long will I wait? | One hung dependency holds threads and connections forever |
| Retry (with backoff and jitter) | Was that a one-off failure? | Transient blips become user-visible errors |
| Fallback | What can I do instead? | Optional features break core flows |
| Circuit breaker | Is it pointless to try right now? | Every request waits for the full timeout against a dead service |
| Bulkhead / concurrency limit | How much of me can this dependency use up? | A slow dependency exhausts the threads every other endpoint needs |
Under overload, two more apply: rate limiting (refuse callers who send too much) and load shedding (refuse work you can't finish in time, rather than queueing it).
A checkout that survives a flaky loyalty service
Showing a customer's loyalty points on the receipt is nice; it must never stop an order. The loyalty client below is protected with a timeout, a concurrency limit and retries, and the checkout falls back if it still fails:
@Service public static class LoyaltyClient {
private final HttpClient http = HttpClient.newBuilder().connectTimeout(Duration.ofMillis(200)).build();
@Retryable(includes = IOException.class, maxRetries = 3, delay = 50, multiplier = 2, jitter = 10)
@ConcurrencyLimit(10)
public int points(String customer) throws IOException, InterruptedException {
var res = http.send(HttpRequest.newBuilder(URI.create(".../points?c=" + customer))
.timeout(Duration.ofMillis(300)).build(), BodyHandlers.ofString());
if (res.statusCode() >= 500) throw new IOException("loyalty service returned " + res.statusCode());
return Integer.parseInt(res.body());
}
}
@Service public static class CheckoutService {
public String receipt(String customer) {
String points;
try { points = loyalty.points(customer) + " points"; }
catch (Exception e) { points = "points unavailable right now"; } // fallback: the order still succeeds
return "order confirmed for " + customer + " | " + points;
}
}
@Configuration @EnableResilientMethods @ComponentScan public static class Cfg {}
loyalty service flaky: order confirmed for asha | 120 points | attempts 3 | 343 ms
loyalty service down : order confirmed for asha | points unavailable right now | attempts 4 | 445 ms
loyalty service slow : order confirmed for asha | points unavailable right now | attempts 4 | 1568 ms
Read each line against the tools:
- Flaky (two of every three calls fail): the first two attempts got 503s, the third succeeded. Retries turned a 67% failure rate into a success the customer never noticed.
- Down: four attempts (one plus three retries, waiting about 50, 100 and 200 ms between them) all failed, and the fallback kept the order working.
- Slow (the service takes 5 s): each attempt was cut off by the 300 ms timeout, so the order still completed, but notice the cost: four timeouts plus backoff made the checkout take 1.6 s. Retries multiply latency as well as load, which is why retries need an overall deadline and why a circuit breaker (lab experiment 3) should stop calling a service that's clearly down.
@ConcurrencyLimit(10)is a bulkhead: at most 10 threads can be inside this method at once, so a slow loyalty service can't absorb all of the server's request threads (lab experiment 4).
@Retryable and @ConcurrencyLimit are new in Spring Framework 7 and work through proxies (chapter 46). For circuit breakers, rate limiters and more detailed policies, Java services use Resilience4j; Go has libraries like sony/gobreaker, .NET has Polly, Rust has tower layers, and a service mesh (Istio, Linkerd) can apply timeouts and retries outside the code.
Retrying safely
Retries are the most dangerous of the tools, because they add load at exactly the moment a dependency is struggling. Three rules:
- Only retry what's safe to repeat: idempotent operations (GET, PUT, DELETE) or requests carrying an idempotency key (chapter 45). Retrying "charge the card" without one can charge twice.
- Only retry what might succeed: timeouts, 503, 429 (after
Retry-After), connection resets. Never 400, 401, 403, 404 or 422. - Back off with jitter, and retry at one layer: wait longer each time, randomise the wait so clients don't retry in synchronised waves, and don't let every layer of a call chain retry (the lab's three layers of retries turned one request into 64 calls on the database).
How deep to go in resilience
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, fallbacks, circuit breakers and bulkheads |
| L2 | Apply them with Spring Framework 7 or Resilience4j, with sensible settings |
| L3 | Explain retry amplification, backoff with jitter, breaker state machines, rate-limit algorithms, load shedding and hedging |
| L4 | Diagnose retry storms, cascading timeouts, pool exhaustion and overload from metrics and traces |
| L5 | Set per-dependency resilience policies and budgets; run game days and fault injection |
| L6 | Set organisation-wide reliability patterns, defaults and review standards |
Why systems fail
Failure is the normal case
In a distributed system, dependencies will be slow or unavailable: networks drop packets, garbage collectors pause, databases fail over, deploys restart pods, third-party APIs rate-limit you, and one overloaded service slows everyone that calls it. Resilience patterns don't prevent failure. They contain it, so one dependency's problem doesn't become a system-wide outage.
The most dangerous failures aren't clean errors. Slowness is worse than failure. A dependency that returns errors quickly costs little, but one that hangs for 30 seconds ties up threads, connections and memory in every caller. As requests pile up, callers slow down and their callers slow down too: a cascading failure.
Michael Nygard's Release It! catalogued these patterns: timeouts, circuit breakers, bulkheads, steady state, fail fast, let it crash, handshaking, and backpressure. They apply in every language. Libraries implement them, and the hard part is choosing the right values.
Timeouts and retries
Timeouts
Every remote call needs a timeout. Without one, a hung dependency can hold a thread or connection forever. Defaults are often infinite or very long: Go's http.Client{} has no timeout, Java's HttpURLConnection defaults to infinite, and JDBC queries have no timeout unless set.
Kinds of timeouts:
| Timeout | Bounds | Typical value |
|---|---|---|
| Connect | TCP + TLS handshake | 100 ms – 2 s (in-region connects are fast; slowness means trouble) |
| Read / response | Waiting for the response (per read, or total) | Based on the dependency's p99.9 latency plus margin |
| Pool acquisition | Waiting for a free pooled connection | Short (≈ 1–2 s): fail fast when saturated |
| Overall request deadline | The whole operation, including retries | Driven by the caller's own SLO |
| Database statement / lock | Query execution, lock waits | statement_timeout, lock_timeout |
| Server-side | Read-header, idle and write timeouts on your own servers | Protect against slow clients (Slowloris) |
Choosing values: base them on the dependency's observed latency distribution (p99/p99.9) and your own latency budget, not on round numbers. If your endpoint's SLO is 500 ms and it calls two services sequentially, each can't take 2 seconds.
Deadline propagation: rather than independent timeouts at every hop, pass the remaining time budget downstream, so work stops everywhere once the original caller has given up:
- gRPC has deadlines built in (
grpc-timeoutheader, propagated automatically). - Go passes
context.WithTimeoutthrough every call: every blocking operation takesctxand aborts when it's cancelled. That's the most pervasive implementation of this idea. - In Java, structured concurrency scopes, virtual threads and interruption, and Reactor's
timeout. Across HTTP hops, send a deadline header (some teams useX-Request-Deadline). - .NET
CancellationToken; Rust drops the future (cancellation at.awaitpoints) withtokio::time::timeout.
func (s *Service) Quote(ctx context.Context, sku string) (Price, error) {
ctx, cancel := context.WithTimeout(ctx, 300*time.Millisecond) // never exceeds the parent's remaining deadline
defer cancel()
req, _ := http.NewRequestWithContext(ctx, http.MethodGet, s.pricingURL+"/prices/"+sku, nil)
resp, err := s.http.Do(req) // aborts when ctx expires
if err != nil {
return Price{}, fmt.Errorf("pricing: %w", err) // errors.Is(err, context.DeadlineExceeded)
}
defer resp.Body.Close()
…
}
Retries
Many failures are transient: a dropped connection, a failover in progress, a brief 503, a lock conflict, a rate-limit blip. Retrying often succeeds. But retries are also the most common way to turn a small problem into an outage.
When to retry:
- Only transient errors: connection failures, timeouts (carefully), 408, 429 (honouring
Retry-After), 502, 503, 504, deadlock and serialisation failures, optimistic-lock conflicts (re-reading first). - Not for 400, 401, 403, 404, 409 (business conflict) or 422: retrying won't change the answer.
- Only idempotent operations, or ones protected by idempotency keys (chapter 45).
How to retry: exponential backoff with jitter, and a small, bounded number of attempts:
attempt 1: immediately
attempt 2: wait base × 2^0 = 100 ms ± jitter
attempt 3: wait base × 2^1 = 200 ms ± jitter
attempt 4: wait base × 2^2 = 400 ms ± jitter (cap at max, e.g. 2 s; stop after N attempts or a deadline)
Jitter (randomness in the delay) is essential. Without it, all clients that failed at the same moment retry at the same moment, in synchronised waves (thundering herd), hitting the recovering service in bursts and knocking it over again. AWS's well-known analysis compared strategies:
- Full jitter:
sleep = random(0, min(cap, base × 2^attempt)), simple and effective. - Equal jitter: half fixed, half random.
- Decorrelated jitter:
sleep = min(cap, random(base, previous_sleep × 3)).
Full or decorrelated jitter spreads load best.
Retry amplification
Retries multiply. If each layer retries 3 times (4 attempts) and the failure is at the bottom of a 3-deep call chain, one user request can generate 4 × 4 × 4 = 64 calls to the failing service, right when it's least able to handle them:
Mitigations:
- Retry at one layer: typically the client closest to the failing dependency, or only at the edge. Inner layers fail fast and propagate the error.
- Retry budgets: allow retries only while they're a small fraction of traffic (for example, retries ≤ 10% of requests per client, as in Finagle, Envoy's
retry_budgetand gRPC retry throttling). When everything is failing, retries stop automatically. - Respect
Retry-Afterand deadlines: don't retry if the remaining budget can't fit another attempt. - Circuit breakers (below) stop calling a clearly broken dependency at all.
- Monitor retry rates as a metric. A rising retry rate is an early warning.
Non-idempotent operations
Retrying a timed-out POST /payments/charge may charge the customer twice: the first attempt may have succeeded and only the response was lost (chapter 45). Rules:
- Never auto-retry non-idempotent operations unless you know the request wasn't processed. A connection refused before any bytes were sent is safe; a read timeout isn't.
- Make them idempotent with idempotency keys (generated once per logical operation and reused across retries) or client-generated IDs, and pass them through to downstream providers.
- Some HTTP clients and proxies retry automatically. Check: Envoy and gateway retry policies, OkHttp's
retryOnConnectionFailure, browser behaviour, and load balancers retrying on another backend. Configure them to retry only idempotent methods.
Isolating failure
Circuit breaker
A circuit breaker wraps calls to a dependency and stops calling it when it's clearly failing. That gives it time to recover and makes callers fail fast instead of waiting for timeouts:
// Resilience4j (spring-boot starter): configure in YAML, apply with annotations or functionally
@Service
class PricingClient {
private final RestClient http;
@CircuitBreaker(name = "pricing", fallbackMethod = "cachedPrice")
@Retry(name = "pricing") // aspect order: Retry(CircuitBreaker(call)) by default
@TimeLimiter(name = "pricing") // for async (CompletableFuture) calls
public Price price(String sku) {
return http.get().uri("/prices/{sku}", sku).retrieve().body(Price.class);
}
private Price cachedPrice(String sku, Throwable t) { // fallback signature: same args + Throwable
return priceCache.lastKnown(sku).orElseThrow(() -> new PricingUnavailable(sku, t));
}
}
resilience4j:
circuitbreaker.instances.pricing:
sliding-window-type: COUNT_BASED
sliding-window-size: 50
minimum-number-of-calls: 20 # don't trip on 2 failures out of 2
failure-rate-threshold: 50
slow-call-duration-threshold: 800ms # slow calls count as failures
slow-call-rate-threshold: 60
wait-duration-in-open-state: 30s
permitted-number-of-calls-in-half-open-state: 5
ignore-exceptions: [com.shop.pricing.UnknownSkuException] # business errors aren't dependency failures
retry.instances.pricing:
max-attempts: 3
wait-duration: 100ms
enable-exponential-backoff: true
exponential-backoff-multiplier: 2
enable-randomized-wait: true # jitter
retry-exceptions: [java.io.IOException, org.springframework.web.client.ResourceAccessException]
Design notes:
- One breaker per dependency (or per dependency + endpoint class), not one global breaker.
- Count slow calls as failures. A dependency that's merely slow can be as harmful as a dead one.
- Exclude business errors (404s, validation errors) from failure counting.
- Expose breaker state as metrics and alerts (Resilience4j publishes Micrometer metrics). An open breaker is an incident signal.
- Breakers in front of retries: retrying against an open breaker should fail immediately rather than wait.
Bulkheads
Ships are divided into watertight compartments so one breach doesn't sink the vessel. A bulkhead limits how much of a shared resource any one dependency or workload can consume, so a slow dependency can only exhaust its own share:
- Concurrency limits per dependency: at most 20 in-flight calls to the payments service. When it hangs, only those 20 requests wait, and requests that don't need payments proceed. That's a semaphore (chapter 38), and it's the right choice with virtual threads, where thread pools no longer provide natural limits.
- Separate thread pools per dependency (the classic Hystrix approach): bounded queues, isolation even from CPU-heavy work, and calls can be abandoned on timeout. It's heavier, and less necessary with virtual threads.
- Separate connection pools per database or role (reporting queries can't starve OLTP).
- Infrastructure bulkheads: separate deployments or node pools for critical versus batch workloads, per-tenant capacity, and cell-based architecture (Vol. 5).
// Spring Framework 7: built-in concurrency limiting and retries in spring-core (no extra library)
@Configuration
@EnableResilientMethods
class ResilienceConfig {}
@Service
class PaymentsClient {
@ConcurrencyLimit(20) // bulkhead: at most 20 concurrent invocations
@Retryable(includes = IOException.class, maxRetries = 3, delay = 100, multiplier = 2, jitter = 50, maxDelay = 1000)
public Receipt charge(ChargeRequest r) { … } // charge must carry an idempotency key to be safely retried
}
Rate limiting
Rate limiting caps how many requests a client (or all clients) may make per unit of time. It protects services from abuse, enforces fair use and quotas, and keeps you within downstream providers' limits. The algorithms:
| Algorithm | How | Properties |
|---|---|---|
| Fixed window counter | Count requests per calendar window (per minute); reject above N | Simple. Boundary bursts: up to 2N requests across the edge of two windows |
| Sliding window log | Keep each request's timestamp; count those in the last 60 s | Exact; memory per request |
| Sliding window counter | Weighted blend of the current and previous window counts | Good approximation, cheap (Cloudflare uses it) |
| Token bucket | A bucket holds up to B tokens, refilled at rate R. Each request takes a token; an empty bucket means reject (or wait) | Allows bursts up to B while enforcing an average rate R. The most common choice (AWS API Gateway, Guava RateLimiter-style, Go x/time/rate, Bucket4j) |
| Leaky bucket (as a queue) | Requests enter a queue drained at a constant rate | Smooths output to a constant rate; adds latency |
| GCRA (generic cell rate algorithm) | Tracks a "theoretical arrival time" per key: equivalent to a token bucket with one stored timestamp | Very memory-efficient; used by redis-cell, Stripe and Throttled |
Practical concerns:
- Key by identity: API key, account or tenant (and IP only as a coarse fallback). Use different limits per plan.
- Distributed enforcement: with many instances, counters need shared state (Redis with atomic Lua scripts or
INCRwith expiry, Bucket4j with Redis or Hazelcast). Alternatively, per-instance limits ≈ the global limit divided by the instance count, which is approximate and cheaper. - Where to enforce: at the edge (API gateway, Envoy/NGINX, CDN/WAF) for coarse protection, and in the application for business quotas.
- Respond well: 429 with
Retry-Afterand rate-limit headers (chapter 45). - Client-side limiting when calling providers with quotas (stay under the payment provider's 100 requests per second): a token bucket in your client, ideally shared across instances.
// Go: golang.org/x/time/rate (token bucket) as per-client middleware
var limiters sync.Map // apiKey → *rate.Limiter
func rateLimit(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
key := r.Header.Get("X-Api-Key")
l, _ := limiters.LoadOrStore(key, rate.NewLimiter(rate.Limit(10), 20)) // 10/s, burst 20
if !l.(*rate.Limiter).Allow() {
w.Header().Set("Retry-After", "1")
http.Error(w, "rate limited", http.StatusTooManyRequests)
return
}
next.ServeHTTP(w, r)
})
}
Under overload
Load shedding
When a service is overloaded (more work arriving than it can complete), accepting everything makes every request slow. Queues grow, latency rises past client timeouts, and the service does work whose results nobody will receive (clients already gave up). That's congestion collapse. Load shedding deliberately rejects excess work early and cheaply, so the work that is accepted completes within its deadline:
- Bounded queues everywhere (thread pools, connection pools, in-memory queues), rejecting when full rather than queuing indefinitely.
- Concurrency limits at the server entry: when in-flight requests exceed the limit, return 503 immediately (cheap) instead of accepting and timing out (expensive).
- Adaptive concurrency limits: estimate capacity dynamically from latency, the way TCP congestion control does (Netflix's
concurrency-limitslibrary with Vegas and Gradient algorithms; Envoy's adaptive concurrency filter). The limit tightens automatically as latency rises. - Priority-based shedding: drop low-priority work first (analytics, prefetches, batch jobs) and protect critical paths (checkout, login). Mark priority in a request header.
- Deadline-aware dropping: if a queued request's deadline has already passed (or can't be met), drop it without doing the work.
- LIFO under overload: some systems serve the newest requests first during overload (Facebook's adaptive LIFO), since older ones are likely already abandoned.
Graceful degradation and fallbacks
When a dependency fails, degrade functionality rather than failing the whole request:
| Dependency down | Degraded behaviour |
|---|---|
| Recommendations | Show bestsellers or nothing |
| Pricing service | Serve the last known price from cache, marked stale (if business rules allow) |
| Reviews | Render the page without reviews |
| Search | Fall back to a simpler database query, or show categories |
| Payment provider A | Route to provider B; or accept the order and charge later (business decision) |
| Feature flag service | Use the last-known or default flag values |
Rules for fallbacks:
- Fallbacks must be simpler and more reliable than the primary. A fallback that calls another remote service can fail the same way. Static defaults and local caches are the best fallbacks.
- Make degradation visible in metrics and logs (count fallback activations), and in the UI where appropriate ("prices may be out of date").
- Test fallbacks, through fault injection and chaos experiments (Vol. 6). Untested fallback code is frequently broken when it's finally needed.
- Business-level decisions: whether it's acceptable to sell at a cached price, or to accept an order without a fraud check, isn't a technical call. Agree it with the product owners.
- Kill switches / feature flags let operators disable expensive non-critical features during incidents.
Hedging and other tail-latency techniques
- Hedged requests: if a request hasn't completed by the p95 latency, send a second copy to another replica and use whichever answers first. This cuts tail latency at the cost of a few percent extra load (Google's The Tail at Scale). Use it only for idempotent reads, and cap it with a budget. gRPC supports hedging policies.
- Request coalescing / single-flight: concurrent identical requests share one upstream call (Go's
singleflight, cache stampede protection, chapter 53). - Caching as resilience: serve stale data when the source is down (
stale-if-error).
Implementations across stacks
| Ecosystem | Libraries and mechanisms |
|---|---|
| Java | Resilience4j (circuit breaker, retry, rate limiter, bulkhead, time limiter, cache; functional and annotation APIs; Micrometer metrics), Spring Framework 7 core resilience (@Retryable, @ConcurrencyLimit, RetryTemplate), Spring Cloud Circuit Breaker (an abstraction), Failsafe, Bucket4j (rate limiting), Netflix concurrency-limits; Hystrix is retired |
| Go | context deadlines (built in), golang.org/x/time/rate, sony/gobreaker, failsafe-go, cenkalti/backoff, x/sync/singleflight, x/sync/semaphore |
| Rust | tower middleware: Timeout, Retry (with policies), ConcurrencyLimit, RateLimit, LoadShed, Buffer, all composable as layers in Axum, tonic and Hyper; backon/backoff crates; governor (GCRA rate limiting) |
| .NET | Polly v8 resilience pipelines (retry, circuit breaker, timeout, rate limiter, hedging, fallback), Microsoft.Extensions.Http.Resilience (AddStandardResilienceHandler() gives sensible defaults on HttpClient), and System.Threading.RateLimiting |
| Python | tenacity (retries with backoff and jitter), pybreaker, aiolimiter, asyncio.timeout |
| Node | opossum (circuit breaker), p-retry, bottleneck (rate limiting), AbortSignal.timeout() |
| Elixir/Erlang | Supervisors (let it crash + restart strategies with intensity limits), :fuse (circuit breaker), Hammer (rate limiting), process mailboxes as natural bulkheads (one process per dependency) |
| Platform / mesh | Envoy/Istio/Linkerd: timeouts, retries (with budgets), circuit breaking (outlier detection, connection limits), rate limiting and fault injection, configured outside the application. API gateways and cloud load balancers add more |
// Rust: tower layers compose resilience declaratively around any Service
use tower::{ServiceBuilder, timeout::TimeoutLayer, limit::ConcurrencyLimitLayer, load_shed::LoadShedLayer};
let app = Router::new()
.route("/orders", post(create_order))
.layer(
ServiceBuilder::new()
.layer(HandleErrorLayer::new(handle_overload)) // map shed/timeout errors to 503/504
.layer(LoadShedLayer::new()) // reject immediately when the inner service isn't ready
.layer(ConcurrencyLimitLayer::new(256)) // bulkhead: max in-flight requests
.layer(TimeoutLayer::new(Duration::from_secs(2))), // per-request deadline
);
// .NET: a standard resilience pipeline on an HttpClient (retry + circuit breaker + timeouts + rate limiter)
builder.Services.AddHttpClient<PricingClient>(c => c.BaseAddress = new Uri("https://pricing.internal"))
.AddStandardResilienceHandler(o =>
{
o.AttemptTimeout.Timeout = TimeSpan.FromMilliseconds(500);
o.TotalRequestTimeout.Timeout = TimeSpan.FromSeconds(2);
o.Retry.MaxRetryAttempts = 2; // exponential backoff with jitter by default
o.CircuitBreaker.FailureRatio = 0.5;
});
Library or mesh? Mesh-level policies are language-agnostic and centrally managed, but they don't know application semantics: which operations are idempotent, what a good fallback is, which errors are business errors. Application-level policies have that context. A common split: the mesh handles connect timeouts, outlier ejection, mTLS and coarse retries for idempotent methods, and the application handles deadlines, fallbacks, idempotency keys, bulkheads around specific dependencies, and business-aware retries. Make sure the two layers don't both retry (retry amplification again).
A resilience checklist for each dependency
- Timeout set from measured latency and the caller's budget, propagated as a deadline.
- Retry only transient errors, only idempotent operations (or with idempotency keys), with exponential backoff + jitter, a small attempt count, and at one layer.
- Circuit breaker with slow-call detection, excluding business errors.
- Bulkhead: a concurrency limit or dedicated pool sized to the dependency's capacity.
- Fallback / degradation defined with the business, simple, tested, and visible.
- Rate limits respected (client-side) and enforced (server-side) with clear 429s.
- Observability: metrics for latency, errors, retries, breaker state, rejections and fallbacks, with alerts.
- Tested with fault injection: latency, errors and blackholes (Toxiproxy, chaos tooling, mesh fault injection).
Lab: resilience patterns, measured
JDK 21 on a 2-core machine. Each experiment is a small, real program (threads, queues, sleeps standing in for slow dependencies) rather than a simulation in a spreadsheet, so the numbers include scheduling and timing noise like real systems.
Experiment 1: retry amplification
A user request passes through a gateway, an orders service and a loyalty service to a database that is down. Each layer tries 4 times (1 + 3 retries):
one user request, three layers each retrying 3 times, database down: database received 64 calls
retrying only at the layer next to the database: 4 calls
Retries multiply across layers: 4 × 4 × 4. When the database comes back under load, those 64× bursts from every user can keep it down (a retry storm). Retry at one layer (usually the one closest to the failing dependency, or the client edge, but not both), propagate a deadline so inner layers stop when the caller has given up, and use a retry budget (retries limited to, say, 10% of requests; gRPC and Envoy support this) so retries can never multiply load by more than a fixed fraction.
Experiment 2: synchronised retries
1,000 clients all fail at the same moment (a deploy, a network blip) and retry four times:
fixed 100 ms : peak 1000 retries in one 10 ms window, retries spread over 4 windows
exponential 100·2^n, no jitter : peak 1000 retries in one 10 ms window, retries spread over 4 windows
exponential with full jitter : peak 154 retries in one 10 ms window, retries spread over 137 windows
Without randomness every client retries at exactly the same instants, so the recovering service receives four waves of 1,000 simultaneous requests: exponential backoff alone spaces the waves out but keeps them just as sharp. Full jitter (wait a random time between 0 and the backoff) spread the same retries over 137 windows and cut the peak by 85%. AWS's architecture guidance recommends full or "decorrelated" jitter; Spring's @Retryable(jitter = …) and Resilience4j's randomised interval functions provide it.
Experiment 3: circuit breaker
100 sequential calls to a dependency that hangs, each with a 200 ms timeout:
no breaker: total 20206 ms | p50 200 ms | dependency reached 100 times
circuit breaker (opens after 5 failures): total 1003 ms | p50 0 ms | dependency reached 5 times
Without a breaker, every call paid the full timeout and added load to a service that was already failing. The breaker counted five consecutive failures, opened, and from then on failed calls instantly (so the caller could use its fallback in microseconds) while sending the dependency nothing. After a cool-down it lets a trial call through (half-open) and closes again if that succeeds. Real breakers (Resilience4j) use a failure rate over a sliding window, count slow calls as failures, and expose their state as a metric, which makes an open breaker one of the clearest signals on a dashboard that a dependency is down.
Experiment 4: bulkhead
One shared pool of 20 threads (like Tomcat's). Sixty requests for a slow report (2 s each) arrive just before 20 requests for the menu (5 ms each):
no limit: menu p50 5937 ms, max 5941 ms | reports rejected 0
reports limited to 5 concurrent: menu p50 5 ms, max 10 ms | reports rejected 55
Without a limit, the reports occupied all 20 threads, and the menu, which needed nothing from the slow dependency, waited about 6 seconds behind three rounds of reports: a failure in one feature became an outage of all of them. Capping reports at 5 concurrent (a semaphore; @ConcurrencyLimit(5) in Spring 7, with the REJECT policy to fail instead of block) kept 15 threads for everything else, and the menu stayed at 5 ms. The excess reports were rejected immediately, which the client can retry later. Separate connection pools per dependency and separate thread pools for batch and interactive work are bulkheads too.
Experiment 5: queueing versus shedding under overload
A service that can handle 100 requests per second (2 workers × 20 ms) receives 200 per second for 3 seconds:
unbounded queue: served 600, shed 0 | p50 1564 ms | p99 3101 ms | last served after 6128 ms
queue of 10, reject when full: served 307, shed 293 | p50 118 ms | p99 121 ms | last served after 3111 ms
The unbounded queue "served everyone", but the median request waited 1.5 s and the last 3 s, long after any real client would have timed out and retried (adding more load). Every request was served too late to be useful, and the backlog took twice the overload's duration to drain. Bounding the queue and rejecting the excess (with 503 and Retry-After) served half the requests at a steady 120 ms and recovered the instant the burst ended. That's the core of load shedding: work you can't finish within the client's deadline should be refused at the door, ideally prioritising (keep checkout, shed recommendations). Adaptive concurrency limits (Netflix's concurrency-limits library, Envoy's adaptive concurrency) find the right queue bound automatically from observed latency.
Try it yourself
- Add an overall deadline to Start here's
LoyaltyClient(@Retryable(timeout = 500)in Spring 7.0) and rerun the slow case. How long does checkout take now? - Extend experiment 3's breaker with a half-open trial after 1 s, let the dependency recover after 2 s, and plot when calls start succeeding again.
- Replace experiment 5's fixed queue bound with a CoDel-style rule: shed requests that have already waited more than 50 ms. Compare p99 and throughput.
- Implement a token-bucket rate limiter (10 requests per second, burst 20) and drive it with experiment 5's load. How does it differ from shedding?
Revision sheet: resilience
Key ideas
- Failure is normal: partial failures, slow responses (worse than errors), correlated failures, cascading failures through shared resources.
- Timeouts: connect vs read vs overall; derived from the caller's deadline; deadline propagation (gRPC, headers).
- Retries: transient errors only, idempotent operations only; exponential backoff with full jitter; bounded attempts; one layer; retry budgets; honour
Retry-After. - Circuit breakers: closed → open (failure rate or slow-call rate over a window) → half-open trial; fail fast with fallbacks; expose state as metrics.
- Bulkheads: semaphores, separate pools per dependency,
@ConcurrencyLimit. - Rate limiting: token bucket, leaky bucket, fixed and sliding windows, GCRA; per client and global; 429 with
Retry-After. - Overload: bounded queues, load shedding, priorities, adaptive concurrency limits, CoDel-style queue-time limits.
- Degradation and tail latency: fallbacks, cached or default responses, feature switches; hedged requests for idempotent reads.
- Implementations: Spring Framework 7 (
@Retryable,@ConcurrencyLimit,RetryTemplate), Resilience4j, Polly (.NET), tower (Rust), Go libraries, service-mesh policies.
Numbers to remember
- Lab: three layers of 3 retries → 64 calls; full jitter cut the retry peak from 1,000 to 154 per 10 ms; a breaker turned 100 × 200 ms timeouts (20 s) into 1 s; a bulkhead kept menu latency at 5 ms instead of 6 s; shedding held p99 at 121 ms vs 3.1 s with an unbounded queue.
- Availability compounds: 20 dependencies at 99.9% each ≈ 98% all up.
Pitfalls
- No timeouts, or timeouts longer than the caller's.
- Retrying non-idempotent operations or 4xx errors; retrying at every layer; retries without jitter.
- Fallbacks that hide outages (no metrics, no alerts) or that call the same failing dependency.
- Shared pools with no bulkheads; unbounded queues.
- Circuit breakers with thresholds never tested under real failure (no game days).
Glossary
- Backoff: increasing delay between retries.
- Jitter: randomness added to delays.
- Retry storm: synchronised or amplified retries overwhelming a recovering service.
- Half-open: the breaker state that admits trial calls.
- Bulkhead: isolation of capacity per dependency or workload.
- Load shedding: rejecting excess work early to protect latency.