Skip to content

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 forGo to
The whole page in three tablesEverything in one minute
Why a shared pool turns one slow call into an outageWhy it exists
Nygard, Hystrix, Route 53, cells, SREWhere it comes from
The idea of a compartmentBulkhead
Goroutine, thread, connection pools, semaphoresResource pools
Bounded queues, separate queues, worker fleets, reject or waitQueues
How many slots, how long a queueSizing
Per-tenant limits, cells, shuffle shardingTenants and cells
Kubernetes, Envoy, pgbouncer, replicasPlatform bulkheads
What graceful degradation isGraceful degradation
Feature flags, kill switches, brownoutFlags and brownout
The ladder, QoS tiers, read-only mode, static pageDegradation ladder
Stale data, partial results, fallbacks that biteStale and partial
Game days, metrics for degraded modesTesting and observability
Exact knobs, defaults, error messagesMechanics
CodeGo, Laravel
Classic failures and fixesSolving the classic problems
Which isolation, which degradationChoosing
Monolith to distributed systemIn architecture
Run itLab
Wrong beliefs, summary, quiz, termsMisconceptions, Cheat sheet, Self-check, Glossary

Everything in one minute ​

The two ideas.

IdeaIn plain wordsTiny exampleWhat it limits
BulkheadFixed slice of a resource per neighbour20 connections for reports, 40 for checkoutThe blast radius of a slow or greedy neighbour
Graceful degradationDo less on purpose instead of failingProduct page without recommendationsThe damage when capacity or a dependency is gone

Where a bulkhead can live, smallest to largest.

LayerCompartmentMechanismTypical product or API
In processCalls to one dependencySemaphore, goroutine pool, bounded queueGo golang.org/x/sync/semaphore, Resilience4j Bulkhead, Hystrix
Process to databaseConnections per serviceConnection pool, role limitpgbouncer pool_size, PostgreSQL CONNECTION LIMIT
QueueJob classSeparate queue and worker fleetLaravel queue:work --queue=critical,default, Horizon supervisor
Proxy or meshUpstream clusterConnection, pending and request limitsEnvoy circuit breaker thresholds
OrchestratorPods, nodes, teamsrequests and limits, PriorityClass, PodDisruptionBudget, node pool, namespace quotaKubernetes
TenantCustomer or shardPer-tenant limit, shuffle shardAWS Route 53, API gateways
Whole stackA full copy of the serviceCell-based architectureAWS cells, regional deployments

The degradation ladder (this page's running example).

RungNameWhat turns offEntry signal (example)Users notice
0NormalNothing-Nothing
1Shed optionalRecommendations, personalisationLoad 70%Plainer page
2Cached onlyReviews, search suggestions; stale cache allowedLoad 85%Slightly old data
3Read onlyAll writes (503 + Retry-After)Load 95%Cannot change anything
4Static pageEverything dynamicLoad 110% or operatorA static notice
One shared pool (8 slots)8 of 8 slots held by slow recs callscheckout call waits ... rejectedEverything shares one fateBulkheads (4 + 4 slots)recs compartmentcheckout compartmentfull: extra calls rejected fastfree slots: servedcheckout call okrecs call: 503 / fallbackA slow dependency can only drown itselfSame total threads, same slow dependency; only the partitioning differs

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 resourceIsolated resource
Cheap and efficient: idle capacity is reusedSome capacity idles while a neighbour is full
One slow dependency can consume everythingA slow dependency can consume only its slice
Failure of a minor feature takes down the major onesMinor features fail alone and visibly
Simple to configureOne more number per dependency to size and watch
Great average utilisationGreat 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 ​

  1. "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.
  2. "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".
  3. "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.

text
     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 bulkhead

The 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.

text
     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 ms

Real 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.

text
     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).

MechanismCountsWaiting behaviourWhere
Thread pool (dedicated)ThreadsBounded queue, then rejectHystrix, Resilience4j FixedThreadPoolBulkhead
SemaphoreConcurrent callsAcquire(ctx) waits; TryAcquire fails at onceGo golang.org/x/sync/semaphore, Resilience4j SemaphoreBulkhead
Buffered channel as semaphoreConcurrent callsBlock or select with defaultGo stdlib
Connection poolOpen connectionsWait for ConnMaxLifetime/pool timeoutdatabase/sql, pgbouncer
Cache::funnelConcurrent executions across serversblock(seconds) then failure closure or exceptionLaravel 13
Envoy max_requestsOutstanding requests per clusterOverflow counter, x-envoy-overloadedEnvoy

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).

text
     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 cares

Real 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).

