Bulkheads & Graceful Degradation
"Remember that the code path you never use is the code path that (often) doesn't work." — Google SRE Book, Addressing Cascading Failures
Summary: A bulkhead gives each dependency, tenant or priority class its own fixed slice of a shared resource, so one slow or abusive neighbour can only drown its own compartment; graceful degradation decides in advance what the system stops doing, in what order, when capacity or a dependency runs out. Focus: Resource pools (goroutine, thread and connection pools, semaphores, bounded queues), separate queues and worker fleets, sizing with Little's law, rejection vs queueing, per-tenant limits, cells and shuffle sharding, bulkheads in Kubernetes, Envoy, pgbouncer and PostgreSQL, Laravel queues and Horizon; feature flags, kill switches, stale fallbacks, read-only mode, static pages, brownout, degradation ladders, testing them in game days, and the anti-patterns (shared pools, hard dependencies on optional features, ladders nobody ever climbs). Learning goal: For every dependency and tenant of a system, say which resource it may consume and how much, what happens at the limit (queue, reject, degrade), and which feature goes dark first; then prove the ladder works with a test and a game day rather than hoping.
This chapter sits after Circuit Breaker (stop calling a dependency that is failing) and before Load Shedding (refuse work you cannot finish). It is the structural half of resilience: partition the resources, then decide what to switch off. The failure it prevents is described in Cascading Failures; deadlines and retries live in Timeouts, Retries & Jitter and Service Communication; queue mechanics in Competing Consumers, Backpressure & Flow Control and Laravel Queue Internals; database connection pools in Connection Pooling. Persian: نسخهٔ فارسی.
Page map
| If you are looking for | Go to |
|---|---|
| The whole page in three tables | Everything in one minute |
| Why a shared pool turns one slow call into an outage | Why it exists |
| Nygard, Hystrix, Route 53, cells, SRE | Where it comes from |
| The idea of a compartment | Bulkhead |
| Goroutine, thread, connection pools, semaphores | Resource pools |
| Bounded queues, separate queues, worker fleets, reject or wait | Queues |
| How many slots, how long a queue | Sizing |
| Per-tenant limits, cells, shuffle sharding | Tenants and cells |
| Kubernetes, Envoy, pgbouncer, replicas | Platform bulkheads |
| What graceful degradation is | Graceful degradation |
| Feature flags, kill switches, brownout | Flags and brownout |
| The ladder, QoS tiers, read-only mode, static page | Degradation ladder |
| Stale data, partial results, fallbacks that bite | Stale and partial |
| Game days, metrics for degraded modes | Testing and observability |
| Exact knobs, defaults, error messages | Mechanics |
| Code | Go, Laravel |
| Classic failures and fixes | Solving the classic problems |
| Which isolation, which degradation | Choosing |
| Monolith to distributed system | In architecture |
| Run it | Lab |
| Wrong beliefs, summary, quiz, terms | Misconceptions, Cheat sheet, Self-check, Glossary |
Everything in one minute
The two ideas.
| Idea | In plain words | Tiny example | What it limits |
|---|---|---|---|
| Bulkhead | Fixed slice of a resource per neighbour | 20 connections for reports, 40 for checkout | The blast radius of a slow or greedy neighbour |
| Graceful degradation | Do less on purpose instead of failing | Product page without recommendations | The damage when capacity or a dependency is gone |
Where a bulkhead can live, smallest to largest.
| Layer | Compartment | Mechanism | Typical product or API |
|---|---|---|---|
| In process | Calls to one dependency | Semaphore, goroutine pool, bounded queue | Go golang.org/x/sync/semaphore, Resilience4j Bulkhead, Hystrix |
| Process to database | Connections per service | Connection pool, role limit | pgbouncer pool_size, PostgreSQL CONNECTION LIMIT |
| Queue | Job class | Separate queue and worker fleet | Laravel queue:work --queue=critical,default, Horizon supervisor |
| Proxy or mesh | Upstream cluster | Connection, pending and request limits | Envoy circuit breaker thresholds |
| Orchestrator | Pods, nodes, teams | requests and limits, PriorityClass, PodDisruptionBudget, node pool, namespace quota | Kubernetes |
| Tenant | Customer or shard | Per-tenant limit, shuffle shard | AWS Route 53, API gateways |
| Whole stack | A full copy of the service | Cell-based architecture | AWS cells, regional deployments |
The degradation ladder (this page's running example).
| Rung | Name | What turns off | Entry signal (example) | Users notice |
|---|---|---|---|---|
| 0 | Normal | Nothing | - | Nothing |
| 1 | Shed optional | Recommendations, personalisation | Load 70% | Plainer page |
| 2 | Cached only | Reviews, search suggestions; stale cache allowed | Load 85% | Slightly old data |
| 3 | Read only | All writes (503 + Retry-After) | Load 95% | Cannot change anything |
| 4 | Static page | Everything dynamic | Load 110% or operator | A static notice |
The picture is the whole chapter's first idea. Same threads, same slow dependency: with one shared pool the checkout call is rejected behind slow recommendation calls; with two compartments only the recommendation calls are rejected.
Why it exists
A shared resource has one failure mode: the slowest consumer wins. If every outbound call draws from one pool of 200 goroutines or one pool of 50 database connections, then one dependency whose latency goes from 20 ms to 20 s holds every slot, and the callers of all the other, healthy dependencies queue behind it. By Little's law the number of requests in flight equals arrival rate times latency, so a 1000x latency rise needs 1000x the slots to keep up. No pool is that big, so the pool fills, the service stops answering, and its callers see the outage (Cascading Failures).
| Shared resource | Isolated resource |
|---|---|
| Cheap and efficient: idle capacity is reused | Some capacity idles while a neighbour is full |
| One slow dependency can consume everything | A slow dependency can consume only its slice |
| Failure of a minor feature takes down the major ones | Minor features fail alone and visibly |
| Simple to configure | One more number per dependency to size and watch |
| Great average utilisation | Great worst case |
The analogy we reuse on this page: the ship with watertight compartments. A hull without bulkheads sinks when one hole lets water into the whole length. With watertight walls the water fills one compartment and the ship floats. The cost is that a compartment can be full while others are empty, and that you must decide where to put the walls. Graceful degradation is the crew's plan for the flooded compartment: close that deck, keep the engine room, keep the lifeboats reachable.
Three common misunderstandings, up front
- "A circuit breaker already protects me from a slow dependency." A breaker opens after it has seen failures and only if you count slowness as failure. Until it opens, and for any slow-but-working period, the threads are already stuck. The bulkhead limits damage from the first request; the breaker then stops sending requests (Circuit Breaker). They are partners, not substitutes.
- "Graceful degradation means a nice error page." It means the system keeps doing its most valuable work with less. Google's SRE book describes it as taking "the concept of load shedding one step further by reducing the amount of work that needs to be performed", for example searching "only a subset of data stored in an in-memory cache".
- "We have a fallback, so we are safe." An untested fallback is a second, rarely used program. AWS's article is blunt: "At Amazon we have found that spending engineering resources on making the primary (non-fallback) code more reliable usually raises our odds of success more than investing in an infrequently used fallback strategy." Degradation that nobody exercises is the SRE book's untested code path.
Where it comes from
Ship bulkheads, then software. The word comes from naval architecture. Michael Nygard's Release It! (second edition, January 2018) lists "Bulkheads" in its Stability Patterns chapter beside Timeouts, Circuit Breaker, Steady State, Fail Fast, Let It Crash, Handshaking, Shed Load and Create Back Pressure (table of contents on the publisher's page).
Hystrix. Netflix's Hystrix wiki states: "Hystrix employs the bulkhead pattern to isolate dependencies from each other and to limit concurrent access to any one of them." Each command ran on a per-dependency thread pool (or a semaphore); when "the thread-pool and queue (or semaphore, if not running in a thread) that are associated with the command are full then Hystrix will not execute the command but will immediately route the flow to ... Get the Fallback." Resilience4j kept the idea as two modules: a SemaphoreBulkhead and a FixedThreadPoolBulkhead "which uses a bounded queue and a fixed thread pool", with defaults maxConcurrentCalls 25 and maxWaitDuration 0.
Shuffle sharding, Route 53. The AWS Builders' Library article describes giving each customer a virtual shard of workers: with "eight workers, there are 28 unique combinations of two workers", so the scope of impact "is just 1/28th. That's 7 times better than regular sharding." Route 53 uses 2048 virtual name servers and four per domain, "a staggering 730 billion possible shuffle shards".
Cell-based architecture. The AWS Well-Architected guidance Reducing the Scope of Impact with Cell-Based Architecture (published 20 September 2023) says it "expands one of the best practices from the AWS Well-Architected Framework, Use bulkhead architectures to limit scope of impact", and that cell-based architecture "can give your workload more fault isolation, predictability, and testability".
Google SRE, 2016. The cascading-failures chapter gives the vocabulary of degraded results, load shedding and "Enter Degraded Modes", and the warning about unexercised code paths.
Year Idea What changed in practice
1 - Watertight compartments in ships The metaphor
2 - Nygard, Release It!: Bulkheads Isolation named as a stability pattern
3 - Netflix Hystrix: per-dependency pools Thread-pool isolation plus fallback by default
4 2016 Google SRE: degraded modes, untested paths Degradation is engineered and exercised
5 - AWS Route 53: shuffle sharding Per-customer shards; 1/28 instead of 1/4
6 2018 Release It!, 2nd edition Pattern catalogue (incl. Bulkheads) in print
7 2023 AWS cell-based architecture guidance Whole-stack copies as the largest bulkheadThe concept catalogue
Each block follows the same order: plain words, the usual wrong belief, a definition, a timeline, real scenarios, how products provide it, and the fix.
The bulkhead Must-know
In plain words: Give each thing that can go wrong its own fixed share of a resource, so when it goes wrong it can only use up its own share.
Common misunderstanding: "More capacity solves this." Capacity helps a little; a slow dependency multiplies the slots it needs by its latency, so any finite shared pool is eventually emptied by the slowest user. Partitioning, not size, is the fix.
Definition: A bulkhead is a hard limit on the concurrency (or share) of one resource that a given dependency, tenant or priority class may hold, with a defined behaviour at the limit: wait a bounded time, or reject at once.
Shared pool of 8 slots; recommendations (recs) hangs for 300 ms, checkout needs 5 ms
1 t=0 ms 40 recs calls arrive -> 8 slots taken, 32 queue
2 t=10 ms checkout call arrives -> no free slot, waits
3 t=50 ms checkout waited 40 ms -> gives up: rejected (a healthy dependency failed)
With bulkheads recs=4 slots, checkout=4 slots
4 t=0 ms 40 recs calls arrive -> 4 run, 36 rejected immediately (maxWait 0)
5 t=10 ms checkout call arrives -> own slot free, served in 5 msReal scenario: A product page calls inventory, pricing and recommendations in parallel; recommendations hangs and the whole page times out. A reporting job opens 80 connections and starves checkout. One tenant's import saturates the shared worker fleet. A noisy neighbour pod uses all CPU on a node.
What provides it: the table in Everything in one minute: semaphores and pools in code, pgbouncer and role limits for the database, separate queues for jobs, Envoy limits at the proxy, requests and limits at the node, cells for whole stacks.
Fix: put a limit around every outbound dependency and every tenant-controlled resource; choose queue-or-reject for each (see Queues); then size it (Sizing). Go: bulkhead. Laravel: Cache::funnel (Laravel).
Resource pools: threads, goroutines, connections, semaphores Must-know
In plain words: A pool is a fixed number of ready workers or connections that callers borrow. A semaphore is the simplest pool: a counter of free slots with no workers attached.
Common misunderstanding: "Go has cheap goroutines, so Go does not need bulkheads." Goroutines are cheap; the things they hold are not: file descriptors, database connections, memory per in-flight request, the downstream's capacity. Unbounded goroutines just move the exhaustion to memory or to the dependency.
Definition: A thread pool bulkhead runs calls on a dedicated set of threads (Hystrix default); a semaphore bulkhead lets the caller's own thread run the call but caps how many may do so at once (Go semaphore.Weighted, Resilience4j SemaphoreBulkhead). A connection pool caps open connections to one server.
Semaphore bulkhead, limit 2, maxWait 20 ms
1 A: TryAcquire -> ok (in flight 1)
2 B: TryAcquire -> ok (in flight 2)
3 C: TryAcquire -> fail; Acquire with 20 ms timeout starts
4 A: Release (in flight 1)
5 C: Acquire returns (waited 7 ms) -> runs
6 D: TryAcquire -> fail; Acquire times out after 20 ms -> ErrFull (rejected)Real scenario: a service that calls payments, inventory and email; an HTTP client per dependency each with its own MaxConnsPerHost; Hikari or database/sql pools per service; a PHP-FPM pool per site (pm.max_children).
| Mechanism | Counts | Waiting behaviour | Where |
|---|---|---|---|
| Thread pool (dedicated) | Threads | Bounded queue, then reject | Hystrix, Resilience4j FixedThreadPoolBulkhead |
| Semaphore | Concurrent calls | Acquire(ctx) waits; TryAcquire fails at once | Go golang.org/x/sync/semaphore, Resilience4j SemaphoreBulkhead |
| Buffered channel as semaphore | Concurrent calls | Block or select with default | Go stdlib |
| Connection pool | Open connections | Wait for ConnMaxLifetime/pool timeout | database/sql, pgbouncer |
Cache::funnel | Concurrent executions across servers | block(seconds) then failure closure or exception | Laravel 13 |
Envoy max_requests | Outstanding requests per cluster | Overflow counter, x-envoy-overloaded | Envoy |
Fix: per dependency, one semaphore (or pool) sized with Little's law, a bounded wait, a metric for rejections. Do not share a pool between a critical and an optional dependency.
Queues: bounded, separate, prioritised Must-know
In plain words: A queue is a waiting room. A bounded queue has a fixed number of chairs; when they are full you turn people away. Separate queues give each kind of job its own waiting room and its own staff.
Common misunderstanding: "An unbounded queue is safe because nothing is lost." A queue that only grows turns overload into latency: every job eventually succeeds, after the user gave up. The SRE book makes the point for servers: "Servers should protect themselves from becoming overloaded and crashing. ... fail early and cheaply."
Definition: Rejection answers "no" at once (HTTP 503/429, ErrFull); queueing delays the work. A bounded queue converts excess load into rejection; a separate queue with its own worker fleet isolates one job class; a priority queue serves classes in order but can starve the low class (one worker fleet, shared fate on a crash).
Laravel: one queue vs separate queues
1 default queue: 5,000 BuildRecommendations (2 s each) + 1 ChargeCard
2 10 workers drain 5/s -> ChargeCard waits behind ~1,000 s of work
Separate queues
3 critical: 1 ChargeCard -> own 4 workers, runs immediately
4 low: 5,000 jobs -> own 3 workers, drains in ~55 min; nobody else caresReal scenario: password-reset emails stuck behind a 2 million-row export; webhooks from one noisy tenant delaying all others; Kafka consumers with one slow partition (see Competing Consumers).
| Choice | Pro | Con | Use when |
|---|---|---|---|
| Reject at the limit | Fast failure, no latency growth | Client must retry or degrade | Interactive requests |
| Wait up to a bound | Absorbs short bursts | Adds latency up to the bound | Bursty but fast dependencies |
| Unbounded queue | Nothing refused | Latency and memory grow without limit | Almost never; batch only with monitoring |
| Priority queue, one fleet | Simple | Starvation, shared worker crash | Few classes, similar cost |
| Separate queues and fleets | Hard isolation, per-class scaling | More processes to run | Classes with very different cost or importance |
Fix: bound every queue; size it from the wait you can tolerate (Sizing); give classes with different importance their own queue and fleet. Laravel: php artisan queue:work --queue=critical,default (strict order inside one worker) and one Horizon supervisor per class (separate fleets).
Sizing: Little's law, queue length, rejection vs queueing Must-know
In plain words: Slots needed = requests per second x seconds each takes. Queue length is how many people you let wait before the oldest has waited too long.
Common misunderstanding: "Set the pool as large as the downstream allows." The pool must be sized from your own traffic and its latency, with headroom; a pool as big as the dependency's capacity lets you flood it, and a pool sized for the average latency collapses when latency doubles. Size for the latency you promise, not the latency you hope for.
Definition: Little's law: L = lambda x W (requests in the system = arrival rate x mean time in system). For a compartment, slots = rate x latency x (1 + headroom). Throughput of a full compartment = slots / latency. Maximum useful queue = throughput x maximum acceptable wait.
Checkout calls the payment provider
1 rate lambda = 200 req/s, mean latency W = 50 ms -> L = 200 x 0.05 = 10 in flight
2 headroom 30% -> 13 slots
3 full compartment throughput = 13 / 0.05 -> 260 req/s
4 tolerate 100 ms of queueing -> queue <= 260 x 0.1 = 26
5 latency rises to 500 ms -> 13 slots now serve only 26 req/s
6 the other 174 req/s are rejected (or degraded) instead of piling upReal scenario: 13 slots for payments, 3 for the recommendation builder, 5 connections for reports; a per-tenant concurrency of 10 on an API.
| Number | Formula | Example |
|---|---|---|
| Concurrency (slots) | rate x latency x (1 + headroom) | 200 x 0.05 x 1.3 = 13 |
| Capacity of the compartment | slots / latency | 13 / 0.05 = 260 req/s |
| Queue bound | capacity x tolerable wait | 260 x 0.1 = 26 |
| Slots after a latency spike | unchanged; throughput = slots / new latency | 13 / 0.5 = 26 req/s |
| Pool total across instances | per-instance slots x instances | 13 x 12 pods = 156 against the dependency |
Fix: write the three numbers (slots, queue bound, max wait) next to every bulkhead; recompute when latency or traffic changes; remember to multiply by the number of instances when the dependency has its own cap (see Latency Budgets for queueing delay and the knee). Go: sizing.Slots, sizing.MaxQueue.
Tenants, cells and shuffle sharding Important
In plain words: In a multi-tenant system the dangerous neighbour is another customer. Limit each tenant; for big systems, give each tenant only a few workers chosen so that no two tenants share all of theirs.
Common misunderstanding: "Per-tenant rate limits are enough." A rate limit bounds request count, not cost: one tenant's few expensive requests can still hold every worker. Concurrency per tenant and a smaller blast radius (shards or cells) are the second and third layers (Rate Limiting owns the algorithms).
Definition: A per-tenant limit caps rate, concurrency or queue share per tenant. Sharding splits tenants over groups of workers. Shuffle sharding assigns each tenant k of n workers, so the number of distinct shards is C(n,k) and a bad tenant fully disables only the tenants with the identical set. A cell is a complete, independent copy of the service (compute, storage, queues) serving a fixed subset of tenants, behind a thin routing layer.
8 workers, 2 per tenant (AWS Builders' Library example)
1 Plain sharding into 4 groups : bad tenant hurts 1 of 4 groups -> 25% of tenants
2 Shuffle sharding, C(8,2) = 28 : bad tenant hurts 1 of 28 shards -> about 3.6% (7x better)
3 Tenant A on w1+w4 sends poison requests: w1 and w4 fail
4 Tenant B on w1+w8 retries and reaches w8 -> degraded, not down
5 Tenant C on w2+w5 never noticesReal scenario: DNS (Route 53); a SaaS where a customer's bulk import must not slow others; an API gateway that routes each API key to 2 of 20 backends; a payment platform with one cell per region and merchant range.
| Technique | Blast radius | Cost | Needs |
|---|---|---|---|
| Shared everything | 100% | Lowest | - |
| Per-tenant limits | Bounded per tenant for what you limit | Low | Tenant id on every request |
| Plain shards | 1 / shards | Medium | Routing by tenant |
| Shuffle shards | about 1 / C(n,k) | Medium; clients must retry on another worker | Stable hash, retrying clients |
| Cells | 1 / cells for the whole stack | High: N copies, a router, cell migration | A cell router that is itself simple and reliable |
Fix: start with per-tenant concurrency and queue limits; add shuffle sharding when one worker pool serves many tenants; use cells when a bad deploy or data corruption must also be contained. Go: shuffle.Shard, shuffle.FullyAffected. Tenancy models themselves: Multi-Tenancy.
The picture is the AWS example: eight workers, two per tenant. Tenant A's poison hits w1 and w4; B loses one worker and keeps w8; C shares nothing.
Platform bulkheads: Kubernetes, Envoy, pgbouncer, PostgreSQL Must-know
In plain words: The platform can build the walls for you: limits on pods, limits on a proxy's connections to one upstream, limits on database connections per service.
Common misunderstanding: "Setting a CPU limit protects the neighbours." A CPU limit throttles the pod itself; the protection of the neighbours comes from requests (what the scheduler reserves) and from sensible limits. Kubernetes documents the difference: "cpu limits are enforced by CPU throttling" while "memory limits are enforced by the kernel with out of memory (OOM) kills". A memory limit that is too low kills your own pod; no limit lets one pod take the node's memory.
Definition: In Kubernetes, requests and limits set per-container reservation and ceiling; a ResourceQuota caps a namespace; a PriorityClass orders scheduling and preemption; a PodDisruptionBudget limits voluntary evictions; a node pool (labels, taints) dedicates machines. In Envoy, each upstream cluster has circuit breaker thresholds: max_connections, max_pending_requests, max_requests, max_retries, per priority. In PostgreSQL land, each service gets its own pgbouncer pool and role limits.
Envoy cluster "recommendations": max_connections 50, max_pending_requests 20
1 60 requests arrive while all 50 connections are busy
2 20 requests go into the pending queue (max_pending_requests)
3 remaining requests overflow -> 503 with x-envoy-overloaded; upstream_rq_pending_overflow++
4 the checkout cluster has its own limits and is not affectedReal scenario: a batch job that starves a latency-critical service on the same node; a node drain that takes down all replicas of a service at once; an analytics query that holds all 100 PostgreSQL connections; a retry storm against a single upstream.
| Product | Bulkhead knob | What it does | Default or note |
|---|---|---|---|
| Kubernetes | requests and limits | Reserve and cap CPU and memory per container | Equal requests and limits give the Guaranteed QoS class, the last to be evicted |
| Kubernetes | ResourceQuota per namespace | Caps total requests, limits, pod count | One quota per team namespace |
| Kubernetes | PriorityClass | Who is scheduled first and who is preempted | preemptionPolicy defaults to PreemptLowerPriority; Never opts out |
| Kubernetes | PodDisruptionBudget | minAvailable or maxUnavailable for voluntary disruptions | Percent or integer |
| Kubernetes | node pool, nodeSelector, taints | Dedicated machines per class | Cloud-specific naming |
| Envoy | max_connections | Connections to all hosts of the upstream cluster | 1024 per cluster by default |
| Envoy | max_pending_requests | Requests queued waiting for a connection | Overflow counter upstream_rq_pending_overflow |
| Envoy | max_requests | Outstanding requests to the cluster | Overflow counter upstream_rq_active_overflow |
| Envoy | max_retries / retry_budget | Concurrent retries | Keep low to stop retry storms |
| pgbouncer | default_pool_size, per-database pool_size | Server connections per user/database pair | 20 |
| pgbouncer | max_db_connections, max_user_connections | Ceilings across pools | 0 = unlimited |
| pgbouncer | max_client_conn, pool_mode | Client connections; reuse unit | session is the default; transaction is common for web apps |
| PostgreSQL | statement_timeout, lock_timeout, idle_in_transaction_session_timeout | Kill statements, waits and idle transactions | 0 (disabled) by default |
| PostgreSQL | analytics replica | Read-only copy for slow queries | See Replication |
The picture is one request's path with a limit at every layer. Each layer's limit is the compartment wall for the layer behind it; the Kubernetes layer sits underneath all of them.
Fix: one manifest holds the namespace quota, the two PriorityClasses, a Guaranteed-QoS Deployment on a dedicated node pool and its PodDisruptionBudget.
# Namespace-level bulkhead: a quota caps the whole team, a PriorityClass
# decides who is evicted first, a PodDisruptionBudget limits voluntary loss.
apiVersion: v1
kind: ResourceQuota
metadata:
name: shop-quota
namespace: shop
spec:
hard:
requests.cpu: "20"
requests.memory: 40Gi
limits.cpu: "40"
limits.memory: 80Gi
pods: "200"
---
apiVersion: scheduling.k8s.io/v1
kind: PriorityClass
metadata:
name: checkout-critical
value: 1000000
globalDefault: false
description: "Payment and checkout pods; scheduled first, evicted last."
---
apiVersion: scheduling.k8s.io/v1
kind: PriorityClass
metadata:
name: batch-low
value: 1000
preemptionPolicy: Never
description: "Batch and report pods; may be preempted, never preempt others."
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: checkout
namespace: shop
spec:
replicas: 6
selector:
matchLabels: {app: checkout}
template:
metadata:
labels: {app: checkout}
spec:
priorityClassName: checkout-critical
nodeSelector:
pool: critical # dedicated node pool
containers:
- name: app
image: registry.example.com/shop/checkout:1.0.0
resources:
requests: {cpu: "1", memory: 1Gi}
limits: {cpu: "1", memory: 1Gi} # requests == limits -> Guaranteed QoS
---
apiVersion: policy/v1
kind: PodDisruptionBudget
metadata:
name: checkout-pdb
namespace: shop
spec:
maxUnavailable: 1 # node drains evict at most one checkout pod at a time
selector:
matchLabels: {app: checkout}Graceful degradation Must-know
In plain words: When something is broken or overloaded, keep doing the important work and drop the rest, on purpose, in an order you chose in advance.
Common misunderstanding: "Degradation is a fallback to a second implementation." Mostly it is the opposite: less work (skip the feature, serve a cached copy, return a partial list), not a different mechanism that must also be built and tested. AWS argues against heavy fallbacks for exactly that reason; the cheap forms (omit, cache, default) are the ones that survive.
Definition: Graceful degradation is a designed reduction of functionality or quality that keeps the critical path (the few user journeys the business cannot lose, e.g. browse, cart, pay) working. Reduced functionality removes features; stale data trades freshness; partial results return what finished; progressive enhancement builds the page so the core works without the optional layers.
Product page, recommendations service is down
1 GET /products/42 -> product data from cache.flexible (30 s fresh, 5 min stale)
2 recommendations call -> bulkhead slot taken, 500 ms timeout expires
3 catch: omit recommendations (or serve last good list)
4 response -> 200, "degraded": true, header X-Degraded: recommendations
5 metric degraded_responses{feature="recommendations"}++Real scenario: a search box that falls back to prefix search when the ranker is slow; a feed that shows the last computed page; a dashboard that renders tiles independently and shows "unavailable" in one; a shop that hides "add review" in an incident; Google's example of searching "a subset of data stored in an in-memory cache".
| Degradation type | What the user gets | Example |
|---|---|---|
| Omit | The feature is gone | No recommendations carousel |
| Default | A generic value | Popular items instead of personalised |
| Stale | An older but valid value | Price from 5 minutes ago |
| Partial | Some of the parts | 8 of 10 tiles |
| Cheaper algorithm | Lower quality, lower cost | Less accurate ranking |
| Read only | Browse but not change | No new orders; order history works |
| Static | A fixed page | Status notice from the CDN |
Fix: write the list of features, mark each critical or optional, decide the order in which optional ones go dark, and give each a cheap fallback (Degradation ladder). Code: Go degrade, Laravel Cache::flexible and Pennant.
Feature flags, kill switches, brownout Important
In plain words: A feature flag is a switch the operator can flip without deploying. A kill switch is the flag you flip in an emergency to turn one thing off. A brownout is turning a feature off for only some users, a fraction at a time, to shed load gradually.
Common misunderstanding: "Flags are for launches." A flag that exists only to be switched off during an incident is just as valuable, but only if it works without the thing that is broken: a kill switch that reads its state from the failing dependency is useless. SRE warns about the other side too: complex automatic degradation can trip when not wanted; "Design a way to quickly turn off complex graceful degradation or tune parameters if needed."
Definition: A feature flag gates code at runtime (LaunchDarkly, Unleash, Laravel Pennant, a config table). A kill switch is a flag with a default of "on" that operators set to "off", read from a local or highly available source. Brownout disables a feature for a percentage of requests chosen by a stable hash, so a given user does not flicker.
Brownout at 25% for "reviews"
1 request, user u-1041 -> hash(reviews|u-1041) mod 1000 = 612 -> >= 250 -> reviews shown
2 request, user u-77 -> hash(reviews|u-77) mod 1000 = 114 -> < 250 -> reviews hidden
3 same user u-77, next click -> same hash -> still hidden (stable)
4 load recovers -> brownout set to 0% -> everyone sees reviewsReal scenario: switching off the "similar items" panel during a flash sale; turning off an expensive export; disabling a new feature that leaks memory; progressive brownout of a recommender at 50% to keep p99 under the SLO.
| Mechanism | Scope | Product | Note |
|---|---|---|---|
| Config flag in a cache or database | All users | Laravel Cache, a flags table | Must not depend on the broken service |
| Pennant feature, per scope | A user, team or everyone | Laravel Pennant | Stores the resolved value; use before() or activateForEveryone / deactivateForEveryone |
| Percentage rollout | A share of users | Pennant Lottery::odds, LaunchDarkly, Unleash | Stable for the same scope |
| Brownout | A share of requests | Custom (Go SetBrownout) | Stable hash per user |
| Envoy / gateway route | A route or tenant | Envoy, API gateway | Works for services you do not control |
Fix: every optional dependency gets a flag; every flag has an owner and an on-call runbook line; flags are read from local memory with a refresh, not per request from a remote service; automatic changes (brownout, ladder) have hysteresis and a manual override.
The degradation ladder, QoS tiers, read-only mode, static page Must-know
In plain words: A ladder is the ordered list of things you switch off, cheapest to give up first, with a trigger for each rung and a way back down.
Common misunderstanding: "One 'degraded mode' flag is enough." One flag has one meaning, so it either does too little or too much. A ladder gives proportional responses; each rung is a test case. And it needs hysteresis: without it the controller flaps between rungs and the flapping itself becomes the outage.
Definition: A degradation ladder is an ordered set of levels, each defined by which features are off, which signal enters it and which exits it. QoS tiers (quality-of-service tiers) say which customers or request classes are degraded first (free before paid, anonymous before logged in, bots before humans). Read-only mode refuses writes but serves reads. A static page is the last rung: pre-rendered content from a CDN. Maintenance mode is the deliberate, announced version (Laravel php artisan down).
Controller with enter thresholds 0.70 / 0.85 / 0.95 / 1.10, hysteresis 0.10, dwell 30 s
1 load 0.50 -> level 0 normal
2 load 0.75 -> level 1 shed-optional (recommendations off)
3 load 0.65 -> still level 1 (inside the 0.60-0.70 band)
4 load 0.30, 10 s later -> still level 1 (minimum dwell not elapsed)
5 load 0.30, 31 s later -> level 0 normal
6 operator forces level 3 -> read-only until forced back to automaticThe picture is the ladder used by the Go and Laravel code: five rungs, entry loads on the right, and the rule that recovery needs a lower load and time.
Real scenario: a ticket sale where anonymous browsing is cached and only logged-in users reach the queue; an API that rejects free-tier traffic first; a bank app in read-only mode during a database failover (balance and history work, transfers wait); a media site serving a static page from the CDN while the origin is rebuilt.
| QoS tier | Degraded first | Why |
|---|---|---|
| Free or anonymous | Early rungs | Lowest revenue per request |
| Bots, crawlers, bulk API | Before humans | Can retry later |
| Background jobs | Before interactive | Nobody is waiting |
| Paying or logged-in customers | Last | Highest value |
| Critical path (browse, cart, pay) | Never until static | The business |
Fix: write the ladder as a table (rung, features off, entry signal, exit signal, owner); implement it in one controller; expose the level as a metric and a header; rehearse each rung (Testing). Laravel: php artisan down --secret=... for maintenance mode with a bypass; a ReadOnlyMode middleware for rung 3.
Stale data, partial results and fallbacks that bite Important
In plain words: Old data is usually better than no data, and some of the page is better than none, if the user is told or the staleness is harmless.
Common misunderstanding: "Serving stale data is always safe." Stale prices and stock can cause real harm (selling at the wrong price, overselling). Staleness must be bounded per field, and money-moving paths read the source of truth or refuse. And a fallback has costs: "Fallback logic can also place unpredictable load on the system" (AWS), for example a fallback to the database that stampedes it when the cache fails.
Definition: Stale cache = serve an expired value while the origin is unavailable (stale-if-error) or while refreshing in the background (stale-while-revalidate). Partial results = return the pieces that completed within the deadline and mark the rest missing. A fallback is an alternative path (secondary service, default value, cached copy).
Laravel Cache::flexible('product:42', [30, 300], ...)
1 t=0 s miss -> compute, store (fresh)
2 t=20 s hit -> returned at once (fresh, < 30 s)
3 t=100 s hit in stale window -> stale value returned, refresh deferred until after the response
4 t=400 s beyond 300 s -> recomputed now; if the origin is down, the request fails or falls backReal scenario: a catalogue served from cache while the database fails over; a dashboard where 1 of 6 widgets times out; weather or exchange-rate widgets showing "as of 10:15"; a search that returns results from the cache tier only.
| Fallback | Risk | Mitigation |
|---|---|---|
| Cached or stale copy | Wrong data after a long outage | Maximum staleness, label, never for money |
| Default or generic value | Misleading personalisation | Mark as default |
| Secondary service | Untested, different capacity | Prefer to make the primary reliable; exercise regularly |
| Direct database read when the cache fails | Stampede, takes the database too | Bulkhead and rate-limit the fallback; request coalescing |
| Retry later (queue) | Hidden backlog | Bounded queue, visible depth |
Fix: prefer omit, default and stale over a second implementation; bound staleness; protect the fallback with its own bulkhead; test it. Go StaleCache (stale-if-error), Laravel Cache::flexible plus a last-good key. Cache mechanics live in Caching.
Testing and observing degraded modes Important
In plain words: A degradation plan that has never run is a guess. Run it on purpose, in staging and in a controlled slice of production, and make it visible on a dashboard.
Common misunderstanding: "Unit tests of the fallback are enough." They prove the branch returns something; they do not prove the limits, the thresholds, the metrics or the people. SRE's advice: "make sure that graceful degradation stays working by regularly running a small subset of servers near overload in order to exercise this code path." That is a game day in miniature (Chaos Engineering).
Definition: A game day is a planned exercise where a failure is injected (dependency latency, dependency down, a tenant flooding) and the team verifies that the ladder triggers, the bulkheads reject instead of queue, the critical path stays green and the alert fires. Observability of degraded modes means a metric per compartment (in flight, rejected, wait time) and per rung (current level, time at level, degraded responses).
Game day: recommendations service gets +2 s latency
1 inject 2 s latency into recs (Envoy fault filter / toxiproxy)
2 bulkhead recs: in flight 4/4, rejected rate rises to 90% (expected)
3 ladder moves to level 1 within 10 s (expected)
4 checkout success rate stays >= 99.9%, p99 < 400 ms (pass criterion)
5 remove fault: level returns to 0 after dwell (pass criterion)
6 alert "degraded > 15 min" fired and resolved (pass criterion)Real scenario: quarterly game days; a canary pod pinned at level 2 to prove the code path; a CI test that forces each rung; a synthetic probe per rung that checks the degraded response is still correct.
| Signal | Why | Alert on |
|---|---|---|
| In flight per compartment | Saturation | Sustained near limit |
| Rejections per compartment | The bulkhead is working (or limit too small) | Rate and ratio |
| Wait time for a slot | Queueing | p99 above the bound |
| Current degradation level | What users see | Level above 0 for more than N minutes |
| Degraded responses per feature | Impact | Ratio of responses |
| Fallback hits and stale age | Hidden risk | Age above the maximum staleness |
Fix: metrics first (see Observability and Alerting); a test per rung; a quarterly game day; a runbook line "how to force level N and how to go back".
Mechanics
Exact numbers and formulas
| Quantity | Formula or value | Source |
|---|---|---|
| Concurrency | L = lambda x W | Little's law |
| Shuffle shards | C(n,k); C(8,2) = 28; C(2048,4) about 730 billion | AWS Builders' Library |
| Plain sharding blast radius | 1 / shards | AWS |
| Shuffle sharding blast radius | about 1 / C(n,k) | AWS |
| Resilience4j defaults | maxConcurrentCalls 25, maxWaitDuration 0 | Resilience4j docs |
| Envoy default | 1024 connections per cluster, enabled by default | Envoy docs |
| pgbouncer default pool | default_pool_size 20, reserve_pool_timeout 5.0 s | pgbouncer docs |
| PostgreSQL timeouts | statement_timeout, lock_timeout, idle_in_transaction_session_timeout: 0 = off | PostgreSQL docs |
Knobs
| Layer | Knob | Meaning |
|---|---|---|
| Go | semaphore.NewWeighted(n), Acquire(ctx, 1), TryAcquire(1), Release(1) | Weighted semaphore; Acquire blocks until slots or the context ends |
| Laravel | Cache::funnel($key)->limit($n)->releaseAfter($s)->block($s)->then($ok, $fail) | Cross-server concurrency limit; releaseAfter is a safety timeout; block how long to wait |
| Laravel | Cache::flexible($key, [$fresh, $stale], $cb) | Stale-while-revalidate with a deferred refresh |
| Laravel | php artisan queue:work --queue=critical,default | Worker drains critical fully before default |
| Laravel | Horizon supervisor, queue, balance (auto, simple, false), processes, minProcesses, maxProcesses, autoScalingStrategy (time, size, log) | Fleets per class |
| Laravel | php artisan down --refresh=15 --retry=60 --secret=... --render="errors::503" | Maintenance mode with a bypass; APP_MAINTENANCE_DRIVER=cache shares it across servers |
| Pennant | Feature::active, Feature::for($scope), before(), activateForEveryone, purge, EnsureFeaturesAreActive::using(...) | Flags |
| Kubernetes | resources.requests, resources.limits, priorityClassName, maxUnavailable, minAvailable, ResourceQuota | See platform table |
| Envoy | circuit_breakers.thresholds[].max_connections, max_pending_requests, max_requests, max_retries, track_remaining, priority | Per cluster and per priority |
| pgbouncer | pool_mode, max_client_conn, default_pool_size, reserve_pool_size, max_db_connections, max_user_connections | Pool compartments |
| PostgreSQL | ALTER ROLE ... CONNECTION LIMIT, ALTER ROLE ... SET statement_timeout | Per-role limits |
Error messages and signals you will see
| Where | Signal | Meaning |
|---|---|---|
| Envoy | x-envoy-overloaded header, HTTP 503; counters upstream_cx_overflow, upstream_rq_pending_overflow, upstream_rq_active_overflow, upstream_rq_retry_overflow, upstream_cx_pool_overflow | A circuit breaker threshold was hit |
| Laravel | Illuminate\Cache\Limiters\LimiterTimeoutException | Cache::funnel could not get a slot within block() |
| Laravel | Illuminate\Contracts\Cache\LockTimeoutException | Cache::lock(...)->block() timed out (lock, not funnel) |
| Laravel | HTTP 503 from HttpException | Maintenance mode |
| Resilience4j | BulkheadFullException | Semaphore bulkhead full |
| PostgreSQL | canceling statement due to statement timeout (SQLSTATE 57014) | statement_timeout fired |
| PostgreSQL | canceling statement due to lock timeout (SQLSTATE 55P03) | lock_timeout fired |
| PostgreSQL | FATAL: too many connections for role "svc_checkout" (SQLSTATE 53300) | CONNECTION LIMIT reached |
| Kubernetes | Eviction API answers 429 Too Many Requests | The eviction is not allowed now because of a PodDisruptionBudget |
| Kubernetes | Pod status OOMKilled | Memory limit exceeded |
| HTTP | 503 + Retry-After; 429 | Rejected (bulkhead, read-only, quota) |
Go
The module academy/bulkhead-graceful-degradation uses the standard library plus golang.org/x/sync/semaphore. Every package has tests; cmd/sim prints the numbers used in the lab.
Before
One shared pool, bounded wait. Twenty slow recommendation calls fill the pool and the 5 ms checkout call is rejected.
// Before: one shared pool for every dependency. A slow recommendations
// service holds every slot and the critical checkout call is starved.
package main
import (
"fmt"
"sync"
"time"
)
// sharedPool is a single bounded set of slots used by all dependencies.
type sharedPool struct{ slots chan struct{} }
func newSharedPool(n int) *sharedPool { return &sharedPool{slots: make(chan struct{}, n)} }
func (p *sharedPool) call(d time.Duration) bool {
select {
case p.slots <- struct{}{}:
defer func() { <-p.slots }()
time.Sleep(d)
return true
case <-time.After(50 * time.Millisecond):
return false // waited too long for a slot
}
}
func main() {
pool := newSharedPool(8)
var wg sync.WaitGroup
// 20 slow recommendation calls (400 ms each) arrive first.
for i := 0; i < 20; i++ {
wg.Add(1)
go func() { defer wg.Done(); pool.call(400 * time.Millisecond) }()
}
time.Sleep(20 * time.Millisecond)
// Checkout needs 5 ms but waits behind the slow calls.
ok := pool.call(5 * time.Millisecond)
fmt.Println("checkout served:", ok)
wg.Wait()
}After
A per-dependency bulkhead. Bulkhead.Do takes a slot with TryAcquire; if none is free it either rejects (maxWait 0) or waits a bounded time. Rejections and in-flight counts are metrics.
// Package bulkhead isolates one dependency behind a bounded number of
// concurrent calls (a semaphore) and a bounded wait.
package bulkhead
import (
"context"
"errors"
"sync/atomic"
"time"
"golang.org/x/sync/semaphore"
)
// ErrFull means the compartment has no free slot within the allowed wait.
var ErrFull = errors.New("bulkhead: compartment full")
// Bulkhead limits concurrent calls to one dependency.
type Bulkhead struct {
name string
sem *semaphore.Weighted
maxWait time.Duration // 0 = reject immediately (no queue)
rejected atomic.Int64
inflight atomic.Int64
}
// New returns a bulkhead with limit concurrent slots. maxWait is how long a
// caller may queue for a slot; zero means fail fast.
func New(name string, limit int64, maxWait time.Duration) *Bulkhead {
return &Bulkhead{name: name, sem: semaphore.NewWeighted(limit), maxWait: maxWait}
}
// Do runs fn inside the compartment or returns ErrFull.
func (b *Bulkhead) Do(ctx context.Context, fn func(context.Context) error) error {
if !b.sem.TryAcquire(1) {
if b.maxWait == 0 {
b.rejected.Add(1)
return ErrFull
}
wctx, cancel := context.WithTimeout(ctx, b.maxWait)
defer cancel()
if err := b.sem.Acquire(wctx, 1); err != nil {
b.rejected.Add(1)
return ErrFull
}
}
defer b.sem.Release(1)
b.inflight.Add(1)
defer b.inflight.Add(-1)
return fn(ctx)
}
// Name returns the dependency name used in metrics.
func (b *Bulkhead) Name() string { return b.name }
// Rejected counts calls turned away since start.
func (b *Bulkhead) Rejected() int64 { return b.rejected.Load() }
// InFlight reports calls currently holding a slot.
func (b *Bulkhead) InFlight() int64 { return b.inflight.Load() }A worker fleet with a bounded queue. Submit never blocks; a full queue returns ErrQueueFull.
// Package pool is a worker fleet with a bounded queue: a bulkhead made of
// goroutines. Submit never blocks; a full queue is rejected (shed).
package pool
import (
"errors"
"sync"
)
// ErrQueueFull is returned when the bounded queue has no room.
var ErrQueueFull = errors.New("pool: queue full")
// Pool runs jobs on a fixed number of workers.
type Pool struct {
jobs chan func()
wg sync.WaitGroup
once sync.Once
}
// New starts workers goroutines reading from a queue of size queue.
func New(workers, queue int) *Pool {
p := &Pool{jobs: make(chan func(), queue)}
p.wg.Add(workers)
for i := 0; i < workers; i++ {
go func() {
defer p.wg.Done()
for job := range p.jobs {
job()
}
}()
}
return p
}
// Submit enqueues job or returns ErrQueueFull immediately.
func (p *Pool) Submit(job func()) error {
select {
case p.jobs <- job:
return nil
default:
return ErrQueueFull
}
}
// Close stops accepting jobs and waits for the workers to drain the queue.
func (p *Pool) Close() {
p.once.Do(func() { close(p.jobs) })
p.wg.Wait()
}Sizing. Little's law as three functions with tests.
// Package sizing turns Little's law into bulkhead numbers.
package sizing
import "math"
// Slots returns the concurrency needed for an arrival rate (requests per
// second) at a mean latency (seconds): L = lambda * W, plus headroom
// (for example 0.3 for 30%), rounded up.
func Slots(ratePerSec, latencySec, headroom float64) int {
return int(math.Ceil(ratePerSec * latencySec * (1 + headroom)))
}
// MaxQueue returns how many waiters fit before the oldest one would wait
// longer than maxWaitSec when the compartment drains at throughput
// slots/latency per second.
func MaxQueue(slots int, latencySec, maxWaitSec float64) int {
throughput := float64(slots) / latencySec
return int(math.Floor(throughput * maxWaitSec))
}
// Throughput is the best-case requests per second a compartment can serve.
func Throughput(slots int, latencySec float64) float64 {
return float64(slots) / latencySec
}Shuffle sharding. A stable assignment of k of n workers per tenant, Combinations, Overlap and FullyAffected.
// Package shuffle assigns each tenant a stable "shuffle shard": k of n
// workers chosen pseudo-randomly from the tenant id. Two tenants rarely
// share all of their workers, so one bad tenant cannot take everyone down.
package shuffle
import (
"hash/fnv"
"math/rand/v2"
"sort"
)
// Shard returns k distinct worker indexes in [0,n) for the tenant.
func Shard(tenant string, n, k int) []int {
h := fnv.New64a()
h.Write([]byte(tenant))
r := rand.New(rand.NewPCG(h.Sum64(), 0x9e3779b97f4a7c15))
idx := make([]int, n)
for i := range idx {
idx[i] = i
}
for i := 0; i < k; i++ { // partial Fisher-Yates
j := i + r.IntN(n-i)
idx[i], idx[j] = idx[j], idx[i]
}
out := append([]int(nil), idx[:k]...)
sort.Ints(out)
return out
}
// Combinations is C(n,k): how many distinct shuffle shards exist.
func Combinations(n, k int) int {
if k > n {
return 0
}
c := 1
for i := 1; i <= k; i++ {
c = c * (n - k + i) / i
}
return c
}
// Overlap counts workers two shards share.
func Overlap(a, b []int) int {
seen := map[int]bool{}
for _, x := range a {
seen[x] = true
}
n := 0
for _, x := range b {
if seen[x] {
n++
}
}
return n
}
// FullyAffected returns the share of other tenants whose every worker is in
// the bad tenant's shard (those are the tenants that lose all capacity).
func FullyAffected(bad string, tenants []string, n, k int) float64 {
badShard := Shard(bad, n, k)
hit, total := 0, 0
for _, t := range tenants {
if t == bad {
continue
}
total++
if Overlap(badShard, Shard(t, n, k)) == k {
hit++
}
}
if total == 0 {
return 0
}
return float64(hit) / float64(total)
}The degradation controller. Levels, features with DisableAt, kill switches, a forced level, brownout by stable hash, hysteresis and minimum dwell; AllowWrites is the read-only gate.
// Package degrade is a degradation controller: a ladder of levels, feature
// flags that switch off in a fixed order, kill switches and brownout.
package degrade
import (
"hash/fnv"
"sync"
"time"
)
// Level is a rung of the degradation ladder (higher = more degraded).
type Level int
const (
Normal Level = iota // everything on
ShedOptional // optional, expensive features off
CachedOnly // reads served from cache or stale copies
ReadOnly // no writes accepted
StaticPage // static page only
never // sentinel: feature never switches off
)
func (l Level) String() string {
return [...]string{"normal", "shed-optional", "cached-only", "read-only", "static-page"}[l]
}
// Feature is switched off once the level reaches DisableAt.
type Feature struct {
Name string
DisableAt Level
Optional bool // optional features take part in brownout
}
// Critical declares a feature that survives every rung except the static page.
func Critical(name string) Feature { return Feature{Name: name, DisableAt: StaticPage} }
// Controller decides which features are on.
type Controller struct {
mu sync.Mutex
features map[string]Feature
level Level
forced *Level
killed map[string]bool
brownout float64
enter [4]float64 // utilisation needed to climb to level 1..4
hyst float64
minDwell time.Duration
changed time.Time
now func() time.Time
}
// New builds a controller. enter[i] is the load needed to reach level i+1;
// the level is left again when load drops hyst below that threshold.
func New(features []Feature, enter [4]float64, hyst float64, minDwell time.Duration) *Controller {
m := map[string]Feature{}
for _, f := range features {
m[f.Name] = f
}
return &Controller{features: m, killed: map[string]bool{}, enter: enter, hyst: hyst, minDwell: minDwell, now: time.Now}
}
// Observe feeds a load signal (for example in-flight / capacity). The level
// moves at most one rung per call, and never down before minDwell elapsed.
func (c *Controller) Observe(load float64) {
c.mu.Lock()
defer c.mu.Unlock()
if c.level < StaticPage && load >= c.enter[c.level] {
c.level++
c.changed = c.now()
return
}
if c.level > Normal && load < c.enter[c.level-1]-c.hyst && c.now().Sub(c.changed) >= c.minDwell {
c.level--
c.changed = c.now()
}
}
// Level returns the effective level (a forced level wins).
func (c *Controller) Level() Level {
c.mu.Lock()
defer c.mu.Unlock()
return c.effective()
}
func (c *Controller) effective() Level {
if c.forced != nil {
return *c.forced
}
return c.level
}
// Force pins the level (operator override); nil returns to automatic.
func (c *Controller) Force(l *Level) { c.mu.Lock(); c.forced = l; c.mu.Unlock() }
// Kill turns one feature off (or back on) regardless of the level.
func (c *Controller) Kill(name string, on bool) { c.mu.Lock(); c.killed[name] = on; c.mu.Unlock() }
// SetBrownout switches off the given share (0..1) of requests for optional
// features, chosen by a stable hash of key so a user does not flicker.
func (c *Controller) SetBrownout(share float64) { c.mu.Lock(); c.brownout = share; c.mu.Unlock() }
// Enabled reports whether the feature may run for this request key.
func (c *Controller) Enabled(name string, key string) bool {
c.mu.Lock()
defer c.mu.Unlock()
f, ok := c.features[name]
if !ok || c.killed[name] || c.effective() >= f.DisableAt {
return false
}
if f.Optional && c.brownout > 0 {
h := fnv.New32a()
h.Write([]byte(name + "|" + key))
return float64(h.Sum32()%1000)/1000 >= c.brownout
}
return true
}
// AllowWrites is the read-only gate used by write endpoints.
func (c *Controller) AllowWrites() bool { return c.Level() < ReadOnly }Stale-if-error cache.
package degrade
import (
"sync"
"time"
)
// Source says where a value came from.
type Source string
const (
Fresh Source = "fresh"
Stale Source = "stale"
)
type entry[V any] struct {
v V
fetched time.Time
}
// StaleCache serves a fresh value for ttl, then keeps serving the last good
// value for up to staleFor when the origin fails (stale-if-error).
type StaleCache[V any] struct {
mu sync.Mutex
items map[string]entry[V]
ttl time.Duration
staleFor time.Duration
now func() time.Time
}
// NewStaleCache returns an empty cache.
func NewStaleCache[V any](ttl, staleFor time.Duration) *StaleCache[V] {
return &StaleCache[V]{items: map[string]entry[V]{}, ttl: ttl, staleFor: staleFor, now: time.Now}
}
// Get returns a fresh value, or calls fetch; if fetch fails and a copy is
// younger than ttl+staleFor it returns that copy marked Stale.
func (c *StaleCache[V]) Get(key string, fetch func() (V, error)) (V, Source, error) {
c.mu.Lock()
e, ok := c.items[key]
c.mu.Unlock()
if ok && c.now().Sub(e.fetched) < c.ttl {
return e.v, Fresh, nil
}
v, err := fetch()
if err == nil {
c.mu.Lock()
c.items[key] = entry[V]{v: v, fetched: c.now()}
c.mu.Unlock()
return v, Fresh, nil
}
if ok && c.now().Sub(e.fetched) < c.ttl+c.staleFor {
return e.v, Stale, nil
}
var zero V
return zero, "", err
}The simulation used in the lab, and one test showing the ladder order and the hysteresis.
// Command sim runs the same overload against one shared pool and against
// per-dependency bulkheads, using real goroutines and short sleeps.
package main
import (
"context"
"fmt"
"sync"
"sync/atomic"
"time"
"academy/bulkhead-graceful-degradation/bulkhead"
)
type result struct{ ok, rejected atomic.Int64 }
// run sends checkout calls (5 ms) while the recommendations dependency is
// stuck (every call takes 300 ms).
func run(shared bool) (critical, recs *result) {
critical, recs = &result{}, &result{}
var bCrit, bRecs *bulkhead.Bulkhead
if shared {
one := bulkhead.New("shared", 8, 40*time.Millisecond)
bCrit, bRecs = one, one
} else {
bCrit = bulkhead.New("critical", 4, 40*time.Millisecond)
bRecs = bulkhead.New("recs", 4, 0)
}
var wg sync.WaitGroup
call := func(b *bulkhead.Bulkhead, d time.Duration, r *result) {
defer wg.Done()
err := b.Do(context.Background(), func(context.Context) error { time.Sleep(d); return nil })
if err != nil {
r.rejected.Add(1)
return
}
r.ok.Add(1)
}
for i := 0; i < 40; i++ { // slow recommendations first
wg.Add(1)
go call(bRecs, 300*time.Millisecond, recs)
}
time.Sleep(10 * time.Millisecond)
for i := 0; i < 40; i++ { // then checkout traffic
wg.Add(1)
go call(bCrit, 5*time.Millisecond, critical)
time.Sleep(2 * time.Millisecond)
}
wg.Wait()
return
}
func main() {
for _, shared := range []bool{true, false} {
c, r := run(shared)
name := "per-dependency bulkheads"
if shared {
name = "one shared pool"
}
fmt.Printf("%-26s critical ok=%2d rejected=%2d | recs ok=%2d rejected=%2d\n",
name, c.ok.Load(), c.rejected.Load(), r.ok.Load(), r.rejected.Load())
}
}package degrade
import (
"errors"
"fmt"
"testing"
"time"
)
func newTestController() (*Controller, *time.Time) {
t := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC)
c := New([]Feature{
{Name: "recommendations", DisableAt: ShedOptional, Optional: true},
{Name: "reviews", DisableAt: CachedOnly, Optional: true},
Critical("checkout"),
}, [4]float64{0.7, 0.85, 0.95, 1.1}, 0.1, 30*time.Second)
c.now = func() time.Time { return t }
return c, &t
}
func TestLadderSwitchesExpensiveFeaturesFirst(t *testing.T) {
c, _ := newTestController()
if !c.Enabled("recommendations", "u1") || !c.Enabled("checkout", "u1") {
t.Fatal("everything is on at normal")
}
c.Observe(0.75) // -> shed-optional
if c.Enabled("recommendations", "u1") || !c.Enabled("reviews", "u1") || !c.Enabled("checkout", "u1") {
t.Fatalf("level %v: only recommendations should be off", c.Level())
}
c.Observe(0.9) // -> cached-only
if c.Enabled("reviews", "u1") || !c.Enabled("checkout", "u1") {
t.Fatal("reviews off, checkout still on")
}
c.Observe(1.0) // -> read-only
if c.AllowWrites() || !c.Enabled("checkout", "u1") {
t.Fatal("read-only blocks writes through AllowWrites; checkout flag itself stays")
}
c.Observe(1.2) // -> static page
if c.Enabled("checkout", "u1") {
t.Fatal("static page switches even critical features off")
}
}
func TestHysteresisAndDwell(t *testing.T) {
c, now := newTestController()
c.Observe(0.75)
c.Observe(0.65) // below enter but within hysteresis band (0.7-0.1=0.6)
if c.Level() != ShedOptional {
t.Fatalf("level %v, want shed-optional (inside hysteresis band)", c.Level())
}
c.Observe(0.3) // low enough but dwell not elapsed
if c.Level() != ShedOptional {
t.Fatal("must not recover before minDwell")
}
*now = now.Add(31 * time.Second)
c.Observe(0.3)
if c.Level() != Normal {
t.Fatalf("level %v, want normal after dwell", c.Level())
}
}
func TestKillSwitchAndForce(t *testing.T) {
c, _ := newTestController()
c.Kill("reviews", true)
if c.Enabled("reviews", "u") {
t.Fatal("killed feature must be off at level normal")
}
c.Kill("reviews", false)
l := ReadOnly
c.Force(&l)
if c.AllowWrites() {
t.Fatal("forced read-only must block writes")
}
c.Force(nil)
if !c.AllowWrites() {
t.Fatal("automatic mode restored")
}
}
func TestBrownoutShareIsStableAndApproximate(t *testing.T) {
c, _ := newTestController()
c.SetBrownout(0.25)
off := 0
for i := 0; i < 10000; i++ {
k := fmt.Sprintf("user-%d", i)
a := c.Enabled("reviews", k)
if a != c.Enabled("reviews", k) {
t.Fatal("same key must get the same answer")
}
if !a {
off++
}
if !c.Enabled("checkout", k) {
t.Fatal("critical features never join a brownout")
}
}
if off < 2200 || off > 2800 {
t.Fatalf("browned out %d of 10000, want about 2500", off)
}
}
func TestStaleIfError(t *testing.T) {
c := NewStaleCache[string](time.Minute, 10*time.Minute)
now := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC)
c.now = func() time.Time { return now }
if v, s, err := c.Get("p1", func() (string, error) { return "v1", nil }); v != "v1" || s != Fresh || err != nil {
t.Fatal("first fetch should be fresh")
}
now = now.Add(5 * time.Minute)
boom := func() (string, error) { return "", errors.New("origin down") }
if v, s, err := c.Get("p1", boom); v != "v1" || s != Stale || err != nil {
t.Fatalf("got %q %q %v, want stale v1", v, s, err)
}
now = now.Add(time.Hour)
if _, _, err := c.Get("p1", boom); err == nil {
t.Fatal("beyond the stale window the error must surface")
}
}The Go angle
golang.org/x/sync/semaphoreprovidesNewWeighted,Acquire(ctx, n),TryAcquire(n)andRelease(n); its documented purpose is to "bound concurrent access to a resource", which is exactly a bulkhead. A buffered channel does the same for n = 1 per slot.- Always pass the request
contexttoAcquire; a cancelled client must give up its place in the queue. net/httphas no per-host concurrency cap by default;Transport.MaxConnsPerHostcaps connections per host and is the lightweight bulkhead for HTTP/1.1.database/sqlhasSetMaxOpenConnsandSetMaxIdleConnsper*sql.DB: use one*sql.DBper service role, not one for all.- Release in
defer, and release exactly what you acquired; a leaked slot is a permanent loss of capacity. - Expose
InFlightandRejectedto your metrics library; the bulkhead is only useful if you can see it full. - Run
go test -raceon anything with a mutex; the controller and cache are guarded by one.
Laravel
Laravel 13 has no thread pools; its bulkheads are queues, Horizon supervisors, Cache::funnel (a cross-server concurrency limit), and the framework's maintenance mode. Features are managed with Laravel Pennant.
Before
Everything on the default queue.
<?php
namespace App\Before;
use App\Jobs\ChargeCard;
use App\Jobs\BuildRecommendations;
// Before: every job lands on the same "default" queue, served by one worker
// fleet. A backlog of slow BuildRecommendations jobs delays ChargeCard.
class DefaultQueueBefore
{
public function checkout(int $orderId): void
{
ChargeCard::dispatch($orderId); // critical
BuildRecommendations::dispatch($orderId); // optional, slow
}
}After
Separate queues, one per class. Jobs choose their queue in the constructor.
<?php
namespace App\Jobs;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
class ChargeCard implements ShouldQueue
{
use Queueable;
public int $tries = 5;
public int $timeout = 20;
public function __construct(public int $orderId)
{
// Own queue: its own workers, its own backlog.
$this->onQueue('critical');
}
public function handle(): void
{
// Call the payment provider here.
}
}<?php
namespace App\Jobs;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Support\Facades\Cache;
class BuildRecommendations implements ShouldQueue
{
use Queueable;
public int $tries = 2;
public int $timeout = 120;
public function __construct(public int $userId)
{
$this->onQueue('low');
}
public function handle(): void
{
// At most 3 of these run at once across all workers and servers.
Cache::funnel('recs-builder')
->limit(3)
->releaseAfter(150)
->block(0)
->then(
fn () => $this->build(),
fn () => $this->release(30), // no slot: try again later
);
}
private function build(): void
{
// Expensive model call here.
}
}Horizon supervisors: one fleet per class. critical has a fixed 4 processes (simple balance), low a fixed 3, default auto-scales up to 10. In Laravel's own words, "each supervisor is essentially responsible for 'supervising' a group of worker processes", and you can add more "if you would like to define a different balancing strategy or worker process count for a given queue".
<?php
// Excerpt of config/horizon.php: one supervisor (one compartment) per job class.
return [
'environments' => [
'production' => [
'supervisor-critical' => [
'connection' => 'redis',
'queue' => ['critical'],
'balance' => 'simple',
'processes' => 4, // fixed: always reserved for payments
'tries' => 5,
'timeout' => 20,
],
'supervisor-default' => [
'connection' => 'redis',
'queue' => ['default'],
'balance' => 'auto',
'autoScalingStrategy' => 'time',
'minProcesses' => 1,
'maxProcesses' => 10, // upper bound for the auto strategy
'balanceMaxShift' => 1,
'balanceCooldown' => 3,
'tries' => 3,
'timeout' => 60,
],
'supervisor-low' => [
'connection' => 'redis',
'queue' => ['low'],
'balance' => 'simple',
'processes' => 3, // slow jobs can never take more than 3 processes
'tries' => 2,
'timeout' => 120,
],
],
],
];Without Horizon, run separate php artisan queue:work --queue=critical and php artisan queue:work --queue=low under Supervisor, systemd or separate Kubernetes Deployments. The documented comma-separated form, php artisan queue:work --queue=high,default, drains high first within a single worker: a priority queue, with the starvation trade-off above.
The current level, shared by the fleet.
<?php
namespace App\Support;
use Illuminate\Support\Facades\Cache;
/**
* The current degradation level, shared by every server through the cache.
* 0 normal, 1 shed optional, 2 cached only, 3 read only, 4 static page.
*/
class Degradation
{
public const NORMAL = 0;
public const SHED_OPTIONAL = 1;
public const CACHED_ONLY = 2;
public const READ_ONLY = 3;
public const STATIC_PAGE = 4;
public static function level(): int
{
return (int) Cache::get('degradation.level', self::NORMAL);
}
public static function set(int $level): void
{
Cache::forever('degradation.level', max(0, min(4, $level)));
}
public static function readOnly(): bool
{
return self::level() >= self::READ_ONLY;
}
}Features that switch off by level. Pennant stores the resolved value per scope ("the next time the feature is checked against the same user, the value will be retrieved from storage and the closure will not be invoked"), so a degradation level must not be read in resolve(). A class-based feature's before() runs "always ... in-memory before retrieving the value from storage" and wins when it returns non-null.
<?php
namespace App\Features;
use App\Support\Degradation;
/**
* Optional and expensive: the first feature to switch off.
*
* Pennant stores the resolved value per scope, so a level read inside
* resolve() would be frozen after the first check. before() runs in memory
* on every check and wins whenever it returns a non-null value.
*/
class Recommendations
{
public function before(mixed $scope = null): ?bool
{
// The Pennant docs' own pattern: only act when degraded, else fall through.
return Degradation::level() >= Degradation::SHED_OPTIONAL ? false : null;
}
public function resolve(mixed $scope = null): bool
{
return true; // normal state: on for everybody
}
}<?php
namespace App\Features;
use App\Support\Degradation;
/** Second rung: switched off when the system is cached-only. */
class Reviews
{
public function before(mixed $scope = null): ?bool
{
return Degradation::level() >= Degradation::CACHED_ONLY ? false : null;
}
public function resolve(mixed $scope = null): bool
{
return true;
}
}Product page: stale cache, a bulkhead and a partial result.
<?php
namespace App\Http\Controllers;
use App\Features\Recommendations;
use App\Support\Degradation;
use Illuminate\Cache\Limiters\LimiterTimeoutException;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;
use Laravel\Pennant\Feature;
class ProductController extends Controller
{
public function show(int $id)
{
// Critical path: product data. Fresh for 30 s, servable as stale for 5 min.
$product = Cache::flexible("product:$id", [30, 300], fn () => $this->loadProduct($id));
$recommendations = [];
if (Feature::active(Recommendations::class)) {
$recommendations = $this->recommendations($id);
}
return response()->json([
'product' => $product,
'recommendations' => $recommendations,
'degraded' => Degradation::level() > Degradation::NORMAL,
]);
}
private function recommendations(int $id): array
{
$items = [];
try {
// Bulkhead: at most 5 concurrent calls to the recommendations service
// per cache store; do not wait for a slot (block 0 = fail fast).
Cache::funnel('dep:recommendations')
->limit(5)
->releaseAfter(5)
->block(0)
->then(function () use ($id, &$items) {
$r = Http::connectTimeout(0.2)->timeout(0.5)
->get("https://recs.internal.example/v1/similar/$id");
$items = $r->successful() ? $r->json('items', []) : [];
});
return $items;
} catch (LimiterTimeoutException) {
return []; // compartment full: partial result, no recommendations
} catch (\Throwable) {
return Cache::get("recs:last-good:$id", []); // stale fallback
}
}
private function loadProduct(int $id): array
{
return ['id' => $id, 'name' => 'Example product'];
}
}Read-only mode as middleware, the operator command, routing and registration.
<?php
namespace App\Http\Middleware;
use App\Support\Degradation;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
class ReadOnlyMode
{
public function handle(Request $request, Closure $next): Response
{
if (Degradation::readOnly() && ! $request->isMethodSafe()) {
return response()->json(
['error' => 'read_only', 'message' => 'Writes are paused. Reads still work.'],
503,
['Retry-After' => '60'],
);
}
return $next($request);
}
}<?php
namespace App\Console\Commands;
use App\Support\Degradation;
use Illuminate\Console\Command;
class SetDegradationLevel extends Command
{
protected $signature = 'degrade:set {level : 0 normal, 1 shed, 2 cached, 3 read-only, 4 static}';
protected $description = 'Move the whole fleet to a degradation level';
public function handle(): int
{
Degradation::set((int) $this->argument('level'));
$this->info('level = '.Degradation::level());
return self::SUCCESS;
}
}<?php
use App\Http\Controllers\ProductController;
use App\Features\Reviews;
use Illuminate\Support\Facades\Route;
use Laravel\Pennant\Middleware\EnsureFeaturesAreActive;
Route::get('/products/{id}', [ProductController::class, 'show']);
// Whole route disappears (400 by default) when the feature is off.
Route::get('/reviews/{id}', fn (int $id) => ['reviews' => []])
->middleware(EnsureFeaturesAreActive::using(Reviews::class));<?php
use App\Http\Middleware\ReadOnlyMode;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Middleware;
// Excerpt of bootstrap/app.php (Laravel 13 application builder).
return Application::configure(basePath: dirname(__DIR__))
->withMiddleware(function (Middleware $middleware) {
// Runs for every web and API request.
$middleware->append(ReadOnlyMode::class);
})
->create();<?php
namespace Tests\Feature;
use App\Support\Degradation;
use Illuminate\Support\Facades\Cache;
use Tests\TestCase;
class ReadOnlyModeTest extends TestCase
{
public function test_writes_are_refused_but_reads_work_in_read_only_mode(): void
{
Cache::forever('degradation.level', Degradation::READ_ONLY);
$this->postJson('/orders', ['sku' => 'a'])
->assertStatus(503)
->assertHeader('Retry-After', '60')
->assertJson(['error' => 'read_only']);
$this->getJson('/products/1')->assertOk()->assertJson(['degraded' => true]);
}
}The Laravel angle
- Multiple queues. The docs: pushing jobs to multiple queues "can be especially useful for applications that wish to prioritize or segment how jobs are processed".
onQueue('emails')selects the queue;--queue=high,defaultsets priority order. - Horizon. Three balancing strategies,
auto,simpleandfalse;auto"does not enforce strict priority between queues", so for a hard wall use a separate supervisor. While the application is in maintenance mode Horizon does not process jobs unless the supervisor'sforceoption is true. Cache::funnel"works with any cache driver that supports locks"; withblock(0)it fails fast (rejection), withblock(10)it queues for up to 10 s. It needs a shared store (Redis) to be a fleet-wide bulkhead; with a per-server store it is per server.Cache::flexibleimplements stale-while-revalidate: within the first value fresh; within the second stale and refreshed by a deferred function after the response; after that recomputed.- Maintenance mode.
php artisan down(optionally--retry=60,--refresh=15,--secret=...,--render="errors::503"); the default file-based check needs the command on every server;APP_MAINTENANCE_DRIVER=cachewith a sharedAPP_MAINTENANCE_STOREneeds it on one. Pre-render the view so errors do not appear while dependencies update. - Pennant.
Feature::active,Feature::for($scope),Feature::activateForEveryone, and theEnsureFeaturesAreActiveroute middleware; for a kill switch usebefore()ordeactivateForEveryone. - Octane: static state is shared across requests in a worker; keep counters in the cache store, not static properties, or limits are per worker and never reset.
- SQL for the database half (roles and connection limits):
-- One role per service, each with its own ceiling and timeouts.
CREATE ROLE svc_checkout LOGIN CONNECTION LIMIT 40;
ALTER ROLE svc_checkout SET statement_timeout = '2s';
ALTER ROLE svc_checkout SET idle_in_transaction_session_timeout = '5s';-- One role per service; each gets its own connection ceiling and timeouts.
CREATE ROLE svc_checkout LOGIN CONNECTION LIMIT 40;
CREATE ROLE svc_reports LOGIN CONNECTION LIMIT 5;
ALTER ROLE svc_checkout SET statement_timeout = '2s';
ALTER ROLE svc_checkout SET idle_in_transaction_session_timeout = '5s';
ALTER ROLE svc_checkout SET lock_timeout = '1s';
-- Reports are slow by nature; give them time, but cap them hard, and point them
-- at the analytics replica in pgbouncer.ini (host 192.0.2.11).
ALTER ROLE svc_reports SET statement_timeout = '60s';
ALTER ROLE svc_reports SET idle_in_transaction_session_timeout = '30s';
-- Who is using the connections right now?
SELECT usename, count(*) AS connections, count(*) FILTER (WHERE state = 'active') AS active
FROM pg_stat_activity
WHERE backend_type = 'client backend'
GROUP BY usename
ORDER BY connections DESC;; One pool per (database, user) pair: each service gets its own compartment.
[databases]
shop_checkout = host=192.0.2.10 port=5432 dbname=shop pool_size=30
shop_reports = host=192.0.2.11 port=5432 dbname=shop pool_size=5 ; analytics replica
[pgbouncer]
listen_port = 6432
pool_mode = transaction
max_client_conn = 2000
default_pool_size = 20
reserve_pool_size = 5
reserve_pool_timeout = 3
max_db_connections = 40
max_user_connections = 40# Envoy cluster for the recommendations dependency: its own thresholds.
clusters:
- name: recommendations
connect_timeout: 0.25s
type: STRICT_DNS
lb_policy: ROUND_ROBIN
circuit_breakers:
thresholds:
- priority: DEFAULT
max_connections: 50 # connections to all hosts of the cluster
max_pending_requests: 20 # queued while waiting for a connection
max_requests: 100 # outstanding requests to the cluster
max_retries: 3 # concurrent retries
track_remaining: true # export remaining_* gauges
- priority: HIGH
max_connections: 200
max_pending_requests: 100
max_requests: 400
max_retries: 3
load_assignment:
cluster_name: recommendations
endpoints:
- lb_endpoints:
- endpoint:
address:
socket_address: {address: recs.internal.example, port_value: 8080}Solving the classic problems
"One slow dependency freezes the whole service"
| Solution | How | Advantage | Cost or limit |
|---|---|---|---|
| Per-dependency semaphore | Bulkhead.Do with a slot count from Little's law | Cheap, local | Per instance, not fleet-wide |
| Timeout plus bulkhead | Deadline per call (Timeouts) | Slots come back | Needs sensible timeouts |
| Circuit breaker on top | Open after repeated slow calls | Stops sending | Needs tuning |
| Envoy cluster limits | max_pending_requests, max_requests | Language-independent | Coarser |
"A report query took the OLTP database down"
Give reports their own role (CONNECTION LIMIT, statement_timeout), their own pgbouncer pool with a small pool_size, and an analytics replica. The OLTP pool then cannot be drained by reports; the cost is replica lag for reports.
"A bulk import starves every other tenant"
Per-tenant concurrency limit and queue share; a separate queue and fleet for imports; shuffle shards for the worker pool; cells when the whole stack must be isolated.
"The job queue is full of low-priority work"
Separate queues and Horizon supervisors per class; queue:work --queue=critical,default when one fleet is acceptable; bound the low queue and shed or delay when it is full.
"Maintenance deploys look like an outage"
php artisan down --render="errors::503" --retry=60 --secret=..., or better, a read-only rung that keeps browsing alive and returns 503 + Retry-After for writes.
"Our fallback made it worse"
Treat the fallback as its own dependency: its own bulkhead, its own timeout, its own metric; prefer omit/default/stale; delete fallbacks you cannot test. AWS's listed alternatives are to improve the reliability of the non-fallback case, to let the caller handle errors, to push data proactively, and to convert fallback into failover so the second path runs all the time.
"The ladder flaps"
Add hysteresis (exit threshold lower than entry), a minimum dwell, one rung per signal, and a manual override.
Anti-patterns
| Anti-pattern | Why it hurts | Instead |
|---|---|---|
| One shared pool for everything | Slowest dependency wins | One compartment per dependency |
| Synchronous dependency on a non-critical feature | Optional feature can fail the critical path | Optional call with timeout, bulkhead and default |
| Unbounded queue | Latency grows without bound | Bounded queue, reject or shed |
| Degradation never exercised | Code path rots | Game days, canary pinned to a level |
| Kill switch behind the broken dependency | Cannot be flipped in an incident | Local or highly available flag store |
| Pools sized from average latency | Collapse at the first spike | Size for the promised latency plus headroom |
| Per-instance limits with no fleet cap | N instances multiply the load on the dependency | Divide by instances or use Envoy or Cache::funnel |
| Same worker fleet for all classes | Shared fate | Separate fleets |
Choosing
Which isolation
| Situation | Recommendation | Extra technique | Reason |
|---|---|---|---|
| Few outbound dependencies, one language | In-process semaphore per dependency | Timeout, circuit breaker | Cheapest and local |
| Many languages | Envoy cluster thresholds | Retry budget | One mechanism for all |
| Slow batch beside latency-critical code | Separate queue and fleet, node pool | PriorityClass | Hard wall |
| Many tenants on one pool | Per-tenant limit, then shuffle sharding | Retrying clients | Smaller blast radius |
| Must contain a bad deploy or corruption | Cells | Cell router | Whole-stack isolation |
| Analytics beside OLTP | Analytics replica, separate role and pool | statement_timeout | Protect the primary |
Which degradation
| Situation | Recommendation | Reason |
|---|---|---|
| Optional feature's dependency is slow or down | Omit or default behind a flag | Cheapest, safest |
| Origin down but data tolerates age | Stale cache with a maximum age | Keeps pages alive |
| Overload from traffic | Brownout then ladder; shed per Load Shedding | Proportional response |
| Database failover or migration | Read-only mode | Keeps reads and trust |
| Total loss of dynamic tier | Static page from CDN | Last resort |
| Planned work | Maintenance mode with bypass | Announced, controlled |
In architecture: from a single process to a distributed system
Monolith: one process, one database
A Laravel monolith has one database pool, one queue fleet and one PHP-FPM pool. The simplest correct use: three queues (critical, default, low) with their own workers, a statement_timeout on the web role, a Cache::flexible for hot reads, and php artisan down --secret for planned work. The first bulkhead is almost free: separate the queue that holds email and exports from the queue that charges cards.
Modular monolith: boundaries without the network
Modules still share a process and database, so the compartments are internal: one semaphore per module's outbound integration, one role and pool per module if they have separate schemas, and one queue per module. The module boundary decides the bulkhead boundary. A feature flag per module lets you switch an optional module off without a deploy.
Microservices: every call needs a wall
Each service gets per-dependency bulkheads in code or in Envoy (see Service Mesh for the sidecar), its own database role and pgbouncer pool, its own Kubernetes namespace quota and PriorityClass, and a ladder that its callers understand: a 503 with Retry-After and a header that says X-Degraded. Contract: a caller must treat an optional dependency's failure as normal and a critical one as a degrade-or-fail decision, not a hang (Service Communication).
Distributed data: replicas, caches, regions
Replicas are bulkheads for reads: analytics on a replica protects the primary, at the price of lag. A cache failing is a shared-fate event: when it dies every read goes to the database, so put a bulkhead and rate limit on the fallback path and keep stale copies. In multi-region setups a region is a cell: route users to one region, keep other regions static-stable, and degrade to read-only when the primary region is lost (Replication, Capacity Planning & DR).
Scaling path: 1x, 10x, 100x
| Scale | Isolation | Degradation |
|---|---|---|
| 1x: one app, one database | Separate queues, statement_timeout, role limits | Maintenance mode, Cache::flexible |
| 10x: several services | Semaphore per dependency, pgbouncer per service, node pools, PDBs | Flags and kill switches, stale caches, read-only middleware |
| 100x: many tenants, regions | Per-tenant limits, shuffle sharding, Envoy thresholds, quotas | A controller-driven ladder, brownout, game days |
| 1000x: platform | Cells with a router, regional stacks | Static-stable regions, QoS tiers, automated drills |
Lab: a shared pool vs bulkheads, and the ladder, with real numbers
All Go steps below were run on the author's machine; the platform steps are expected, not run (no Kubernetes, Envoy, pgbouncer, PostgreSQL or Laravel app was started).
# 1) Unit tests
cd docs/snippets/system-design/bulkhead-graceful-degradation/go
go vet ./... && go test -count=1 ./...
# ok academy/bulkhead-graceful-degradation/bulkhead
# ok academy/bulkhead-graceful-degradation/degrade
# ok academy/bulkhead-graceful-degradation/pool
# ok academy/bulkhead-graceful-degradation/shuffle
# ok academy/bulkhead-graceful-degradation/sizing
# 2) The slow-dependency simulation: 40 recs calls of 300 ms, then 40 checkout calls of 5 ms
go run ./cmd/sim
# one shared pool critical ok= 0 rejected=40 | recs ok= 8 rejected=32
# per-dependency bulkheads critical ok=40 rejected= 0 | recs ok= 4 rejected=36
# 3) The "before" program
go run ./before
# checkout served: falseReading the output: with one pool of eight slots, the 40 recommendation calls hold every slot for 300 ms, so every checkout call (waiting at most 40 ms) is rejected. With 4 + 4 slots, recommendations are rejected immediately (the compartment is full) and every checkout call is served. The total number of slots and the traffic are the same; only the partitioning changed.
# 4) Expected, not run: Envoy overflow counters (admin interface, port 9901)
curl -s localhost:9901/stats | grep 'cluster.recommendations.upstream_rq_pending_overflow'
# cluster.recommendations.upstream_rq_pending_overflow: 0 (rises once the limit is hit)
# 5) Expected, not run: pgbouncer pools
psql -h 127.0.0.1 -p 6432 pgbouncer -c 'SHOW POOLS;'
# database | user | cl_active | cl_waiting | sv_active | sv_idle ...
# shop_checkout | ... | 18 | 0 | 18 | 4
# shop_reports | ... | 5 | 12 | 5 | 0 (reports wait; checkout unaffected)
# 6) Expected, not run: Laravel
php artisan degrade:set 3
curl -i -X POST localhost:8000/orders -d 'sku=a'
# HTTP/1.1 503 Service Unavailable
# Retry-After: 60
curl -s localhost:8000/products/1
# {"product":{"id":1,...},"recommendations":[],"degraded":true}
php artisan degrade:set 0Common misconceptions
| Belief | Reality |
|---|---|
| "Goroutines are cheap, so no bulkhead needed" | What they hold (connections, memory, downstream capacity) is not cheap |
| "A circuit breaker replaces a bulkhead" | The breaker stops calls after failure; the bulkhead limits damage before and during |
| "Bigger pools are safer" | A bigger shared pool is emptied by the same slow call, later |
| "Unbounded queues never lose work" | They turn overload into unbounded latency and memory |
| "Per-tenant rate limits are isolation" | Rate is not cost; limit concurrency and blast radius too |
| "A CPU limit protects neighbours" | Requests protect neighbours; limits throttle yourself |
| "A fallback is always safer than failing" | Untested fallbacks fail, and can overload the thing they fall back to |
| "Stale data is always fine" | Stale is fine when bounded per field and never for money-moving decisions |
| "Maintenance mode is degradation" | It is announced, binary and global; degradation is partial and automatic |
| "Feature flags are only for launches" | Kill switches are the operational use, and must not depend on the failing system |
| "One degraded flag is enough" | A ladder gives proportional responses and testable rungs |
| "If it never triggers it works" | Untriggered code paths rot; exercise them |
Cheat sheet
| Topic | What to remember |
|---|---|
| Bulkhead | Fixed slice per dependency, tenant or class; limit plus defined behaviour at the limit |
| Semaphore | Go semaphore.NewWeighted; TryAcquire rejects, Acquire(ctx) waits |
| Queue | Bound it; reject or shed at the bound |
| Sizing | slots = rate x latency x (1 + headroom); queue = throughput x tolerable wait |
| Per instance vs fleet | Multiply by instances, or limit at Envoy or Cache::funnel |
| Tenants | Per-tenant concurrency, then shuffle sharding, then cells |
| Shuffle sharding | C(n,k) shards; 8 choose 2 = 28, so 1/28 of the impact |
| Kubernetes | requests and limits, ResourceQuota, PriorityClass, PDB, node pool |
| Envoy | max_connections, max_pending_requests, max_requests, max_retries |
| pgbouncer | One pool per service; pool_size, max_db_connections, pool_mode |
| PostgreSQL | Role CONNECTION LIMIT, statement_timeout, analytics replica |
| Laravel queues | queue:work --queue=critical,default, Horizon supervisor per class |
| Degradation | Omit, default, stale, partial, cheaper, read-only, static |
| Ladder | Ordered rungs, entry and exit signals, hysteresis, dwell, override |
| Kill switch | Off-switch not behind the failing dependency |
| Testing | A test per rung, a game day, a canary pinned to a level |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — A service has one pool of 100 goroutines for three dependencies. One dependency goes from 20 ms to 10 s. Explain what happens to the other two. Must-know
Answer
Answer: By Little's law the slow dependency needs 500x more slots for the same traffic. It takes all 100 slots, so calls to the other two wait for a slot and time out even though their dependencies are healthy. The fix is one compartment per dependency.
2 — Size a compartment for 200 req/s at 50 ms mean latency with 30% headroom, and give the queue bound for 100 ms of tolerated wait. Important
Answer
Answer: Slots = 200 x 0.05 x 1.3 = 13. Capacity = 13 / 0.05 = 260 req/s. Queue bound = 260 x 0.1 = 26.
3 — When is rejecting at the limit better than queueing, and when is a short bounded wait better? Must-know
Answer
Answer: Reject for interactive requests with tight deadlines and when the caller has a cheap degraded path. Wait a bounded time for short bursts against fast dependencies. Never an unbounded queue for interactive work.
4 — With eight workers and two per tenant, how many shuffle shards exist, and what share of other tenants can a bad tenant fully disable? Good to know
Answer
Answer: C(8,2) = 28 shards, so about 1/28 (3.6%) of tenants share both workers, against 1/4 with four plain shards.
5 — What do max_connections and max_pending_requests do in an Envoy cluster? Important
Answer
Answer: max_connections caps connections to all hosts of the upstream cluster; max_pending_requests caps requests queued waiting for a ready connection. Overflow increments upstream_cx_overflow or upstream_rq_pending_overflow and the router sets x-envoy-overloaded.
6 — Why does a Pennant feature that reads the degradation level in resolve() not switch off when the level changes, and how do you fix it? Good to know
Answer
Answer: Pennant stores the resolved value per scope, so the closure runs once. Use a class-based feature's before(), which runs in memory on every check, or deactivateForEveryone for a kill switch.
7 — What is the difference between Cache::flexible('k', [30, 300], ...) and Cache::remember? Important
Answer
Answer: remember recomputes on expiry; flexible serves a stale value between the fresh and stale times and refreshes it after the response, so users do not wait.
8 — Why does a degradation ladder need hysteresis and a minimum dwell? Important
Answer
Answer: Without them, load hovering near a threshold makes the controller flap between rungs, and each switch changes load again. Exit thresholds below entry thresholds and a dwell time damp it.
9 — Name three things a game day for the recommendations dependency must verify. Important
Answer
Answer: The bulkhead rejects instead of queueing, the ladder reaches the right rung within the target time, the critical path (checkout) keeps its success rate and p99; also the alert fires and the system returns to normal after the fault is removed.
10 — Why might a fallback to the database when the cache fails make an incident worse? Must-know
Answer
Answer: All traffic suddenly hits the database (a stampede) and the fallback is rarely exercised. Protect it with its own bulkhead and rate limit, coalesce requests and keep stale copies.
11 — How do php artisan queue:work --queue=high,default and two Horizon supervisors differ? Important
Answer
Answer: The first is one fleet that drains high before default (priority, starvation possible, shared fate). Two supervisors are separate fleets with fixed process counts, a real bulkhead.
12 — What does a PodDisruptionBudget protect, and what does it not? Important
Answer
Answer: It limits voluntary disruptions such as node drains (minAvailable/maxUnavailable). It does not stop crashes, OOM kills or node failures.
Glossary
| Term | Meaning |
|---|---|
| Bulkhead | A hard limit on the share of a resource one dependency, tenant or class may use |
| Isolation | Keeping one component's failure from reaching another |
| Resource pool | Fixed set of reusable workers or connections |
| Thread pool | Dedicated threads for one dependency's calls |
| Connection pool | Cap on open connections to one server |
| Semaphore | Counter of free slots |
| Bounded queue | Queue with a fixed length; excess is rejected |
| Separate queue | A queue per job class |
| Worker fleet | The processes serving a queue |
| Priority queue | Queue served in class order; may starve low classes |
| Rejection | An immediate refusal (503, 429) |
| Queueing | Delaying work until capacity is free |
| Little's law | L = lambda x W |
| Headroom | Extra slots over the computed minimum |
| Per-tenant limit | Rate, concurrency or queue share per customer |
| Cell-based architecture | Many independent full copies of a service, each serving a subset |
| Cell router | The thin layer that maps a tenant to a cell |
| Shuffle sharding | Assign each tenant k of n workers pseudo-randomly |
| requests and limits | Kubernetes container reservation and ceiling |
| ResourceQuota | Namespace-wide cap on resources |
| namespace | Kubernetes scope for names and quotas |
| PriorityClass | Scheduling and preemption order for pods |
| PodDisruptionBudget | Limit on voluntary pod evictions |
| node pool | A group of nodes with the same shape or labels |
| Envoy circuit breaker thresholds | Per-cluster limits: max_connections, max_pending_requests, max_requests, max_retries |
| max_connections | Envoy cap on connections to a cluster |
| max_pending_requests | Envoy cap on queued requests |
| pgbouncer | A PostgreSQL connection pooler |
| statement_timeout | PostgreSQL time limit per statement |
| analytics replica | Read-only database copy for slow queries |
| Horizon supervisor | A Laravel Horizon group of workers for given queues |
queue:work --queue | Laravel worker option listing queues in priority order |
| Graceful degradation | Doing less on purpose to keep the critical path alive |
| Critical path | The journeys the business cannot lose |
| Feature flag | A runtime switch for code |
| Kill switch | A flag used to turn a feature off in an incident |
| Pennant | Laravel's feature flag package |
| Fallback | An alternative path when the primary fails |
| Stale cache | An expired value served on purpose |
| Reduced functionality | Features removed to save capacity |
| Read-only mode | Reads served, writes refused |
| Static page | Pre-rendered content served without the backend |
| Maintenance mode | Announced global unavailability (php artisan down) |
| Brownout | Disabling a feature for a fraction of requests |
| QoS tier | A service class that is degraded in a defined order |
| Progressive enhancement | Core works first; optional layers added on top |
| Partial results | Returning what completed |
| Degradation ladder | Ordered levels of reduced service |
| Hysteresis | Different enter and exit thresholds to prevent flapping |
| Game day | A planned failure exercise |
References
- Google SRE Book, Addressing Cascading Failures: https://sre.google/sre-book/addressing-cascading-failures/
- AWS Builders' Library, Workload isolation using shuffle-sharding: https://aws.amazon.com/builders-library/workload-isolation-using-shuffle-sharding/
- AWS Builders' Library, Avoiding fallback in distributed systems: https://aws.amazon.com/builders-library/avoiding-fallback-in-distributed-systems/
- AWS Well-Architected, Reducing the Scope of Impact with Cell-Based Architecture: https://docs.aws.amazon.com/wellarchitected/latest/reducing-scope-of-impact-with-cell-based-architecture/reducing-scope-of-impact-with-cell-based-architecture.html
- Michael Nygard, Release It! (2nd ed.), table of contents: https://pragprog.com/titles/mnee2/release-it-second-edition/
- Netflix Hystrix wiki, How it Works: https://github.com/Netflix/Hystrix/wiki/How-it-Works
- Resilience4j, Bulkhead: https://resilience4j.readme.io/docs/bulkhead
- Kubernetes, Resource management for pods and containers: https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/
- Kubernetes, Resource Quotas: https://kubernetes.io/docs/concepts/policy/resource-quotas/
- Kubernetes, Pod Priority and Preemption: https://kubernetes.io/docs/concepts/scheduling-eviction/pod-priority-preemption/
- Kubernetes, Pod Quality of Service classes: https://kubernetes.io/docs/concepts/workloads/pods/pod-qos/
- Kubernetes, API-initiated eviction: https://kubernetes.io/docs/concepts/scheduling-eviction/api-eviction/
- Kubernetes, Configure a PodDisruptionBudget: https://kubernetes.io/docs/tasks/run-application/configure-pdb/
- Envoy, Circuit breaking: https://www.envoyproxy.io/docs/envoy/latest/intro/arch_overview/upstream/circuit_breaking
- Envoy, CircuitBreakers proto: https://www.envoyproxy.io/docs/envoy/latest/api-v3/config/cluster/v3/circuit_breaker.proto
- PgBouncer configuration: https://www.pgbouncer.org/config.html
- PostgreSQL, Client connection defaults (timeouts): https://www.postgresql.org/docs/current/runtime-config-client.html
- Go,
golang.org/x/sync/semaphore: https://pkg.go.dev/golang.org/x/sync/semaphore - Laravel 13 Queues: https://laravel.com/docs/13.x/queues
- Laravel 13 Horizon: https://laravel.com/docs/13.x/horizon
- Laravel 13 Pennant: https://laravel.com/docs/13.x/pennant
- Laravel 13 Cache (
flexible,funnel): https://laravel.com/docs/13.x/cache - Laravel 13 Configuration (maintenance mode): https://laravel.com/docs/13.x/configuration