ChoiceProConUse when
Reject at the limitFast failure, no latency growthClient must retry or degradeInteractive requests
Wait up to a boundAbsorbs short burstsAdds latency up to the boundBursty but fast dependencies
Unbounded queueNothing refusedLatency and memory grow without limitAlmost never; batch only with monitoring
Priority queue, one fleetSimpleStarvation, shared worker crashFew classes, similar cost
Separate queues and fleetsHard isolation, per-class scalingMore processes to runClasses 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.

text
     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 up

Real scenario: 13 slots for payments, 3 for the recommendation builder, 5 connections for reports; a per-tenant concurrency of 10 on an API.

NumberFormulaExample
Concurrency (slots)rate x latency x (1 + headroom)200 x 0.05 x 1.3 = 13
Capacity of the compartmentslots / latency13 / 0.05 = 260 req/s
Queue boundcapacity x tolerable wait260 x 0.1 = 26
Slots after a latency spikeunchanged; throughput = slots / new latency13 / 0.5 = 26 req/s
Pool total across instancesper-instance slots x instances13 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.

text
     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 notices

Real 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.

TechniqueBlast radiusCostNeeds
Shared everything100%Lowest-
Per-tenant limitsBounded per tenant for what you limitLowTenant id on every request
Plain shards1 / shardsMediumRouting by tenant
Shuffle shardsabout 1 / C(n,k)Medium; clients must retry on another workerStable hash, retrying clients
Cells1 / cells for the whole stackHigh: N copies, a router, cell migrationA 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.

8 workers, 2 per tenant: 28 possible shuffle shardsw1w2w3w4w5w6w7w8Tenant A (bad)downTenant BslowerTenant CunaffectedPlain sharding into 4 groups: a bad tenant hurts 1/4. Shuffle sharding: about 1/28 (AWS).

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.

text
     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 affected

Real 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.

ProductBulkhead knobWhat it doesDefault or note
Kubernetesrequests and limitsReserve and cap CPU and memory per containerEqual requests and limits give the Guaranteed QoS class, the last to be evicted
KubernetesResourceQuota per namespaceCaps total requests, limits, pod countOne quota per team namespace
KubernetesPriorityClassWho is scheduled first and who is preemptedpreemptionPolicy defaults to PreemptLowerPriority; Never opts out
KubernetesPodDisruptionBudgetminAvailable or maxUnavailable for voluntary disruptionsPercent or integer
Kubernetesnode pool, nodeSelector, taintsDedicated machines per classCloud-specific naming
Envoymax_connectionsConnections to all hosts of the upstream cluster1024 per cluster by default
Envoymax_pending_requestsRequests queued waiting for a connectionOverflow counter upstream_rq_pending_overflow
Envoymax_requestsOutstanding requests to the clusterOverflow counter upstream_rq_active_overflow
Envoymax_retries / retry_budgetConcurrent retriesKeep low to stop retry storms
pgbouncerdefault_pool_size, per-database pool_sizeServer connections per user/database pair20
pgbouncermax_db_connections, max_user_connectionsCeilings across pools0 = unlimited
pgbouncermax_client_conn, pool_modeClient connections; reuse unitsession is the default; transaction is common for web apps
PostgreSQLstatement_timeout, lock_timeout, idle_in_transaction_session_timeoutKill statements, waits and idle transactions0 (disabled) by default
PostgreSQLanalytics replicaRead-only copy for slow queriesSee Replication
ClientEnvoyService podspgbouncerPostgreSQLper cluster:max_connectionsmax_pending_requestsmax_requestsper dependency:semaphore slotsbounded queuetimeoutsper service:pool_sizemax_db_connectionsreserve_poolper role:statement_timeoutCONNECTION LIMITanalytics replicaKubernetes layerrequests/limits, PDB, node pool

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.

yaml
# 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.

text
     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 typeWhat the user getsExample
OmitThe feature is goneNo recommendations carousel
DefaultA generic valuePopular items instead of personalised
StaleAn older but valid valuePrice from 5 minutes ago
PartialSome of the parts8 of 10 tiles
Cheaper algorithmLower quality, lower costLess accurate ranking
Read onlyBrowse but not changeNo new orders; order history works
StaticA fixed pageStatus 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.

text
     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 reviews

Real 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.

MechanismScopeProductNote
Config flag in a cache or databaseAll usersLaravel Cache, a flags tableMust not depend on the broken service
Pennant feature, per scopeA user, team or everyoneLaravel PennantStores the resolved value; use before() or activateForEveryone / deactivateForEveryone
Percentage rolloutA share of usersPennant Lottery::odds, LaunchDarkly, UnleashStable for the same scope
BrownoutA share of requestsCustom (Go SetBrownout)Stable hash per user
Envoy / gateway routeA route or tenantEnvoy, API gatewayWorks 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).

text
     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 automatic
0 normalall features on-1 shed optionalrecommendations, personalisation offload >= 70%2 cached onlyreviews, suggestions off; stale cache okload >= 85%3 read onlywrites refused: 503 + Retry-Afterload >= 95%4 static pagestatic page from CDN/edgeload >= 110%Climb one rung per signal; descend only after load below threshold - 10 points and a minimum dwell time

The 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 tierDegraded firstWhy
Free or anonymousEarly rungsLowest revenue per request
Bots, crawlers, bulk APIBefore humansCan retry later
Background jobsBefore interactiveNobody is waiting
Paying or logged-in customersLastHighest value
Critical path (browse, cart, pay)Never until staticThe 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).

text
     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 back

Real 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.

FallbackRiskMitigation
Cached or stale copyWrong data after a long outageMaximum staleness, label, never for money
Default or generic valueMisleading personalisationMark as default
Secondary serviceUntested, different capacityPrefer to make the primary reliable; exercise regularly
Direct database read when the cache failsStampede, takes the database tooBulkhead and rate-limit the fallback; request coalescing
Retry later (queue)Hidden backlogBounded 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).

text
     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.

SignalWhyAlert on
In flight per compartmentSaturationSustained near limit
Rejections per compartmentThe bulkhead is working (or limit too small)Rate and ratio
Wait time for a slotQueueingp99 above the bound
Current degradation levelWhat users seeLevel above 0 for more than N minutes
Degraded responses per featureImpactRatio of responses
Fallback hits and stale ageHidden riskAge 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 ​

QuantityFormula or valueSource
ConcurrencyL = lambda x WLittle's law
Shuffle shardsC(n,k); C(8,2) = 28; C(2048,4) about 730 billionAWS Builders' Library
Plain sharding blast radius1 / shardsAWS
Shuffle sharding blast radiusabout 1 / C(n,k)AWS
Resilience4j defaultsmaxConcurrentCalls 25, maxWaitDuration 0Resilience4j docs
Envoy default1024 connections per cluster, enabled by defaultEnvoy docs
pgbouncer default pooldefault_pool_size 20, reserve_pool_timeout 5.0 spgbouncer docs
PostgreSQL timeoutsstatement_timeout, lock_timeout, idle_in_transaction_session_timeout: 0 = offPostgreSQL docs

Knobs ​

LayerKnobMeaning
Gosemaphore.NewWeighted(n), Acquire(ctx, 1), TryAcquire(1), Release(1)Weighted semaphore; Acquire blocks until slots or the context ends
LaravelCache::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
LaravelCache::flexible($key, [$fresh, $stale], $cb)Stale-while-revalidate with a deferred refresh
Laravelphp artisan queue:work --queue=critical,defaultWorker drains critical fully before default
LaravelHorizon supervisor, queue, balance (auto, simple, false), processes, minProcesses, maxProcesses, autoScalingStrategy (time, size, log)Fleets per class
Laravelphp artisan down --refresh=15 --retry=60 --secret=... --render="errors::503"Maintenance mode with a bypass; APP_MAINTENANCE_DRIVER=cache shares it across servers
PennantFeature::active, Feature::for($scope), before(), activateForEveryone, purge, EnsureFeaturesAreActive::using(...)Flags
Kubernetesresources.requests, resources.limits, priorityClassName, maxUnavailable, minAvailable, ResourceQuotaSee platform table
Envoycircuit_breakers.thresholds[].max_connections, max_pending_requests, max_requests, max_retries, track_remaining, priorityPer cluster and per priority
pgbouncerpool_mode, max_client_conn, default_pool_size, reserve_pool_size, max_db_connections, max_user_connectionsPool compartments
PostgreSQLALTER ROLE ... CONNECTION LIMIT, ALTER ROLE ... SET statement_timeoutPer-role limits

Error messages and signals you will see ​

WhereSignalMeaning
Envoyx-envoy-overloaded header, HTTP 503; counters upstream_cx_overflow, upstream_rq_pending_overflow, upstream_rq_active_overflow, upstream_rq_retry_overflow, upstream_cx_pool_overflowA circuit breaker threshold was hit
LaravelIlluminate\Cache\Limiters\LimiterTimeoutExceptionCache::funnel could not get a slot within block()
LaravelIlluminate\Contracts\Cache\LockTimeoutExceptionCache::lock(...)->block() timed out (lock, not funnel)
LaravelHTTP 503 from HttpExceptionMaintenance mode
Resilience4jBulkheadFullExceptionSemaphore bulkhead full
PostgreSQLcanceling statement due to statement timeout (SQLSTATE 57014)statement_timeout fired
PostgreSQLcanceling statement due to lock timeout (SQLSTATE 55P03)lock_timeout fired
PostgreSQLFATAL: too many connections for role "svc_checkout" (SQLSTATE 53300)CONNECTION LIMIT reached
KubernetesEviction API answers 429 Too Many RequestsThe eviction is not allowed now because of a PodDisruptionBudget
KubernetesPod status OOMKilledMemory limit exceeded
HTTP503 + Retry-After; 429Rejected (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.

go
// 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.

go
// 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.

go
// 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.

go
// 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.

go
// 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.

go
// 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.

go
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.

go
// 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())
	}
}
go
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/semaphore provides NewWeighted, Acquire(ctx, n), TryAcquire(n) and Release(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 context to Acquire; a cancelled client must give up its place in the queue.
  • net/http has no per-host concurrency cap by default; Transport.MaxConnsPerHost caps connections per host and is the lightweight bulkhead for HTTP/1.1. database/sql has SetMaxOpenConns and SetMaxIdleConns per *sql.DB: use one *sql.DB per 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 InFlight and Rejected to your metrics library; the bulkhead is only useful if you can see it full.
  • Run go test -race on 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
<?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
<?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
<?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
<?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
<?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
<?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
<?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
<?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
<?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
<?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
<?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
<?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
<?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,default sets priority order.
  • Horizon. Three balancing strategies, auto, simple and false; 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's force option is true.
  • Cache::funnel "works with any cache driver that supports locks"; with block(0) it fails fast (rejection), with block(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::flexible implements 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=cache with a shared APP_MAINTENANCE_STORE needs it on one. Pre-render the view so errors do not appear while dependencies update.
  • Pennant. Feature::active, Feature::for($scope), Feature::activateForEveryone, and the EnsureFeaturesAreActive route middleware; for a kill switch use before() or deactivateForEveryone.
  • 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):
sql
-- 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';
sql
-- 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;
ini
; 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
yaml
# 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" ​

SolutionHowAdvantageCost or limit
Per-dependency semaphoreBulkhead.Do with a slot count from Little's lawCheap, localPer instance, not fleet-wide
Timeout plus bulkheadDeadline per call (Timeouts)Slots come backNeeds sensible timeouts
Circuit breaker on topOpen after repeated slow callsStops sendingNeeds tuning
Envoy cluster limitsmax_pending_requests, max_requestsLanguage-independentCoarser

"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-patternWhy it hurtsInstead
One shared pool for everythingSlowest dependency winsOne compartment per dependency
Synchronous dependency on a non-critical featureOptional feature can fail the critical pathOptional call with timeout, bulkhead and default
Unbounded queueLatency grows without boundBounded queue, reject or shed
Degradation never exercisedCode path rotsGame days, canary pinned to a level
Kill switch behind the broken dependencyCannot be flipped in an incidentLocal or highly available flag store
Pools sized from average latencyCollapse at the first spikeSize for the promised latency plus headroom
Per-instance limits with no fleet capN instances multiply the load on the dependencyDivide by instances or use Envoy or Cache::funnel
Same worker fleet for all classesShared fateSeparate fleets

Choosing ​

Which isolation ​

SituationRecommendationExtra techniqueReason
Few outbound dependencies, one languageIn-process semaphore per dependencyTimeout, circuit breakerCheapest and local
Many languagesEnvoy cluster thresholdsRetry budgetOne mechanism for all
Slow batch beside latency-critical codeSeparate queue and fleet, node poolPriorityClassHard wall
Many tenants on one poolPer-tenant limit, then shuffle shardingRetrying clientsSmaller blast radius
Must contain a bad deploy or corruptionCellsCell routerWhole-stack isolation
Analytics beside OLTPAnalytics replica, separate role and poolstatement_timeoutProtect the primary

Which degradation ​

SituationRecommendationReason
Optional feature's dependency is slow or downOmit or default behind a flagCheapest, safest
Origin down but data tolerates ageStale cache with a maximum ageKeeps pages alive
Overload from trafficBrownout then ladder; shed per Load SheddingProportional response
Database failover or migrationRead-only modeKeeps reads and trust
Total loss of dynamic tierStatic page from CDNLast resort
Planned workMaintenance mode with bypassAnnounced, 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 ​

ScaleIsolationDegradation
1x: one app, one databaseSeparate queues, statement_timeout, role limitsMaintenance mode, Cache::flexible
10x: several servicesSemaphore per dependency, pgbouncer per service, node pools, PDBsFlags and kill switches, stale caches, read-only middleware
100x: many tenants, regionsPer-tenant limits, shuffle sharding, Envoy thresholds, quotasA controller-driven ladder, brownout, game days
1000x: platformCells with a router, regional stacksStatic-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).

text
# 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: false

Reading 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.

text
# 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 0

Common misconceptions ​

BeliefReality
"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 ​

TopicWhat to remember
BulkheadFixed slice per dependency, tenant or class; limit plus defined behaviour at the limit
SemaphoreGo semaphore.NewWeighted; TryAcquire rejects, Acquire(ctx) waits
QueueBound it; reject or shed at the bound
Sizingslots = rate x latency x (1 + headroom); queue = throughput x tolerable wait
Per instance vs fleetMultiply by instances, or limit at Envoy or Cache::funnel
TenantsPer-tenant concurrency, then shuffle sharding, then cells
Shuffle shardingC(n,k) shards; 8 choose 2 = 28, so 1/28 of the impact
Kubernetesrequests and limits, ResourceQuota, PriorityClass, PDB, node pool
Envoymax_connections, max_pending_requests, max_requests, max_retries
pgbouncerOne pool per service; pool_size, max_db_connections, pool_mode
PostgreSQLRole CONNECTION LIMIT, statement_timeout, analytics replica
Laravel queuesqueue:work --queue=critical,default, Horizon supervisor per class
DegradationOmit, default, stale, partial, cheaper, read-only, static
LadderOrdered rungs, entry and exit signals, hysteresis, dwell, override
Kill switchOff-switch not behind the failing dependency
TestingA test per rung, a game day, a canary pinned to a level

Self-check: questions & answers ​

Show:
  • 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 ​

TermMeaning
BulkheadA hard limit on the share of a resource one dependency, tenant or class may use
IsolationKeeping one component's failure from reaching another
Resource poolFixed set of reusable workers or connections
Thread poolDedicated threads for one dependency's calls
Connection poolCap on open connections to one server
SemaphoreCounter of free slots
Bounded queueQueue with a fixed length; excess is rejected
Separate queueA queue per job class
Worker fleetThe processes serving a queue
Priority queueQueue served in class order; may starve low classes
RejectionAn immediate refusal (503, 429)
QueueingDelaying work until capacity is free
Little's lawL = lambda x W
HeadroomExtra slots over the computed minimum
Per-tenant limitRate, concurrency or queue share per customer
Cell-based architectureMany independent full copies of a service, each serving a subset
Cell routerThe thin layer that maps a tenant to a cell
Shuffle shardingAssign each tenant k of n workers pseudo-randomly
requests and limitsKubernetes container reservation and ceiling
ResourceQuotaNamespace-wide cap on resources
namespaceKubernetes scope for names and quotas
PriorityClassScheduling and preemption order for pods
PodDisruptionBudgetLimit on voluntary pod evictions
node poolA group of nodes with the same shape or labels
Envoy circuit breaker thresholdsPer-cluster limits: max_connections, max_pending_requests, max_requests, max_retries
max_connectionsEnvoy cap on connections to a cluster
max_pending_requestsEnvoy cap on queued requests
pgbouncerA PostgreSQL connection pooler
statement_timeoutPostgreSQL time limit per statement
analytics replicaRead-only database copy for slow queries
Horizon supervisorA Laravel Horizon group of workers for given queues
queue:work --queueLaravel worker option listing queues in priority order
Graceful degradationDoing less on purpose to keep the critical path alive
Critical pathThe journeys the business cannot lose
Feature flagA runtime switch for code
Kill switchA flag used to turn a feature off in an incident
PennantLaravel's feature flag package
FallbackAn alternative path when the primary fails
Stale cacheAn expired value served on purpose
Reduced functionalityFeatures removed to save capacity
Read-only modeReads served, writes refused
Static pagePre-rendered content served without the backend
Maintenance modeAnnounced global unavailability (php artisan down)
BrownoutDisabling a feature for a fraction of requests
QoS tierA service class that is degraded in a defined order
Progressive enhancementCore works first; optional layers added on top
Partial resultsReturning what completed
Degradation ladderOrdered levels of reduced service
HysteresisDifferent enter and exit thresholds to prevent flapping
Game dayA planned failure exercise

References ​

Built by Morteza Negahi