Skip to content

Load Shedding ​

"Goodput is the subset of the throughput that is handled without errors and with low enough latency for the client to make use of the response." — Amazon Builders' Library, Using load shedding to avoid overload (5 December 2019)

Summary: Every server has a capacity; offered load above it does not make the server "a little slower", it makes it useless, because queued requests are answered after the client has stopped waiting. Load shedding means refusing some work on purpose, early and cheaply, so the work you accept still finishes in time. Focus: Goodput versus throughput, overload signals (queue wait, in-flight, CPU, latency, memory), static and adaptive concurrency limits (AIMD, Vegas, gradient), queue-time budgets and CoDel, criticality tiers, per-customer quotas, 503 versus 429 and Retry-After, client-side throttling and retry budgets, queue TTL and overflow, autoscaling interplay, Envoy, NGINX, HAProxy and Kubernetes knobs, testing and metrics, with Go and Laravel 13 code and a simulator lab. Learning goal: For any service, name the signal that says "overloaded", put a limit in front of the work that adapts to it, decide which requests lose first, tell clients what to do next, and prove with a load test that goodput plateaus instead of collapsing.

This chapter sits in the Resilience group, after Timeouts, Retries & Jitter and Circuit Breaker, and next to Bulkheads & Graceful Degradation. Rate limiting by identity is Rate Limiting; slowing producers through the broker is Backpressure & Flow Control; how one overloaded service drags down its callers is Cascading Failures. Here we own the decision "which work do we drop, where, how do we say no, and how do we know it helped".

Page map ​

If you are looking forGo to
The whole page in three tablesEverything in one minute
Why a server gets worse, not just slowerWhy it exists
Google SRE, Netflix, AWS, CoDel, EnvoyWhere it comes from
Goodput and the collapseGoodput
What tells you "overloaded"Overload signals
Fixed and adaptive limitsStatic limit, Adaptive limits
Dropping old workQueue-time budget and CoDel
Who loses firstCriticality tiers, Quotas and cost
What the client sees503, 429, Retry-After, Partial results
Clients that helpClient cooperation
Rate limit, backpressure or sheddingThree different tools
QueuesQueue-based shedding
AutoscalingAutoscaling interplay
Which layerWhere to shed
ProofTesting and metrics
Exact knobs and numbersMechanics
CodeGo, Laravel
Classic failuresSolving the classic problems
Decision tableChoosing
Monolith to fleetIn architecture
Run the simulatorLab
Wrong beliefs, summary, quiz, termsMisconceptions, Cheat sheet, Self-check, Glossary

Everything in one minute ​

The ideas.

IdeaIn plain wordsTiny exampleMain risk
Load sheddingRefuse some requests on purpose so the rest finish in timeReturn 503 at once when 20 requests are already in flightRefusing work you could have served (false positive)
GoodputReplies that arrived in time and were correct100 req/s served under a 1 s client timeoutMeasuring throughput instead and missing the collapse
Concurrency limitCap on requests in flight, not on requests per secondlimit = RPS x latency: 100 req/s at 100 ms is 10A fixed number that goes stale after a deploy or a scale-out
Adaptive limitThe cap moves with measured latency or lossNetflix concurrency-limits, Envoy adaptive concurrencyOscillation, a bad minimum-latency baseline
Queue-time budgetDrop requests that already waited too longX-Request-Start older than 500 msClock skew between proxy and app
Criticality tierLabel that decides who is refused firstCRITICAL_PLUS, CRITICAL, SHEDDABLE_PLUS, SHEDDABLEEverybody labels themselves critical
Client cooperationClients slow down when told toAdaptive throttling, retry budget, honour Retry-AfterRetries that multiply the overload

The signals, from late to early.

SignalWhat it measuresReactsWeakness
Latency versus SLOTime users seeLate: damage already doneSlow successes and fast refusals mix in one histogram
CPU utilisationCompute saturationMediumBlind to I/O waits and to lock contention
Memory pressureHeap or cgroup useLate, cliff-shapedOOM kill comes before a gentle slope
In-flight requestsConcurrency right nowEarlyNeeds a good limit to compare against
Queue lengthBacklog sizeEarlySame length means different waits as service time changes
Queue wait timeAge of the oldest or the next itemEarliest, most directNeeds timestamps taken at the front door

What to return.

SituationStatusHeadersClient should
Server is overloaded503 Service UnavailableRetry-After: 1 plus jitterBack off, retry within its budget
This customer is over its quota429 Too Many RequestsRetry-AfterSlow this caller only
Overloaded and retries will not help503an explicit "do not retry" markerFail up, do not retry
A cheaper answer exists200Warning or a field marking the result partialRender the degraded result
Connection refused at the listenerTCP reset or no responsenoneTreat like a 503
1x2x3x4xOffered load (multiple of capacity)Capacity (100 req/s in the lab)Goodput (useful replies per second)With shedding: flat at capacityexcess is refused in microsecondsNo shedding: collapseserver works on requests nobody waits for1000

The picture is the whole chapter. Below capacity, goodput equals offered load. Above it, a server that accepts everything spends its time on requests whose clients have already left, and goodput falls toward zero. A server that refuses the excess keeps goodput flat at capacity. The numbers in the lab come from the simulator in this chapter.

Why it exists ​

A server is a queue with workers. Once offered load exceeds what the workers can finish, the queue grows without bound, every request waits longer, and sooner or later the wait exceeds the client's timeout. From then on each reply is wasted: the server did the work and nobody read the answer. The Builders' Library describes the shape: "When a system is given more work than its resources support, it becomes slow. Computers take on work even when they're overloaded, but they spend increasing amounts of their time context switching and become too slow to be useful." It then names the amplifier: "clients often retry their request. This multiplies the offered load on the system." The result is "an overload creates its own feedback loop that results in overload as a steady state."

Accept everythingShed on purpose
Every request waits in a growing queueExcess requests are refused in microseconds
Latency rises for all usersLatency stays flat for admitted users
Work on expired requests is wastedExpired work is skipped
Retries pile on topClients are told to wait, with a hint
The process may run out of memory and restartThe process stays up and keeps serving
Recovery needs the load to disappearRecovery is automatic when load falls
Dashboards show high throughput, low goodputDashboards show shed counts you can alarm on

The analogy we reuse on this page: a restaurant with a full kitchen. The kitchen can cook ten dishes at a time. If the host seats every walk-in, tickets pile up, every table waits an hour, half the guests leave, and the kitchen still cooks their dishes. A good host quotes a wait, seats reservations and the food-critic table first, tells the tour bus to come back at three, and keeps the kitchen at full speed on dishes someone will eat. Seating is admission control. The priority list is criticality. "Come back at three" is Retry-After. Cooking a dish for a table that left is wasted work.

Three common misunderstandings, up front ​

  1. "Shedding means we failed." Shedding is the planned failure of the cheapest, least important requests so the important ones succeed. AWS states the effect: "the requests that the server decided to accept remain available because they were served quickly".
  2. "An overloaded server should stop accepting traffic." Google's SRE book calls this a mistake: "We actually want the backend to continue accepting as much traffic as possible, but to only accept that load as capacity frees up."
  3. "Autoscaling makes shedding unnecessary." New instances take minutes; overload takes seconds. AWS adds that misconfigured shedding can even "disable reactive automatic scaling". The two have to be designed together (Autoscaling interplay).

Where it comes from ​

TCP congestion control, 1988 onward. The ideas behind adaptive limits are older than web services: grow the window by one while things go well, cut it sharply on loss (AIMD), or watch the delay and slow down when a queue starts to build (Vegas). Netflix's README states the borrowing directly: "to estimate the limit we borrow from common TCP congestion control algorithms by equating a system's concurrency limit to a TCP congestion window".

Controlled delay, 2012. Nichols and Jacobson's CoDel (ACM Queue, 2012; IETF RFC 8289, January 2018, Experimental) measures how long each packet sat in the buffer ("sojourn time") and drops only when that delay stays above a target for a whole interval, which means a standing queue rather than a burst.

Google SRE book, 2016. Chapter 21 Handling Overload introduced criticality (four values), per-customer quotas measured in CPU, client-side adaptive throttling and retry budgets, and the rule that "a backend task provisioned to serve a certain traffic rate should continue to serve traffic at that rate without any significant impact on latency, regardless of how much excess traffic is thrown at the task".

Netflix concurrency-limits, 2018. The Netflix library replaced fixed requests-per-second limits with concurrency limits estimated from latency, because "in large distributed systems that auto-scale this value quickly goes out of date". It ships Vegas, Gradient2, AIMD and a partitioned (percentage) enforcement strategy.

Amazon Builders' Library, 2019. Using load shedding to avoid overload gave the vocabulary this page uses (goodput versus throughput, positive feedback loops, bounded work, per-request time-to-live) and the testing rule: the ideal overload test shows "goodput to plateau when the service is close to being fully utilized".

Envoy. Envoy ships an adaptive concurrency HTTP filter built on the gradient controller and an overload manager that triggers actions such as envoy.overload_actions.stop_accepting_requests from resource monitors.

text
     Year   Idea                                       What changed in practice
1    1988   TCP congestion avoidance (AIMD)            Probe up slowly, back off fast
2    1995   TCP Vegas (delay based)                    Queue estimated from RTT, no loss needed
3    2012   CoDel (Nichols, Jacobson)                  Drop on persistent queue delay, not queue length
4    2016   SRE book ch. 21                            Criticality, adaptive throttling, retry budgets
5    2018   Netflix concurrency-limits                 Concurrency limits replace RPS limits
6    2018   RFC 8289                                   CoDel specified (Experimental)
7    2019   AWS Builders' Library                      Goodput, per-request TTL, test to plateau
8    later  Envoy adaptive concurrency, overload mgr   Shedding in the proxy, no app change

The concept catalogue ​

Each block follows the same order: plain words, the usual wrong belief, a definition, a sequence, real scenarios, how products provide it, and the fix.

Goodput and the overload collapse Must-know ​

In plain words: Throughput counts every request the server touched. Goodput counts only the replies somebody could still use. Under overload the first stays high while the second falls to nothing.

Common misunderstanding: "CPU is at 100% and requests per second are at record height, so the system is doing great." Those numbers include work for clients that timed out. A system can have maximum throughput and zero goodput.

Definition: Goodput is the rate of requests completed successfully and within the client's deadline. AWS: "Throughput is the total number of requests per second that is being sent to the server. Goodput is the subset of the throughput that is handled without errors and with low enough latency for the client to make use of the response." The shape of the problem comes from the Universal Scalability Law, which the same article invokes: beyond a point, adding load lowers useful output.

text
     t     Event (server: 10 workers x 100 ms = 100 req/s; clients time out after 1 s)
1    0.0   Offered load jumps to 300 req/s; queue starts to grow at 200 req/s
2    1.0   First requests exceed 1 s in the queue; their clients give up
3    1.0   Server still processes them: wasted work, no reply is read
4    2.0   Queue is 400 deep; every new request waits 4 s, so none can succeed
5    2.0   Clients retry; offered load is now 300 + retries
6    ...   Goodput is about zero while CPU stays at 100%

Real scenarios: a product launch where the login service answers everyone after the browser gave up; a batch job starting at midnight and doubling traffic on a shared database; a deploy that removes a third of the fleet at peak; a cache flush that sends every read to the database.

What provides it: a reject path that is much cheaper than the work, and a limit that keeps queueing delay below the client timeout.

ProductWhere the "refuse early" happensDefault reply
NGINXlimit_conn / limit_req503 (limit_conn_status, limit_req_status default 503)
HAProxytimeout queue after server maxconn is reached503
EnvoyOverload manager stop_accepting_requests; adaptive concurrency filter503
Kuberneteskubelet eviction under node pressurePod killed, not a reply
RabbitMQqueue overflow=reject-publishbasic.nack to the publisher
Laravelyour middleware (below)503 + Retry-After

Fix / how to use it: measure goodput as "2xx within the SLO latency", set up the load test in Testing and metrics, and put an admission limit in front of the work (Go, Laravel).

Overload signals Must-know ​

In plain words: To refuse work at the right moment you need a number that rises before users are hurt. Different numbers rise at different times.

Common misunderstanding: "CPU above 80% means overloaded." A service can be saturated at 30% CPU (all threads blocked on a slow database) or healthy at 90% (compute-bound with no queue). CPU is a proxy; queue wait is the thing itself.

Definition: An overload signal is a measurement, taken inside the process or at its front door, that crosses a threshold when demand exceeds capacity. Google's SRE book builds task-level protection on "utilization": "In many cases, the utilization is just a measurement of the CPU rate ... but in some cases we also factor in measurements such as the portion of the memory reserved that is currently being used." Its most general signal is the executor load average, the smoothed count of active threads, "and begin rejecting requests as the number of active threads grows beyond the number of processors available to the task".

text
     Time   In flight   Queue wait   CPU    p99     What the signal says
1    0 s    8           2 ms         55%    90 ms   healthy
2    5 s    12          40 ms        70%    120 ms  in flight above workers: queueing starts
3    10 s   20          300 ms       85%    450 ms  queue wait shows overload; CPU still "fine"
4    15 s   40          1.5 s        100%   2.5 s   latency shows it, users are already gone

Real scenarios: a service waiting on a slow downstream (low CPU, in-flight at the cap); a GC-heavy JVM where memory pressure is the first sign (Google notes that "in platforms with garbage collection, memory pressure naturally translates into increased CPU consumption"); a PHP-FPM pool where all pm.max_children are busy; a Go service with goroutines piling up on a mutex.

SignalNGINX / HAProxyEnvoyKubernetesApplication
In-flight / connectionslimit_conn, server maxconncircuit breaker max requests, adaptive concurrencynonegauge you keep
Queue waittimeout queue (HAProxy)pending requests breakernoneX-Request-Start age
Memorynonefixed_heap, cgroup_memory resource monitorsmemory.available eviction signalprocess RSS
CPUnoneCPU-based actions via monitorsnode Allocatable, not an eviction signal for CPUutilisation, executor load
Latency vs SLOnonegradient controller (RTT)nonehistogram, minRTT

Fix / how to use it: pick one early signal as the trigger (in-flight against a limit, or queue wait), keep CPU and memory as backstops, and always count requests per tier. A good default is queue wait for time-sensitive services and in-flight for everything else.

Static concurrency limit Must-know ​

In plain words: Decide how many requests may be inside the service at once; the next one is refused.

Common misunderstanding: "A requests-per-second limit is the same thing." It is not: RPS says nothing about how long each request holds a worker. Netflix's README: "RPS limits are then set somewhere below this tipping point (say 75% of this value) and enforced via a token bucket. However, in large distributed systems that auto-scale this value quickly goes out of date." Concurrency tracks capacity because of Little's Law, which the README writes as Limit = Average RPS * Average Latency.

Definition: A static concurrency limit is a constant L. A request is admitted if fewer than L are in flight; otherwise it is refused immediately. Little's Law gives the starting point: 100 req/s at 100 ms is 10 requests in flight; a limit of 20 allows a queue of 10, which adds at most 100 ms.

text
     In flight   Event
1    0..19       request admitted, counter++
2    20          next request refused: 503 + Retry-After, counter unchanged
3    19          one finishes, counter--
4    20          next request admitted

Real scenarios: NGINX limit_conn perserver 100; HAProxy server maxconn; a Go semaphore in front of an expensive endpoint; PHP-FPM pm.max_children as an accidental limit that queues in the web server.

ProductSettingWhat happens at the limit
NGINXlimit_conn zone number;503 by default (limit_conn_status)
HAProxymaxconn on a server, timeout queuewaits in queue, then 503
Envoycircuit breaker max_requests, max_pending_requests, max_connections503, upstream_rq_pending_overflow counters
PHP-FPMpm.max_childrenconnections wait in the listen backlog
Laravel Octane--workers (default: one per CPU core)requests queue in the application server

Fix / how to use it: start from workers x (1 + tolerated queue), load test, and treat the number as a guess that expires; the adaptive limits below remove the guessing.

Adaptive concurrency limits: AIMD, Vegas, gradient Must-know ​

In plain words: Let the server find its own limit the way TCP finds a window: speed up while latency is flat, slow down when latency rises.

Common misunderstanding: "Adaptive means no tuning." You still choose the algorithm, the bounds, the window and the buffer, and you still need tiers and good metrics. What disappears is the hand-measured constant.

Definition: An adaptive limit is a limit recomputed from samples (RTT, in-flight count, drops). The three families:

AlgorithmSignalUpdate ruleStrengthWeakness
AIMDloss: timeout or rejectionsuccess and in-flight above half the limit: +1; drop: multiply by a backoff such as 0.9simple, needs no baselinereacts after harm; sawtooth
Vegasdelayqueue = limit x (1 - minRTT/sampleRTT); alpha 2-3, beta 4-6: below alpha +1, above beta -1 (Netflix README)reacts before lossone fast outlier poisons minRTT
Gradient / Gradient2delay trendEnvoy: gradient = (minRTT + B) / sampleRTT, limit' = gradient x limit + headroom, headroom = sqrt(limit), B = minRTT x buffersmooth, probes upward by itselfminRTT drift; needs periodic re-measure

Netflix's README explains what Gradient2 adds: "This algorithm attempts to address bias and drift when using minimum latency measurements. To do this the algorithm tracks the measure of divergence between two exponential averages over a long and short time window." Envoy's controller handles the same drift differently: it re-measures minRTT periodically by pinning concurrency to min_concurrency, with jitter so not every host measures at once, and the docs warn: "It is possible that there is a noticeable increase in request 503s during the minRTT measurement window because of the potentially significant drop in the concurrency limit."

Arrivalstiers 1.0 / 0.9 / 0.7 / 0.5Limiterin flight < share x limitServerqueue + workSampleRTT, in flight, drop?Algorithmcompare with minRTTnew limitAIMD (loss based, TCP style)success and in flight above half the limit: limit + 1drop or timeout: limit x backoff (for example 0.9)Vegas (delay based)queue = limit x (1 - minRTT / sampleRTT)below alpha: +1, above beta: -1Gradient (Envoy gradient controller)gradient = (minRTT + B) / sampleRTTlimit' = gradient x limit + sqrt(limit)Why minRTT mattersit is the latency with no queue; any rise above itis queueing, which is the overload signal

The loop in the picture is the same for every algorithm: admit while in flight is below the limit, measure each finished request, compare with the unloaded latency, and move the limit.

text
     Window   avg RTT   minRTT   gradient (buffer 0.2)   limit   Event
1    1        10 ms     10 ms    1.20 -> 1.0 (capped)    100     grow by sqrt(limit) = +10
2    2        14 ms     10 ms    12/14 = 0.86            96      slight queueing: shrink
3    3        30 ms     10 ms    12/30 = 0.40 -> 0.5     58      clamp, limit nearly halves
4    4        12 ms     10 ms    1.0                     65      queue drained: grow again

Real scenarios: Netflix recommends the Vegas limiter on the server and AIMD on the client for gRPC ("it is recommended to use a dynamic delay based limiter such as the VegasLimit on the server and either a pure loss based (AIMDLimit) or combined loss and delay based limiter on the client"); Envoy's adaptive concurrency filter in front of a cluster; a Go gateway using the gradient limiter from this chapter.

ProductAdaptive limitNotes
Netflix concurrency-limits (Java)VegasLimit, Gradient2Limit, AIMDLimit, WindowedLimitgRPC interceptor, servlet filter (rejects with 429), executor
Envoyenvoy.filters.http.adaptive_concurrency gradient controllermax_concurrency_limit defaults to 1000; filter must see all traffic to the cluster
NGINXnone built inlimit_conn is static
HAProxynone built inmaxconn is static; dynamic via the runtime API from outside
KubernetesnoneHPA scales replicas, not in-flight limits
Laravel Octanenoneworkers are fixed; use the gauge in the Laravel section

Fix / how to use it: Go limiter and algorithms below: limit.NewGradient, limit.NewVegas, limit.NewAIMD, each behind the same Algorithm interface so tests can swap them.

Queue-time budget, queue timeout and CoDel Important ​

In plain words: Do not do work for someone who has stopped waiting. Stamp when the request arrived; if it already waited longer than it is worth, drop it unread.

Common misunderstanding: "A longer queue is safer because nothing is dropped." A long queue only converts overload into latency; most of its content will be expired by the time it reaches a worker. A short, bounded queue with a time budget is the safe one.

Definition: A queue-time budget refuses a request whose waiting time (now minus enqueue or arrival time, the "sojourn time") exceeds a limit. HAProxy has it built in: "When a server's maxconn is reached, connections are left pending in a queue ... If the timeout is reached, it is considered that the request will almost never be served, so it is dropped and a 503 error is returned to the client." CoDel makes the budget adaptive in spirit: RFC 8289 says TARGET "SHOULD be set to 5 ms for normal Internet traffic" and the INTERVAL is 100 ms, and it only drops when delay stays above TARGET for a whole INTERVAL, which separates a burst from a standing queue. AWS adds the deadline version: "we have found it helpful to enforce a 'per-request time-to-live' and throw away doomed requests".

text
     Clock      Event
1    12:00:00.000   proxy stamps X-Request-Start = t=1700000000.000
2    12:00:00.400   request reaches PHP worker (queued behind slow requests)
3    12:00:00.401   middleware: waited 401 ms, tier budget 500 ms: serve
4    12:00:01.200   next request, waited 1200 ms: over budget -> 503 + Retry-After, no work done

Real scenarios: an NGINX in front of PHP-FPM where the listen backlog fills; a Go service whose accept queue holds old connections; a job queue where jobs older than ten minutes are pointless; a consumer reading a topic with a growing backlog.

MechanismProductKnob
Queue timeoutHAProxytimeout queue, server maxqueue
Per-request TTLRabbitMQx-message-ttl, per-message expiration
Job stalenessLaravel queuesretryUntil(), Skip::when()
Request ageAny proxy that stamps X-Request-StartNGINX proxy_set_header X-Request-Start "t=${msec}"
Standing-queue dropCoDel (RFC 8289)TARGET 5 ms, INTERVAL 100 ms for networks; service queues need their own values

Fix / how to use it: shed.ParseRequestStart and the middleware's QueueBudget; msgqueue.CoDel for in-process queues; ShedLoad for Laravel. One caution: the budget compares two clocks (the proxy's and the app's). Keep them NTP-synchronised or measure on a single host only.

Criticality tiers (priority-based shedding) Must-know ​

In plain words: When something has to be refused, refuse the least important requests first.

Common misunderstanding: "Priority queues solve this." A priority queue orders waiting work; it does not stop the queue from growing. Tiers must be tied to an admission limit: lower tiers are refused at a lower occupancy, so room is kept for higher tiers.

Definition: Google's SRE book defines four criticality values attached to every request: CRITICAL_PLUS ("reserved for the most critical requests, those that will result in serious user-visible impact if they fail"), CRITICAL ("the default value for requests sent from production jobs"), SHEDDABLE_PLUS ("traffic for which partial unavailability is expected. This is the default for batch jobs") and SHEDDABLE ("frequent partial unavailability and occasional full unavailability is expected"). Rules from the chapter: "When a task is itself overloaded, it will reject requests of lower criticalities sooner", criticality is "orthogonal to its latency requirements", and it is propagated: "request B and request C will use the same criticality as request A by default". Set it "as close as possible to the browsers or mobile clients".

RequestX-Priority1. Queue budgetnow - X-Request-Startabove the tier budget?2. Customer quotain-flight per API keyabove the cap?3. Tier sharein flight at or aboveshare x limit?Handlerrun503Retry-After429Retry-After503Retry-AfteryesyesyesnononoCRITICAL_PLUSCRITICALSHEDDABLE_PLUSSHEDDABLE100%90%70%50%Share of the concurrency limit each tier may occupy
text
     In flight (limit 20)   CRITICAL_PLUS(20)  CRITICAL(18)  SHEDDABLE_PLUS(14)  SHEDDABLE(10)
1    0..9                   admit              admit         admit               admit
2    10..13                 admit              admit         admit               refuse
3    14..17                 admit              admit         refuse              refuse
4    18..19                 admit              refuse        refuse              refuse
5    20                     refuse             refuse        refuse              refuse

Real scenarios: checkout (CRITICAL_PLUS) versus order history (CRITICAL) versus typeahead (SHEDDABLE) versus nightly CSV export (SHEDDABLE_PLUS); health-check pings, which the Builders' Library calls "the most important request that a server will receive"; Netflix's percentage enforcement ("live traffic 100% of the limit during heavy load" and batch starved, or "50% of the limit ... to write traffic so writes are never starved"); search-engine crawlers at amazon.com.

ProductTiering mechanism
Google RPCcriticality as a first-class field, propagated down the call tree
Netflix concurrency-limitspartitionByHeader(...), partition("live", 0.9)
Envoyper-route and per-priority circuit breakers; no built-in tier propagation
KubernetesPriorityClass for eviction order; API Priority and Fairness for the API server
Laravelroute middleware parameter plus X-Priority header (this chapter)
This chapter's Go middlewareThresholds 1.0 / 0.9 / 0.7 / 0.5 of the shared limit

Fix / how to use it: tier by route and by caller, never by trusting a client-supplied label alone (the Laravel middleware lets a client lower its tier, never raise it). Keep exactly four tiers: Google notes more values "would require more resources to operate various criticality-aware systems". Default unlabelled traffic to CRITICAL.

Per-customer quotas and cost-based shedding Important ​

In plain words: One noisy customer must not cause errors for the quiet ones. Give each customer a share and refuse only the one that exceeds it.

Common misunderstanding: "Requests per second per customer is a fair quota." Requests differ wildly in cost. Google: "modeling capacity as 'queries per second' ... often makes for a poor metric"; it measures cost as normalised CPU time instead.

Definition: A per-customer quota caps the resources one caller may use. In the SRE book, quotas are CPU-seconds per second ("Gmail is allowed to consume up to 4,000 CPU seconds per second") and "these numbers may add up to more than the 10,000 CPUs allocated", relying on the fact that all customers rarely peak together. Over quota, requests of that customer alone are rejected, lowest criticality first. Cost-based shedding generalises this: admit by estimated or measured cost (rows scanned, CPU ms, tokens), not by count.

text
     Customer   Quota   Using   Event
1    A          4000    4600    over quota: A's SHEDDABLE rejected first, then CRITICAL
2    B          4000    1200    untouched
3    C          3000    2900    near quota, still admitted
4    other      500     480     admitted

Real scenarios: a tenant running a scraper against a shared API; an internal team launching a batch job against a shared backend; a public API with a free tier and an enterprise tier; GraphQL queries priced by complexity.

ProductPer-caller mechanismReply
NGINXlimit_conn_zone $binary_remote_addr (+ limit_req)503 by default; set limit_conn_status 429
Envoylocal and global rate-limit filters429
AWS API Gateway, Cloudflareper-key usage plans, rate rules429
Netflix servlet filterpartitionByUserPrincipal429
This chapterCustomer and CustomerMax in the Go middleware429 + Retry-After

Fix / how to use it: quota by identity first (cheap, gives 429), and keep the shared adaptive limit for what quotas cannot see. For the algorithms behind per-identity limits see Rate Limiting.

What to return: 503, 429, Retry-After Must-know ​

In plain words: The status code tells the client whose fault it is and whether waiting helps.

Common misunderstanding: "Use 429 for all shedding." RFC 6585 defines 429 as "the user has sent too many requests in a given amount of time". That is about one caller's rate. Server-wide overload is not the caller's fault and is 503.

Definition: RFC 9110 defines 503: "the server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay. The server MAY send a Retry-After header field". It adds that "the existence of the 503 status code does not imply that a server has to use it when becoming overloaded. Some servers might simply refuse the connection." Retry-After is "HTTP-date / delay-seconds"; with 503 it "indicates how long the service is expected to be unavailable to the client". RFC 6585: 429 responses "MAY include a Retry-After header" and "MUST NOT be stored by a cache".

StatusMeaningUse whenRetry-AfterRetry safe?
503 Service UnavailableServer cannot take it nowConcurrency limit, queue budget, overload managerYes, seconds, with jitterYes, within a budget
429 Too Many RequestsThis caller exceeded a rate or quotaPer-customer quotaYesYes, after the wait
504 Gateway TimeoutA proxy gave up on its upstreamNot shedding: a symptom of overload downstreamNoIdempotent only
500 Internal Server ErrorBugNever for sheddingNoUnknown
gRPC UNAVAILABLENetflix limiter's rejectiongRPC servicesvia trailerYes, budgeted
Connection refused / GOAWAYListener or connection levelEnvoy disable_http_keepaliven/aYes
text
     Request                                    Response
1    GET /search/suggest?q=lo  (SHEDDABLE)  ->  503 Service Unavailable
2                                              Retry-After: 2
3                                              X-Shed-Reason: concurrency
4                                              Cache-Control: no-store

Real scenarios: NGINX limit_conn_status 429 for per-IP downloads and the default 503 for server-wide limits; Envoy stop_accepting_requests returning 503; a mobile client that must not show an error page for a suggestion request.

Fix / how to use it: reply with 503 for global overload and 429 for a caller over its own quota; send Retry-After in seconds (never a date in a fleet with skewed clocks), add jitter on the server so refused clients do not return together, add Cache-Control: no-store, and count the reason as a metric label. Keep the reject path tiny: no logging of bodies, no database calls. AWS warns that "it's easy to miss an accidental log statement or a socket setting, which might make dropping a request far more expensive than it needs to be".

Partial results and graceful degradation Important ​

In plain words: Sometimes the best "no" is a smaller "yes".

Common misunderstanding: "Degraded answers hide problems." They are explicit when the response says what is missing, and they keep users working. The SRE book's first option for overload is exactly this: "serve degraded responses: responses that are not as accurate as or that contain less data than normal responses, but that are easier to compute".

Definition: A partial or degraded result replaces an expensive answer with a cheaper one: search a smaller part of the corpus, serve a cached copy, drop optional widgets, return the first page only. It is a form of shedding applied inside the request. Detailed patterns are in Bulkheads & Graceful Degradation.

text
     Load level   Search response
1    normal       full ranking over the whole index, personalised
2    elevated     top 100 candidates only, no personalisation
3    high         cached results from the last minute
4    extreme      503 + Retry-After for SHEDDABLE, cached for the rest

Real scenarios: product pages without recommendations; feeds without ads; search with "results may be incomplete"; dashboards that skip the slowest panel.

ProductDegradation hook
Envoyretry/fallback via route config, custom response on overload
NGINXproxy_cache_use_stale serves stale content on errors
LaravelCache::remember with a stale fallback inside a catch
Gocontext deadline plus a fallback function

Fix / how to use it: make the degraded path a first-class code path with its own tests, because it will run exactly when everything else is failing.

Client cooperation: adaptive throttling, retry budgets, backoff Must-know ​

In plain words: A client that is being refused should send less, not more.

Common misunderstanding: "The server can handle it alone." Rejecting is not free: Google notes that "the backend can become overloaded even though the vast majority of its CPU is spent just rejecting requests". And naive retries multiply the load; the SRE book's worst case is three attempts per request, "somewhere just below 3X".

Definition: Three client-side tools. (1) Adaptive throttling: each client keeps requests and accepts for the last two minutes. Once requests exceed K x accepts it rejects locally with probability max(0, (requests - K x accepts) / (requests + 1)); the book prefers K = 2 and reports "backends end up rejecting one request for each request they actually process". (2) Retry budget: a per-request cap of three attempts and a per-client cap ("A request will only be retried as long as this ratio is below 10%"), which cuts the worst-case growth to "just 1.1x". (3) Honour Retry-After and add jitter (Timeouts, Retries & Jitter). Retry only the layer immediately above the rejecting one, and use an "overloaded; don't retry" answer when the whole fleet is saturated: otherwise "we'd have a combinatorial explosion".

text
     Step   Client                               Server
1    1      GET /x                           ->  503 Retry-After: 2 (overloaded)
2    2      budget ok (retries/requests 4%)
3    3      wait 2 s + jitter, GET /x        ->  503
4    4      budget: 3 attempts spent; return the 503 to the caller
5    5      next requests: requests > 2 x accepts -> 40% rejected locally, no network

Real scenarios: a mobile app retrying at app launch after an outage; a batch client hammering an API with ten parallel workers; a gateway retrying 503s three times per layer.

ProductClient-side mechanism
Envoyretry budgets and max_retries circuit breaker ("we recommend using retry budgets")
gRPCretry policy with throttling (maxTokens, tokenRatio) in service config
Netflixclient-side AIMDLimit or blockOnLimit
Gothis chapter's throttle.Transport
LaravelHttp::retry() with a sleep closure that reads Retry-After and a when: closure backed by a cache budget

Fix / how to use it: throttle.Adaptive, throttle.RetryBudget, throttle.Transport. Only idempotent requests retry; see API Idempotency.

Shedding vs rate limiting vs backpressure Must-know ​

In plain words: Rate limiting enforces fairness against a promise, backpressure slows the sender, shedding protects the receiver when the others were not enough.

Common misunderstanding: "They are the same thing, pick one." They answer different questions and are stacked: a rate limit stops one caller from taking more than its share, backpressure transmits the receiver's pace to the sender, and shedding is the last resort that works even when senders ignore both.

Definition:

Rate limitingBackpressureLoad shedding
QuestionIs this caller within its agreed rate?Can the receiver take more right now?Can this server finish more work in time?
Decided byPolicy (plan, quota)Receiver's capacityServer's own state
SignalCount per identity per windowFull buffer, window, credit, lagIn-flight, queue wait, latency
Typical reply429Block, nack, slow ack, smaller fetch503
Protects againstAbuse, noisy neighbourFast producer, slow consumerSurges, slow dependencies, retries
Needs cooperationClient reads headersSender honours the signalNone: it is unilateral
WhereEdge, gatewayBetween stages and queuesEvery server
text
     Layer                What it stops                 Chapter
1    Rate limit           one caller above its plan     /system-design/rate-limiting-algorithms
2    Backpressure         producer faster than consumer /messaging/backpressure-flow-control
3    Load shedding        aggregate demand above capacity (this chapter)
4    Circuit breaker      calling a failing dependency  /system-design/circuit-breaker

Real scenarios: an API with plan limits (rate limiting) and a database-protecting concurrency limit (shedding); a Kafka consumer pausing partitions when its in-memory buffer is full (backpressure) while the HTTP front is shedding at the edge.

ProductRate limitingBackpressureShedding
NGINXlimit_reqproxy_buffering, limit_ratelimit_conn
Envoyrate-limit filtersflow-control windows, watermark buffersadaptive concurrency, overload manager
RabbitMQnonepublisher confirms, credit flowoverflow=reject-publish, TTL
Kafkaquotas (producer_byte_rate)consumer pull (max.poll.records)retention drop, consumer skips stale
Redis Streamsnoneconsumer reads at its paceMAXLEN/MINID trimming
LaravelRateLimiter, throttle middlewareworker --sleep, --max-jobsShedLoad middleware (this chapter)

Fix / how to use it: stack them in this order of cheapness: identity-based rate limit at the edge, a shedding limit in every service, backpressure on every queue.

Queue-based shedding: TTL, drop-head and reject-publish Important ​

In plain words: A queue is a promise to do work later. If later is too late, throw the message away, and decide whether to throw away the oldest or the newest.

Common misunderstanding: "A queue absorbs any burst, so nothing is ever lost." An unbounded queue only turns an outage of capacity into an outage of freshness; when the backlog is hours long, the consumer works on things nobody needs while new, important messages wait behind them.

Definition: Three levers. Message TTL: the broker or consumer discards messages older than a limit. Drop-head: when the queue is full, discard the oldest; RabbitMQ's documented default, overflow = drop-head ("oldest messages are discarded from the head of the queue"). Reject-publish: when full, refuse the new message; RabbitMQ: "the most recently published messages will be discarded", and with publisher confirms "the publisher will be informed of the reject via a basic.nack". reject-publish-dlx also dead-letters the rejected messages. Drop-head favours freshness and hides the loss from producers; reject-publish keeps old work and pushes back on producers, which is backpressure.

text
     Policy           Queue full, new message M arrives
1    drop-head        oldest message dropped (dead-lettered if DLX set); M enqueued; producer sees success
2    reject-publish   M refused; producer gets nack and must slow or retry; queue untouched
3    TTL              messages older than TTL skipped at the head; broker or consumer frees the slot
4    CoDel            persistent delay above target: head messages dropped until delay recovers

Real scenarios: price updates (only the latest matters: drop-head); payment commands (never silently dropped: reject-publish and slow the producer); notification digests (TTL of ten minutes); telemetry (drop-head, accept loss).

ProductTTLOverflowDead letter
RabbitMQx-message-ttl policy or per-message expiration (lower of the two wins); classic queues expire at the headx-max-length, x-overflow: drop-head (default), reject-publish, reject-publish-dlxDLX on expiry and drop-head
Kafkanone per message; retention.ms / retention.bytes drop whole segmentsnone: producers block or error on max.block.ms / buffer limitsconsumer-side error topic
Redis Streamsnone per entryXADD ... MAXLEN / MINID trims old entriesnone built in
SQSMessageRetentionPeriod (default four days)none: unboundedredrive to a DLQ by maxReceiveCount
Laravel queuesretryUntil(), Skip::when(), --max-timenone built infailed_jobs

Fix / how to use it: msgqueue.Queue models both overflow modes, TTL skip and CoDel with a fake clock; the Laravel job in this chapter expires by age. Rejected and expired messages should land in a dead-letter queue (Dead Letter Queue) so loss is visible.

Shedding and autoscaling Important ​

In plain words: Shedding buys time; scaling buys capacity. They must not hide each other.

Common misunderstanding: "If we shed, CPU stays low, so the autoscaler will do the right thing." The opposite can happen. AWS: "a service is configured for CPU-based reactive scaling and also has load shedding configured to reject requests at a similar CPU target. In this case, the load shedding system will reduce the number of requests to keep the CPU load low, and reactive scaling will never receive or get a delayed signal to launch new instances."

Definition: The two controllers need different triggers. Shed on a fast, local signal (in-flight, queue wait). Scale on a signal that includes the rejected demand: shed rate, offered requests per second, or concurrency including refused attempts. AWS also warns about Availability Zone capacity: with shedding, "a fleet might run much closer to the point at which requests would be rejected than system metrics indicate".

text
     t      Event
1    0 s    Surge begins; in-flight hits the limit; shedding starts (fast loop, seconds)
2    10 s   Shed rate is 30% and rising; CPU is flat at 70% because of shedding
3    30 s   Autoscaler sees shed rate over threshold (not CPU): +4 replicas requested
4    120 s  New replicas pass readiness; the limit per fleet rises; shed rate falls to 0
5    300 s  Surge ends; scale-in after the cool-down

Real scenarios: a Kubernetes HPA on CPU while an NGINX limit_conn caps connections; an ECS service scaling on request count behind an ALB; Octane with a fixed worker count and an HPA that never fires.

ProductScaling signal that survives shedding
Kubernetes HPAcustom or external metric: shed count, in-flight, queue wait (via metrics adapter)
KEDAqueue length or lag scalers
AWS Auto ScalingRequestCountPerTarget, target tracking on a custom shed metric
Envoyupstream_rq_pending_overflow and overload manager stats exported to the scaler
Laravel Horizonbalance: auto scales workers by queue load

Fix / how to use it: export the shed counter per tier, scale on shed_rate > 1% or on queue wait, and see Scaling Strategies. Also check that a failed AZ does not turn into a permanent shedding state.

Where to shed: edge, gateway, service, consumer Important ​

In plain words: Say no as early as you cheaply can, and also say no in the service, because earlier layers know less.

Common misunderstanding: "One layer is enough, put it on the gateway." A gateway sees request counts and identities but not CPU, locks or downstream health. Google's conclusion: "we consider it critical to ensure that individual tasks are protected against overload."

Definition: Each layer has what it knows and what it can do.

ClientEdge / LBAPI gatewayServiceQueue consumerDatabaseAdaptivethrottlingRetry budgetHonourRetry-AfterNGINXlimit_connEnvoy overloadmanagerstop_accepting_requests: 503Per-customerquota: 429Rate limitsEnvoy adaptiveconcurrencyConcurrencylimit (adaptive)Priority tiersQueue-timebudget503 + Retry-AfterMessage TTLreject-publishor drop-headSkip stale jobsDead lettermax_connectionsstatement_timeoutPool sizeLast line ofdefence onlyEarliercheap to refuse, little information (no tier, no cost)Laterknows the tier and cost, but work is already wastedShed at several layers; the service's own limit is the one you cannot skip
LayerKnowsCan doTypical tool
Clientits own recent accept ratethrottle itself, back offadaptive throttling, retry budget
Edge / CDN / LBconnections, IP, request ratereject cheaply, drainNGINX limit_conn, Envoy overload manager, ALB
API gatewayidentity, route, planquota, 429, priority tagKong, Envoy, AWS API Gateway
Servicein-flight, queue wait, tier, downstream healthtiered admission, deadline dropmiddleware in this chapter, Envoy adaptive concurrency
Queue consumermessage age, backlogTTL skip, drop, dead-letterRabbitMQ TTL, Laravel Skip
Databaseconnections, statementsmax_connections, statement_timeoutPostgreSQL, pooler (Connection Pooling)
Orchestratornode memory, disk, PIDsevict podskubelet eviction
text
     Layer      Decision                                  Cost of refusing
1    Client     local throttle at 40% probability         zero network
2    Edge       503 at stop_accepting_requests            one TCP/TLS hop
3    Gateway    429 for tenant over quota                 a lookup
4    Service    503 for SHEDDABLE at 50% of limit         a counter compare
5    Consumer   skip a 20-minute-old job                  a timestamp compare
6    Database   FATAL: sorry, too many clients already    a failed connect (last resort)

Real scenarios: Envoy overload manager at the ingress during a memory spike; NGINX limit_conn on a download location; service-level adaptive limit behind it; a pod evicted for memory pressure while others hold.

ProductSettingEffect
Envoy overload managerenvoy.overload_actions.stop_accepting_requests triggered at heap 95%"Envoy will immediately respond with a 503 response code to new requests"
Envoy overload managerenvoy.overload_actions.disable_http_keepalive at 92%drains HTTP/2 and HTTP/3 with GOAWAY
Envoy load shed pointenvoy.load_shed_points.tcp_listener_acceptstops accepting TCP connections
Kubernetes kubelethard threshold memory.available<100Mi (Linux default)kills pods at once, no grace
Kubernetes kubeletnode condition MemoryPressuretaint, stop scheduling more pods

Kubernetes eviction ranks pods by "whether the pod's resource usage exceeds requests", then Pod Priority, then usage over requests; BestEffort and Burstable pods over their requests go first. It is node-level shedding by killing, not by refusing requests, so it complements, never replaces, application shedding.

Fix / how to use it: one layer at the edge for cheap bulk refusal, one in every service for correctness, one per queue. Use Load Balancing and API Gateway, BFF & Service Mesh for the topology.

Testing and metrics Must-know ​

In plain words: You do not have load shedding until you have watched goodput stay flat under a load test.

Common misunderstanding: "Our load test goes to peak traffic, we are fine." Overload tests must go far beyond the breaking point. AWS: "if they haven't load tested their service to the point where it breaks, and far beyond the point where it breaks, they should assume that the service will fail in the least desirable way possible."

Definition: A shedding test ramps offered load past capacity with a realistic mix of priorities and watches goodput, per-tier success, shed rate and latency of admitted requests. The ideal result is the plateau; the failure is a cliff. Test variants from the same article: fixed fleet versus autoscaling fleet, and "take an existing load generation test or canary, drive sustained load ... but begin removing servers" to raise per-instance load.

text
     Ramp    Offered     Goodput   CRITICAL ok   SHEDDABLE ok   Shed rate   Verdict
1    0.5x    50 /s       50 /s     100%          100%           0%          healthy
2    1.0x    100 /s      100 /s    100%          100%           0%          at capacity
3    2.0x    200 /s      100 /s    100%          ~50%           50%         plateau: pass
4    4.0x    400 /s      100 /s    100%          ~25%           75%         plateau: pass
5    4.0x    400 /s      3 /s      ~0%           ~0%            0%          cliff: no shedding

Real scenarios: k6 or Gatling ramp with a 5/15/30/50% tier mix; removing instances under steady load; a game day that adds latency to a dependency (Chaos Engineering).

MetricWhyLabel
requests_shed_totalthe loss you chosetier, reason (queue_budget, concurrency, quota)
requests_admitted_totaldenominatortier
goodput2xx under the SLO latency per secondtier
concurrency_limitwhat the adaptive algorithm decidedinstance
inflightcurrent useinstance, tier
queue_wait_secondsthe earliest signalquantile
admitted latency histogramdo not mix in refusalssuccess only

AWS's two rules for these: keep the false-positive rate at zero in steady state ("when the service gets it wrong and rejects a request although it has capacity"), and "not to pollute our services' latency metrics with failed request latency", because shedding 60% of traffic can make median latency look wonderful. Alert on shed rate by tier, not on its existence (Alerting That Actually Works, Observability, SLOs).

Fix / how to use it: the simulator in the lab is the unit-test version; production needs the load-test version with real dependencies.

Mechanics ​

The numbers ​

Little's Law, in-flight = arrival rate x time in system, ties the pieces together. For a service with 10 workers and 100 ms of work per request:

QuantityValueMeaning
Capacity10 / 0.1 s = 100 req/sthe plateau of goodput
In-flight at capacity100 x 0.1 = 10equals the worker count
Limit 2010 running + 10 queuedworst-case wait about 100 ms, latency about 200 ms
Limit 20010 running + 190 queuedworst-case wait about 1.9 s: above a 1 s client timeout
Offered 300 req/s, no sheddingqueue grows 200/safter 10 s the queue is 2000 deep: 20 s wait
With shedding at 300 req/s200 req/s refusedadmitted latency stays at 100 to 200 ms

Knobs by product ​

ProductSettingDefaultEffect
NGINXlimit_conn zone numbernonemax concurrent connections per key; HTTP/2 and HTTP/3 count each request as a connection
NGINXlimit_conn_status503status for refused requests
NGINXlimit_conn_dry_run on (1.17.6)offcount excess without refusing
NGINXlimit_req zone burst= nodelaynonerate per key; limit_req_status default 503
NGINXlimit_conn_zone $binary_remote_addr zone=addr:10mnone4 bytes per IPv4 key, 16 for IPv6; the docs: one megabyte holds about 32 thousand 32-byte states or about 16 thousand 64-byte states, and when the zone is exhausted "the server will return the error to all further requests"
HAProxytimeout queuesame as timeout connect if unsetmax wait for a server slot, then 503
HAProxyserver maxconn, maxqueuenoneslots and queue length per server
Envoyadaptive_concurrency gradient controllerfilter off unless configuredconcurrency_update_interval, min_concurrency_limit, max_concurrency_limit (1000), sample_aggregate_percentile, min_rtt_calc_params (interval, request_count, jitter, buffer)
Envoyoverload manager refresh_interval, resource_monitors, actionsnonefixed_heap, cgroup_memory; actions stop_accepting_requests, disable_http_keepalive, reduce_timeouts, reset_high_memory_stream
Envoycircuit breakersper clustermax connections, pending requests, requests, retries
KubernetesevictionHardmemory.available<100Mi, nodefs.available<10%, imagefs.available<15%, nodefs.inodesFree<5%kubelet kills pods when crossed
KubernetesevictionSoft + grace periodnonegraceful eviction
RabbitMQx-max-length, x-overflow, x-message-ttldrop-headqueue size and age limits
Laravel Octane--workers, --max-requests (500), max_execution_time (30)one worker per CPU coreworker count is the in-flight limit
Laravel queuesretryUntil(), Skip::when(), retry_afterretry_after 90 on the redis driverjob age and lifetime

Error messages and codes you will meet ​

WhereText or codeMeaning
HTTP503 Service Unavailable with Retry-Aftershed
HTTP429 Too Many Requestscaller over quota
NGINX error loglimiting connections by zone "addr" (level from limit_conn_log_level, default error)limit_conn refused a request
NGINX error loglimiting requests, excess: 5.420 by zone "one"limit_req refused a request
HAProxysQ termination stateclient waited in the queue and timed out
Envoyupstream_rq_pending_overflow, upstream_rq_active_overflow, upstream_cx_overflow counterscircuit breaker overflow
Envoyresponse flag UOupstream overflow
AMQPbasic.nack after reject-publishqueue full
PostgreSQLFATAL: sorry, too many clients alreadymax_connections reached
Kubernetesnode condition MemoryPressure, kubelet taintthe node is under memory pressure and evicts pods

The next three sections are the code. Everything under docs/snippets/system-design/load-shedding/ compiles, vets and tests (Go) and passes php -l (PHP).

Go ​

Example: an adaptive limiter, priority middleware, client throttle and a simulator ​

The module academy/load-shedding has six small packages. Algorithms first: three limit estimators behind one interface.

go
// Package limit holds concurrency-limit algorithms. Each one answers a single
// question: given what finished recently, how many requests may be in flight?
package limit

import (
	"math"
	"sync"
	"time"
)

// Sample describes one finished request.
type Sample struct {
	RTT      time.Duration // time from admission to completion, queueing included
	Inflight int           // requests in flight when this one was admitted
	Dropped  bool          // timeout, 503 from downstream or other loss signal
}

// Algorithm is a pluggable limit estimator.
type Algorithm interface {
	Limit() int
	OnSample(Sample)
}

func clampInt(v, lo, hi int) int {
	if v < lo {
		return lo
	}
	if v > hi {
		return hi
	}
	return v
}

// Fixed never changes: the static concurrency limit.
type Fixed struct{ N int }

func (f Fixed) Limit() int      { return f.N }
func (f Fixed) OnSample(Sample) {}

// AIMD is loss based, like TCP: add one on success when the limit is really
// being used, multiply by Backoff when a request is dropped.
type AIMD struct {
	mu       sync.Mutex
	limit    float64
	Min, Max int
	Backoff  float64 // for example 0.9
}

func NewAIMD(initial, min, max int, backoff float64) *AIMD {
	return &AIMD{limit: float64(initial), Min: min, Max: max, Backoff: backoff}
}

func (a *AIMD) Limit() int {
	a.mu.Lock()
	defer a.mu.Unlock()
	return clampInt(int(a.limit), a.Min, a.Max)
}

func (a *AIMD) OnSample(s Sample) {
	a.mu.Lock()
	defer a.mu.Unlock()
	switch {
	case s.Dropped:
		a.limit = math.Max(float64(a.Min), a.limit*a.Backoff)
	case float64(s.Inflight)*2 >= a.limit:
		a.limit = math.Min(float64(a.Max), a.limit+1)
	}
}

// window collects RTT samples and releases one summary per N samples.
type window struct {
	n, count int
	sum      time.Duration
	maxIn    int
	dropped  bool
}

func (w *window) add(s Sample) (avg time.Duration, maxInflight int, dropped, full bool) {
	w.count++
	w.sum += s.RTT
	if s.Inflight > w.maxIn {
		w.maxIn = s.Inflight
	}
	w.dropped = w.dropped || s.Dropped
	if w.count < w.n {
		return 0, 0, false, false
	}
	avg, maxInflight, dropped = w.sum/time.Duration(w.count), w.maxIn, w.dropped
	*w = window{n: w.n}
	return avg, maxInflight, dropped, true
}

// Vegas is delay based. The estimated queue is limit * (1 - minRTT/sampleRTT).
// Below Alpha the limit grows by one, above Beta it shrinks by one. Netflix's
// README gives alpha 2-3 and beta 4-6 as typical values.
type Vegas struct {
	mu          sync.Mutex
	limit       float64
	minRTT      time.Duration
	w           window
	Min, Max    int
	Alpha, Beta float64
}

func NewVegas(initial, min, max, windowSize int) *Vegas {
	return &Vegas{limit: float64(initial), Min: min, Max: max, Alpha: 3, Beta: 6, w: window{n: windowSize}}
}

func (v *Vegas) Limit() int {
	v.mu.Lock()
	defer v.mu.Unlock()
	return clampInt(int(v.limit), v.Min, v.Max)
}

func (v *Vegas) OnSample(s Sample) {
	v.mu.Lock()
	defer v.mu.Unlock()
	if s.RTT > 0 && (v.minRTT == 0 || s.RTT < v.minRTT) {
		v.minRTT = s.RTT
	}
	avg, maxIn, dropped, full := v.w.add(s)
	if !full || avg <= 0 || v.minRTT <= 0 {
		return
	}
	if dropped {
		v.limit = math.Max(float64(v.Min), v.limit*0.9)
		return
	}
	queue := v.limit * (1 - float64(v.minRTT)/float64(avg))
	switch {
	case queue < v.Alpha && float64(maxIn)*2 >= v.limit:
		v.limit = math.Min(float64(v.Max), v.limit+1)
	case queue > v.Beta:
		v.limit = math.Max(float64(v.Min), v.limit-1)
	}
}

// Gradient follows Envoy's gradient controller:
// gradient = (minRTT + B) / sampleRTT, limit' = gradient*limit + sqrt(limit),
// where B = minRTT * Buffer. We clamp the gradient to [0.5, 1.0] (our choice)
// so one noisy window cannot halve the limit twice in a row.
type Gradient struct {
	mu       sync.Mutex
	limit    float64
	minRTT   time.Duration
	w        window
	Min, Max int
	Buffer   float64 // fraction of minRTT tolerated before the gradient drops
}

func NewGradient(initial, min, max, windowSize int, buffer float64) *Gradient {
	return &Gradient{limit: float64(initial), Min: min, Max: max, Buffer: buffer, w: window{n: windowSize}}
}

func (g *Gradient) Limit() int {
	g.mu.Lock()
	defer g.mu.Unlock()
	return clampInt(int(g.limit), g.Min, g.Max)
}

// ResetMinRTT forgets the baseline. Envoy re-measures minRTT on a timer
// (min_rtt_calc_params.interval) for the same reason: the "ideal" latency drifts.
func (g *Gradient) ResetMinRTT() {
	g.mu.Lock()
	g.minRTT = 0
	g.mu.Unlock()
}

func (g *Gradient) OnSample(s Sample) {
	g.mu.Lock()
	defer g.mu.Unlock()
	if s.RTT > 0 && (g.minRTT == 0 || s.RTT < g.minRTT) {
		g.minRTT = s.RTT
	}
	avg, maxIn, dropped, full := g.w.add(s)
	if !full || avg <= 0 || g.minRTT <= 0 {
		return
	}
	if dropped {
		g.limit = math.Max(float64(g.Min), g.limit*0.9)
		return
	}
	b := float64(g.minRTT) * g.Buffer
	gradient := (float64(g.minRTT) + b) / float64(avg)
	gradient = math.Max(0.5, math.Min(1.0, gradient))
	next := gradient*g.limit + math.Sqrt(g.limit)
	if gradient == 1.0 && float64(maxIn)*2 < g.limit {
		next = g.limit // not using the limit: do not grow it
	}
	g.limit = math.Max(float64(g.Min), math.Min(float64(g.Max), next))
}

The limiter counts requests in flight and feeds each finished request's latency back to the algorithm. Acquire(fraction) is where tiers become behaviour: a lower tier passes a smaller fraction and runs into the ceiling first.

go
// Package limiter enforces a concurrency limit: it counts requests in flight
// and refuses new ones once the algorithm's current limit is reached.
package limiter

import (
	"math"
	"sync"
	"time"

	"academy/load-shedding/clock"
	"academy/load-shedding/limit"
)

// Outcome tells the algorithm how a request ended.
type Outcome int

const (
	// Success: finished with a useful answer in time.
	Success Outcome = iota
	// Dropped: timed out or failed because of overload (a loss signal).
	Dropped
	// Ignore: carries no latency information (client error, cancelled early).
	Ignore
)

// Limiter is safe for concurrent use.
type Limiter struct {
	alg limit.Algorithm
	clk clock.Clock

	mu       sync.Mutex
	inflight int
}

func New(alg limit.Algorithm, clk clock.Clock) *Limiter {
	return &Limiter{alg: alg, clk: clk}
}

// Token is the permit for one admitted request. Release it exactly once.
type Token struct {
	l        *Limiter
	start    time.Time
	inflight int
	done     bool
}

// Acquire admits a request when inflight is below fraction*limit. Critical
// traffic passes fraction 1.0, sheddable traffic a smaller one, so lower tiers
// are refused first while the shared limit still adapts.
func (l *Limiter) Acquire(fraction float64) (*Token, bool) {
	cap := int(math.Ceil(float64(l.alg.Limit()) * fraction))
	if cap < 1 {
		cap = 1
	}
	l.mu.Lock()
	defer l.mu.Unlock()
	if l.inflight >= cap {
		return nil, false
	}
	l.inflight++
	return &Token{l: l, start: l.clk.Now(), inflight: l.inflight}, true
}

// Release returns the permit and feeds the measured latency to the algorithm.
func (t *Token) Release(o Outcome) {
	if t.done {
		return
	}
	t.done = true
	rtt := t.l.clk.Now().Sub(t.start)
	t.l.mu.Lock()
	t.l.inflight--
	t.l.mu.Unlock()
	if o != Ignore {
		t.l.alg.OnSample(limit.Sample{RTT: rtt, Inflight: t.inflight, Dropped: o == Dropped})
	}
}

// Inflight is the current number of admitted requests.
func (l *Limiter) Inflight() int {
	l.mu.Lock()
	defer l.mu.Unlock()
	return l.inflight
}

// Limit is the algorithm's current limit.
func (l *Limiter) Limit() int { return l.alg.Limit() }

Tiers and X-Request-Start parsing:

go
// Package shed is net/http middleware that drops work on purpose: by queue
// age, by priority tier against an adaptive concurrency limit, and by
// per-customer in-flight quota.
package shed

import "strings"

// Tier mirrors the four criticality values in Google's SRE book, chapter 21.
type Tier int

const (
	CriticalPlus  Tier = iota // user-visible impact if it fails, shed last
	Critical                  // default for production traffic
	SheddablePlus             // batch: partial unavailability expected
	Sheddable                 // frequent partial unavailability expected
)

var names = [...]string{"CRITICAL_PLUS", "CRITICAL", "SHEDDABLE_PLUS", "SHEDDABLE"}

func (t Tier) String() string {
	if t < 0 || int(t) >= len(names) {
		return "UNKNOWN"
	}
	return names[t]
}

// ParseTier reads a header value. Unknown or missing values become Critical,
// the safe default: never shed traffic nobody labelled.
func ParseTier(v string) Tier {
	switch strings.ToUpper(strings.TrimSpace(v)) {
	case "CRITICAL_PLUS":
		return CriticalPlus
	case "SHEDDABLE_PLUS":
		return SheddablePlus
	case "SHEDDABLE":
		return Sheddable
	default:
		return Critical
	}
}

// DefaultThresholds is the share of the concurrency limit each tier may use.
var DefaultThresholds = [4]float64{1.0, 0.9, 0.7, 0.5}
go
package shed

import (
	"strconv"
	"strings"
	"time"
)

// ParseRequestStart reads an X-Request-Start value written by a proxy.
// Accepted forms: "t=1700000000.123" (NGINX: "t=$msec"), "1700000000123"
// (Heroku: unix milliseconds) and "t=1700000000123456" (microseconds).
// The unit is guessed from the magnitude; ok is false when it cannot be read.
func ParseRequestStart(v string) (t time.Time, ok bool) {
	v = strings.TrimPrefix(strings.TrimSpace(v), "t=")
	f, err := strconv.ParseFloat(v, 64)
	if err != nil || f <= 0 {
		return time.Time{}, false
	}
	switch {
	case f >= 1e15: // microseconds
		return time.UnixMicro(int64(f)), true
	case f >= 1e11: // milliseconds
		return time.UnixMilli(int64(f)), true
	default: // seconds with a fraction
		sec := int64(f)
		return time.Unix(sec, int64((f-float64(sec))*1e9)), true
	}
}

The middleware applies three checks in order (queue budget, customer quota, tier share of the adaptive limit), answers 503 or 429 with Retry-After, and feeds the outcome back:

go
package shed

import (
	"context"
	"errors"
	"net/http"
	"strconv"
	"sync"
	"sync/atomic"
	"time"

	"academy/load-shedding/clock"
	"academy/load-shedding/limiter"
)

// Reason says why a request was refused. It becomes a metric label.
type Reason string

const (
	ReasonQueueBudget Reason = "queue_budget" // waited too long before reaching us
	ReasonConcurrency Reason = "concurrency"  // tier threshold of the adaptive limit
	ReasonQuota       Reason = "quota"        // per-customer in-flight cap
)

// Config wires the middleware. Zero values are filled by New.
type Config struct {
	Limiter     *limiter.Limiter
	Clock       clock.Clock
	Thresholds  [4]float64       // share of the limit per tier
	QueueBudget [4]time.Duration // max age per tier; 0 disables the check
	Classify    func(*http.Request) Tier
	// Customer returns the quota key (API key, tenant id); empty skips the quota.
	Customer    func(*http.Request) string
	CustomerMax int
	// RetryAfter is the whole-second hint sent with every refusal. Add jitter
	// here in production so refused clients do not return in lockstep.
	RetryAfter func(Tier, Reason) time.Duration
}

// Stats counts decisions per tier. Goodput is a separate metric: it is
// "answered in time", which only the client or a latency histogram can tell.
type Stats struct {
	admitted [4]atomic.Int64
	shed     [4][3]atomic.Int64
}

var reasonIndex = map[Reason]int{ReasonQueueBudget: 0, ReasonConcurrency: 1, ReasonQuota: 2}

func (s *Stats) Admitted(t Tier) int64 { return s.admitted[t].Load() }

func (s *Stats) Shed(t Tier, r Reason) int64 { return s.shed[t][reasonIndex[r]].Load() }

// Middleware is the shedding gate.
type Middleware struct {
	cfg   Config
	Stats Stats

	mu       sync.Mutex
	perOwner map[string]int
}

func New(cfg Config) *Middleware {
	if cfg.Clock == nil {
		cfg.Clock = clock.Real{}
	}
	if cfg.Thresholds == ([4]float64{}) {
		cfg.Thresholds = DefaultThresholds
	}
	if cfg.Classify == nil {
		cfg.Classify = func(r *http.Request) Tier { return ParseTier(r.Header.Get("X-Priority")) }
	}
	if cfg.RetryAfter == nil {
		cfg.RetryAfter = func(Tier, Reason) time.Duration { return time.Second }
	}
	return &Middleware{cfg: cfg, perOwner: map[string]int{}}
}

// Handler wraps next.
func (m *Middleware) Handler(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		tier := m.cfg.Classify(r)

		// 1. Queue-time budget: a request that already waited past its budget
		//    is probably abandoned by the client; serving it is wasted work.
		if budget := m.cfg.QueueBudget[tier]; budget > 0 {
			if start, ok := ParseRequestStart(r.Header.Get("X-Request-Start")); ok {
				if m.cfg.Clock.Now().Sub(start) > budget {
					m.refuse(w, tier, ReasonQueueBudget, http.StatusServiceUnavailable)
					return
				}
			}
		}

		// 2. Per-customer quota: one noisy customer gets 429, others are untouched.
		if m.cfg.Customer != nil && m.cfg.CustomerMax > 0 {
			if key := m.cfg.Customer(r); key != "" {
				if !m.takeQuota(key) {
					m.refuse(w, tier, ReasonQuota, http.StatusTooManyRequests)
					return
				}
				defer m.returnQuota(key)
			}
		}

		// 3. Adaptive concurrency limit, with a lower ceiling for lower tiers.
		tok, ok := m.cfg.Limiter.Acquire(m.cfg.Thresholds[tier])
		if !ok {
			m.refuse(w, tier, ReasonConcurrency, http.StatusServiceUnavailable)
			return
		}
		m.Stats.admitted[tier].Add(1)

		rec := &statusRecorder{ResponseWriter: w, status: http.StatusOK}
		next.ServeHTTP(rec, r)

		switch {
		case rec.status == http.StatusServiceUnavailable || rec.status == http.StatusGatewayTimeout ||
			errors.Is(r.Context().Err(), context.DeadlineExceeded):
			tok.Release(limiter.Dropped)
		case rec.status >= 400 && rec.status < 500:
			tok.Release(limiter.Ignore) // client errors say nothing about capacity
		default:
			tok.Release(limiter.Success)
		}
	})
}

func (m *Middleware) refuse(w http.ResponseWriter, t Tier, why Reason, code int) {
	m.Stats.shed[t][reasonIndex[why]].Add(1)
	secs := int((m.cfg.RetryAfter(t, why) + time.Second - 1) / time.Second)
	if secs < 1 {
		secs = 1
	}
	w.Header().Set("Retry-After", strconv.Itoa(secs))
	w.Header().Set("X-Shed-Reason", string(why))
	w.Header().Set("Cache-Control", "no-store")
	http.Error(w, http.StatusText(code), code)
}

func (m *Middleware) takeQuota(key string) bool {
	m.mu.Lock()
	defer m.mu.Unlock()
	if m.perOwner[key] >= m.cfg.CustomerMax {
		return false
	}
	m.perOwner[key]++
	return true
}

func (m *Middleware) returnQuota(key string) {
	m.mu.Lock()
	defer m.mu.Unlock()
	if m.perOwner[key]--; m.perOwner[key] <= 0 {
		delete(m.perOwner, key)
	}
}

type statusRecorder struct {
	http.ResponseWriter
	status int
}

func (s *statusRecorder) WriteHeader(code int) {
	s.status = code
	s.ResponseWriter.WriteHeader(code)
}

Its tests use a fake clock and httptest; the tier test holds five requests in flight and checks that SHEDDABLE is refused while CRITICAL_PLUS is still admitted:

go
package shed

import (
	"net/http"
	"net/http/httptest"
	"strconv"
	"testing"
	"time"

	"academy/load-shedding/clock"
	"academy/load-shedding/limit"
	"academy/load-shedding/limiter"
)

func newMW(t *testing.T, limitN int, clk clock.Clock) *Middleware {
	t.Helper()
	cfg := Config{
		Limiter: limiter.New(limit.Fixed{N: limitN}, clk),
		Clock:   clk,
	}
	for i := range cfg.QueueBudget {
		cfg.QueueBudget[i] = 500 * time.Millisecond
	}
	return New(cfg)
}

func req(tier string, mutate func(*http.Request)) *http.Request {
	r := httptest.NewRequest(http.MethodGet, "/x", nil)
	r.Header.Set("X-Priority", tier)
	if mutate != nil {
		mutate(r)
	}
	return r
}

func TestStaleRequestIsShedWith503AndRetryAfter(t *testing.T) {
	now := time.Unix(1_700_000_000, 0)
	clk := clock.NewFake(now)
	mw := newMW(t, 10, clk)
	called := false
	h := mw.Handler(http.HandlerFunc(func(http.ResponseWriter, *http.Request) { called = true }))

	stale := strconv.FormatInt(now.Add(-2*time.Second).UnixMilli(), 10) // waited 2s, budget 500ms
	rec := httptest.NewRecorder()
	h.ServeHTTP(rec, req("CRITICAL", func(r *http.Request) { r.Header.Set("X-Request-Start", stale) }))

	if rec.Code != http.StatusServiceUnavailable {
		t.Fatalf("status %d, want 503", rec.Code)
	}
	if rec.Header().Get("Retry-After") != "1" {
		t.Fatalf("Retry-After %q, want 1", rec.Header().Get("Retry-After"))
	}
	if called {
		t.Fatal("handler must not run for a stale request")
	}
	if mw.Stats.Shed(Critical, ReasonQueueBudget) != 1 {
		t.Fatal("queue_budget counter not incremented")
	}
}

func TestFreshRequestPasses(t *testing.T) {
	now := time.Unix(1_700_000_000, 0)
	mw := newMW(t, 10, clock.NewFake(now))
	h := mw.Handler(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(204) }))
	rec := httptest.NewRecorder()
	fresh := "t=" + strconv.FormatFloat(float64(now.Add(-50*time.Millisecond).UnixMilli())/1000, 'f', 3, 64)
	h.ServeHTTP(rec, req("SHEDDABLE", func(r *http.Request) { r.Header.Set("X-Request-Start", fresh) }))
	if rec.Code != 204 {
		t.Fatalf("status %d, want 204", rec.Code)
	}
}

// With limit 10 and thresholds 1.0/0.9/0.7/0.5, five in-flight requests fill
// the SHEDDABLE share while CRITICAL_PLUS can still use the whole limit.
func TestLowerTiersAreShedFirst(t *testing.T) {
	clk := clock.NewFake(time.Unix(1_700_000_000, 0))
	mw := newMW(t, 10, clk)
	release := make(chan struct{})
	entered := make(chan struct{}, 16)
	h := mw.Handler(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {
		entered <- struct{}{}
		<-release
	}))

	for i := 0; i < 5; i++ {
		go h.ServeHTTP(httptest.NewRecorder(), req("CRITICAL", nil))
	}
	for i := 0; i < 5; i++ {
		<-entered
	}

	rec := httptest.NewRecorder()
	h.ServeHTTP(rec, req("SHEDDABLE", nil))
	if rec.Code != 503 || rec.Header().Get("X-Shed-Reason") != "concurrency" {
		t.Fatalf("SHEDDABLE: %d %q, want 503 concurrency", rec.Code, rec.Header().Get("X-Shed-Reason"))
	}
	go h.ServeHTTP(httptest.NewRecorder(), req("CRITICAL_PLUS", nil)) // admitted: 5 < 10
	<-entered
	close(release)
}

func TestPerCustomerQuotaReturns429(t *testing.T) {
	clk := clock.NewFake(time.Unix(1_700_000_000, 0))
	mw := newMW(t, 100, clk)
	mw.cfg.Customer = func(r *http.Request) string { return r.Header.Get("X-Api-Key") }
	mw.cfg.CustomerMax = 1
	release := make(chan struct{})
	entered := make(chan struct{}, 4)
	h := mw.Handler(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {
		entered <- struct{}{}
		<-release
	}))
	withKey := func(k string) *http.Request {
		return req("CRITICAL", func(r *http.Request) { r.Header.Set("X-Api-Key", k) })
	}
	go h.ServeHTTP(httptest.NewRecorder(), withKey("noisy"))
	<-entered

	rec := httptest.NewRecorder()
	h.ServeHTTP(rec, withKey("noisy"))
	if rec.Code != http.StatusTooManyRequests {
		t.Fatalf("noisy customer: %d, want 429", rec.Code)
	}
	go h.ServeHTTP(httptest.NewRecorder(), withKey("quiet"))
	<-entered // other customers are unaffected
	close(release)
}

func TestParseRequestStart(t *testing.T) {
	want := time.UnixMilli(1_700_000_000_123)
	for _, in := range []string{"1700000000123", "t=1700000000.123", "t=1700000000123000"} {
		got, ok := ParseRequestStart(in)
		if !ok || got.Sub(want).Abs() > time.Millisecond {
			t.Errorf("%q -> %v %v, want %v", in, got, ok, want)
		}
	}
	if _, ok := ParseRequestStart("garbage"); ok {
		t.Error("garbage must not parse")
	}
}

func TestParseTierDefaultsToCritical(t *testing.T) {
	if ParseTier("") != Critical || ParseTier("nonsense") != Critical {
		t.Fatal("unlabelled traffic must default to CRITICAL")
	}
	if ParseTier("sheddable") != Sheddable {
		t.Fatal("case-insensitive parse failed")
	}
}

The client half: adaptive throttling (Google SRE book formula), a retry budget, and a RoundTripper that honours Retry-After, never retries a POST and stops at three attempts.

go
// Package throttle is the client half of load shedding: adaptive throttling
// (Google SRE book, chapter 21) and a retry budget, so a client that is being
// refused backs off by itself instead of adding to the overload.
package throttle

import (
	"sync"
	"time"

	"academy/load-shedding/clock"
)

// counts is a sliding window of per-second buckets.
type counts struct {
	mu      sync.Mutex
	clk     clock.Clock
	buckets []bucket
}

type bucket struct {
	sec            int64
	requests, accs int64
}

func newCounts(clk clock.Clock, window time.Duration) *counts {
	return &counts{clk: clk, buckets: make([]bucket, int(window/time.Second))}
}

func (c *counts) add(requests, accepts int64) {
	sec := c.clk.Now().Unix()
	c.mu.Lock()
	defer c.mu.Unlock()
	b := &c.buckets[int(sec%int64(len(c.buckets)))]
	if b.sec != sec {
		*b = bucket{sec: sec}
	}
	b.requests += requests
	b.accs += accepts
}

func (c *counts) sum() (requests, accepts int64) {
	now := c.clk.Now().Unix()
	c.mu.Lock()
	defer c.mu.Unlock()
	for _, b := range c.buckets {
		if now-b.sec < int64(len(c.buckets)) && b.sec <= now {
			requests += b.requests
			accepts += b.accs
		}
	}
	return
}

// Adaptive implements client-side adaptive throttling. Over the last
// Window it counts requests (attempted by the application, including those
// refused locally) and accepts (admitted by the backend). Once requests exceed
// K*accepts the client rejects new requests locally with probability
// max(0, (requests - K*accepts) / (requests + 1)).
type Adaptive struct {
	K float64
	c *counts
}

// NewAdaptive uses a two-minute window like the SRE book; K=2 is the book's
// preferred multiplier, lower values throttle harder.
func NewAdaptive(clk clock.Clock, k float64) *Adaptive {
	return &Adaptive{K: k, c: newCounts(clk, 2*time.Minute)}
}

// RejectProbability is the current local rejection probability.
func (a *Adaptive) RejectProbability() float64 {
	req, acc := a.c.sum()
	p := (float64(req) - a.K*float64(acc)) / float64(req+1)
	if p < 0 {
		return 0
	}
	return p
}

// Allow records an attempt and decides locally. u is a uniform random number
// in [0,1); it is a parameter so tests are deterministic.
func (a *Adaptive) Allow(u float64) bool {
	p := a.RejectProbability()
	a.c.add(1, 0)
	return u >= p
}

// Accepted records that the backend admitted a request.
func (a *Adaptive) Accepted() { a.c.add(0, 1) }

// RetryBudget allows a retry only while retries stay below Ratio of all
// requests in the window (the SRE book uses 10%), plus a small floor so a
// quiet client can still retry its first failures.
type RetryBudget struct {
	Ratio float64
	Floor int64
	c     *counts
}

func NewRetryBudget(clk clock.Clock, ratio float64, floor int64) *RetryBudget {
	return &RetryBudget{Ratio: ratio, Floor: floor, c: newCounts(clk, time.Minute)}
}

// OnRequest counts a first attempt.
func (b *RetryBudget) OnRequest() { b.c.add(1, 0) }

// TryRetry spends one retry if the budget allows it.
func (b *RetryBudget) TryRetry() bool {
	req, retries := b.c.sum()
	if retries >= b.Floor && float64(retries+1) > b.Ratio*float64(req) {
		return false
	}
	b.c.add(0, 1)
	return true
}
go
package throttle

import (
	"context"
	"errors"
	"net/http"
	"strconv"
	"time"
)

// ErrThrottled is returned without touching the network.
var ErrThrottled = errors.New("throttle: rejected locally, backend is refusing too much")

// MaxAttempts is the per-request cap (SRE book: up to three attempts).
const MaxAttempts = 3

// Transport wraps a RoundTripper with adaptive throttling, a retry budget and
// Retry-After handling. Only idempotent requests with a replayable body retry.
type Transport struct {
	Base     http.RoundTripper
	Throttle *Adaptive
	Budget   *RetryBudget
	Rand     func() float64                                   // uniform [0,1)
	Sleep    func(ctx context.Context, d time.Duration) error // injected for tests
	MaxWait  time.Duration                                    // cap on honouring Retry-After
}

func (t *Transport) RoundTrip(req *http.Request) (*http.Response, error) {
	t.Budget.OnRequest()
	for attempt := 1; ; attempt++ {
		if !t.Throttle.Allow(t.Rand()) {
			return nil, ErrThrottled
		}
		resp, err := t.Base.RoundTrip(req)
		refused := err == nil && (resp.StatusCode == http.StatusServiceUnavailable || resp.StatusCode == http.StatusTooManyRequests)
		if !refused {
			if err == nil {
				t.Throttle.Accepted()
			}
			return resp, err
		}
		if !retryable(req) || attempt >= MaxAttempts || resp.Header.Get("X-Overloaded-Dont-Retry") != "" || !t.Budget.TryRetry() {
			return resp, nil // surface the 503/429 to the caller
		}
		wait := retryAfter(resp, t.MaxWait)
		resp.Body.Close()
		if err := t.Sleep(req.Context(), wait); err != nil {
			return nil, err
		}
		if req.GetBody != nil {
			body, err := req.GetBody()
			if err != nil {
				return nil, err
			}
			req = req.Clone(req.Context())
			req.Body = body
		}
	}
}

func retryable(r *http.Request) bool {
	switch r.Method {
	case http.MethodGet, http.MethodHead, http.MethodOptions, http.MethodPut, http.MethodDelete:
	default:
		return false
	}
	return r.Body == nil || r.Body == http.NoBody || r.GetBody != nil
}

// retryAfter reads the delay-seconds form of Retry-After (RFC 9110, 10.2.3);
// the HTTP-date form is ignored here for brevity.
func retryAfter(resp *http.Response, max time.Duration) time.Duration {
	secs, err := strconv.Atoi(resp.Header.Get("Retry-After"))
	if err != nil || secs < 0 {
		return 0
	}
	d := time.Duration(secs) * time.Second
	if max > 0 && d > max {
		return max
	}
	return d
}

An in-process queue with both overflow modes, TTL skip and a simplified CoDel:

go
// Package msgqueue is a bounded in-memory queue that sheds on purpose:
// it can reject new messages or drop the oldest when full, expire messages by
// TTL, and drop on persistent queue delay (a simplified CoDel).
package msgqueue

import (
	"errors"
	"sync"
	"time"

	"academy/load-shedding/clock"
)

// Overflow is what happens when the queue is full.
type Overflow int

const (
	// RejectPublish refuses the new message (RabbitMQ overflow=reject-publish):
	// the producer learns about it and can slow down. This is backpressure.
	RejectPublish Overflow = iota
	// DropHead discards the oldest message to make room (RabbitMQ's default,
	// overflow=drop-head): the queue stays fresh, producers never find out.
	DropHead
)

// ErrFull is returned by Push under RejectPublish.
var ErrFull = errors.New("msgqueue: full, message rejected")

// Message carries its own enqueue time and TTL.
type Message struct {
	ID       string
	Body     []byte
	TTL      time.Duration // 0 means no expiry
	Enqueued time.Time
}

// DeadLetter receives every message the queue discards, with the reason
// ("expired", "dropped_head", "codel"). Wire it to a dead-letter queue or just count.
type DeadLetter func(m Message, reason string)

// Queue is safe for concurrent use.
type Queue struct {
	max      int
	overflow Overflow
	clk      clock.Clock
	dead     DeadLetter
	codel    *CoDel

	mu   sync.Mutex
	msgs []Message
}

func New(max int, overflow Overflow, clk clock.Clock, dead DeadLetter, codel *CoDel) *Queue {
	if dead == nil {
		dead = func(Message, string) {}
	}
	return &Queue{max: max, overflow: overflow, clk: clk, dead: dead, codel: codel}
}

// Push enqueues m.
func (q *Queue) Push(m Message) error {
	q.mu.Lock()
	defer q.mu.Unlock()
	if len(q.msgs) >= q.max {
		if q.overflow == RejectPublish {
			return ErrFull
		}
		q.dead(q.msgs[0], "dropped_head")
		q.msgs = q.msgs[1:]
	}
	m.Enqueued = q.clk.Now()
	q.msgs = append(q.msgs, m)
	return nil
}

// Pop returns the next message worth processing. Expired messages and
// messages CoDel decides to drop are dead-lettered and skipped: a consumer
// never wastes time on work the sender has already given up on.
func (q *Queue) Pop() (Message, bool) {
	q.mu.Lock()
	defer q.mu.Unlock()
	for len(q.msgs) > 0 {
		m := q.msgs[0]
		q.msgs = q.msgs[1:]
		now := q.clk.Now()
		if m.TTL > 0 && now.Sub(m.Enqueued) > m.TTL {
			q.dead(m, "expired")
			continue
		}
		if q.codel != nil && q.codel.ShouldDrop(now, now.Sub(m.Enqueued)) {
			q.dead(m, "codel")
			continue
		}
		return m, true
	}
	return Message{}, false
}

// Len is the number of queued messages.
func (q *Queue) Len() int {
	q.mu.Lock()
	defer q.mu.Unlock()
	return len(q.msgs)
}
go
package msgqueue

import "time"

// CoDel is a simplified controlled-delay gate. RFC 8289 describes the full
// algorithm for network packets: an estimator (sojourn time, the time a unit
// spent in the buffer), a setpoint (TARGET, 5 ms in the RFC) and a control
// loop (INTERVAL, 100 ms in the RFC). We keep the estimator and the setpoint:
// delay above Target that lasts for a whole Interval means a standing queue,
// and from then on every item older than Target is dropped until delay falls
// back under Target. The RFC's drop-rate control law (interval / sqrt(count))
// is left out. For a service queue pick Target near a small multiple of the
// service time, not the RFC's network values.
type CoDel struct {
	Target   time.Duration
	Interval time.Duration

	firstAbove time.Time
	dropping   bool
}

func (c *CoDel) ShouldDrop(now time.Time, sojourn time.Duration) bool {
	if sojourn < c.Target {
		c.firstAbove = time.Time{}
		c.dropping = false
		return false
	}
	if c.firstAbove.IsZero() {
		c.firstAbove = now.Add(c.Interval) // start the clock; a burst is allowed
		return false
	}
	if now.Before(c.firstAbove) {
		return false
	}
	c.dropping = true
	return true
}

Finally the simulator that produces the lab numbers: 10 servers, 100 ms service, 1 s client timeout, five admission policies, a seeded mix of tiers.

go
// Package sim is a deterministic overload simulator: C identical servers,
// fixed service time, a FIFO queue in front, clients that give up after a
// timeout. It shows what the page claims: without shedding goodput collapses
// under overload, with shedding it plateaus.
package sim

import (
	"container/heap"
	"time"

	"academy/load-shedding/clock"
	"academy/load-shedding/limit"
	"academy/load-shedding/limiter"
	"academy/load-shedding/shed"
)

// Mode is the admission policy in front of the queue.
type Mode string

const (
	Unbounded   Mode = "unbounded"       // accept everything
	Static      Mode = "static-limit"    // reject above a fixed in-system count
	QueueBudget Mode = "queue-budget"    // drop at dequeue when the wait is too long
	Tiered      Mode = "tiered-static"   // per-tier share of a fixed limit
	Adaptive    Mode = "tiered-adaptive" // per-tier share of a gradient limit
)

// Config describes one run.
type Config struct {
	Mode          Mode
	Servers       int
	Service       time.Duration // time one request takes on one server
	ClientTimeout time.Duration // a reply later than this is useless
	Offered       float64       // multiple of capacity, 2.0 = twice what the servers can do
	Duration      time.Duration
	StaticLimit   int           // requests allowed in the system (queued + running)
	Budget        time.Duration // QueueBudget mode
}

// Result counts outcomes per tier.
type Result struct {
	Offered, Good, Late, Shed [4]int
	Duration                  time.Duration
}

// Goodput is useful replies per second.
func (r Result) Goodput() float64 {
	n := 0
	for _, g := range r.Good {
		n += g
	}
	return float64(n) / r.Duration.Seconds()
}

// GoodShare is the fraction of offered requests of tier t answered in time.
func (r Result) GoodShare(t shed.Tier) float64 {
	if r.Offered[t] == 0 {
		return 0
	}
	return float64(r.Good[t]) / float64(r.Offered[t])
}

type request struct {
	tier   shed.Tier
	arrive time.Time
	tok    *limiter.Token
}

type completion struct {
	at  time.Time
	req *request
}

type completions []completion

func (h completions) Len() int            { return len(h) }
func (h completions) Less(i, j int) bool  { return h[i].at.Before(h[j].at) }
func (h completions) Swap(i, j int)       { h[i], h[j] = h[j], h[i] }
func (h *completions) Push(x interface{}) { *h = append(*h, x.(completion)) }
func (h *completions) Pop() interface{} {
	old := *h
	x := old[len(old)-1]
	*h = old[:len(old)-1]
	return x
}

// tierOf draws from a fixed mix, 5% CRITICAL_PLUS, 15% CRITICAL, 30%
// SHEDDABLE_PLUS and 50% SHEDDABLE, with a seeded generator so runs repeat
// exactly. A repeating pattern would alias with the regular arrival spacing.
func tierOf(state *uint64) shed.Tier {
	*state += 0x9e3779b97f4a7c15 // splitmix64
	z := *state
	z = (z ^ (z >> 30)) * 0xbf58476d1ce4e5b9
	z = (z ^ (z >> 27)) * 0x94d049bb133111eb
	z ^= z >> 31
	switch k := z % 100; {
	case k < 5:
		return shed.CriticalPlus
	case k < 20:
		return shed.Critical
	case k < 50:
		return shed.SheddablePlus
	default:
		return shed.Sheddable
	}
}

// Run executes one simulation.
func Run(cfg Config) Result {
	start := time.Unix(1_700_000_000, 0)
	clk := clock.NewFake(start)
	capacity := float64(cfg.Servers) / cfg.Service.Seconds()
	gap := time.Duration(float64(time.Second) / (capacity * cfg.Offered))
	total := int(cfg.Duration / gap)

	var lim *limiter.Limiter
	switch cfg.Mode {
	case Adaptive:
		lim = limiter.New(limit.NewGradient(cfg.StaticLimit, cfg.Servers, 4*cfg.StaticLimit, 20, 0.5), clk)
	default:
		lim = limiter.New(limit.Fixed{N: cfg.StaticLimit}, clk)
	}

	res := Result{Duration: cfg.Duration}
	var queue []*request
	var done completions
	busy, inSystem := 0, 0

	tryStart := func() {
		for busy < cfg.Servers && len(queue) > 0 {
			r := queue[0]
			queue = queue[1:]
			if cfg.Mode == QueueBudget && clk.Now().Sub(r.arrive) > cfg.Budget {
				res.Shed[r.tier]++
				inSystem--
				continue
			}
			busy++
			heap.Push(&done, completion{at: clk.Now().Add(cfg.Service), req: r})
		}
	}

	next := 0
	seed := uint64(42)
	for next < total || done.Len() > 0 {
		arrival := start.Add(time.Duration(next) * gap)
		if next < total && (done.Len() == 0 || !done[0].at.Before(arrival)) {
			clk.Set(arrival)
			t := tierOf(&seed)
			next++
			res.Offered[t]++
			r := &request{tier: t, arrive: arrival}
			admit := true
			switch cfg.Mode {
			case Static:
				admit = inSystem < cfg.StaticLimit
			case Tiered, Adaptive:
				r.tok, admit = lim.Acquire(shed.DefaultThresholds[t])
			}
			if !admit {
				res.Shed[t]++
				continue
			}
			inSystem++
			queue = append(queue, r)
			tryStart()
			continue
		}
		c := heap.Pop(&done).(completion)
		clk.Set(c.at)
		busy--
		inSystem--
		lat := c.at.Sub(c.req.arrive)
		out := limiter.Success
		if lat > cfg.ClientTimeout {
			res.Late[c.req.tier]++
			out = limiter.Dropped
		} else {
			res.Good[c.req.tier]++
		}
		if c.req.tok != nil {
			c.req.tok.Release(out)
		}
		tryStart()
	}
	return res
}
go
package sim

import (
	"testing"
	"time"

	"academy/load-shedding/shed"
)

func base(mode Mode, offered float64) Config {
	return Config{
		Mode: mode, Servers: 10, Service: 100 * time.Millisecond,
		ClientTimeout: time.Second, Offered: offered, Duration: 60 * time.Second,
		StaticLimit: 20, Budget: 300 * time.Millisecond,
	}
}

// Capacity is 10 servers / 0.1s = 100 requests per second.
const capacity = 100.0

func TestUnderCapacityEveryModeServesEverything(t *testing.T) {
	for _, m := range []Mode{Unbounded, Static, QueueBudget, Tiered, Adaptive} {
		r := Run(base(m, 0.5))
		if g := r.Goodput(); g < 0.45*capacity {
			t.Errorf("%s at 0.5x: goodput %.1f, want about 50", m, g)
		}
	}
}

func TestOverloadCollapsesWithoutShedding(t *testing.T) {
	r := Run(base(Unbounded, 3))
	if g := r.Goodput(); g > 0.15*capacity {
		t.Fatalf("unbounded queue at 3x: goodput %.1f, want a collapse below 15", g)
	}
}

func TestSheddingKeepsGoodputNearCapacity(t *testing.T) {
	for _, m := range []Mode{Static, QueueBudget, Tiered, Adaptive} {
		r := Run(base(m, 3))
		if g := r.Goodput(); g < 0.85*capacity {
			t.Errorf("%s at 3x: goodput %.1f, want at least 85", m, g)
		}
	}
}

func TestTiersProtectCriticalTraffic(t *testing.T) {
	for _, m := range []Mode{Tiered, Adaptive} {
		r := Run(base(m, 3))
		if s := r.GoodShare(shed.CriticalPlus); s < 0.95 {
			t.Errorf("%s: CRITICAL_PLUS good share %.2f, want >= 0.95", m, s)
		}
		if s := r.GoodShare(shed.Critical); s < 0.9 {
			t.Errorf("%s: CRITICAL good share %.2f, want >= 0.9", m, s)
		}
		if r.GoodShare(shed.Sheddable) >= r.GoodShare(shed.Critical) {
			t.Errorf("%s: SHEDDABLE must fare worse than CRITICAL", m)
		}
	}
	// Without tiers the unlabelled overload hits everyone alike.
	r := Run(base(Static, 3))
	if d := r.GoodShare(shed.Critical) - r.GoodShare(shed.Sheddable); d > 0.05 || d < -0.05 {
		t.Errorf("static limit is tier-blind, got shares differing by %.2f", d)
	}
}

func TestSimulationIsDeterministic(t *testing.T) {
	a, b := Run(base(Adaptive, 2)), Run(base(Adaptive, 2))
	if a != b {
		t.Fatal("same config must give the same result")
	}
}

// A static limit tuned for an old, faster fleet is the classic failure:
// 200 in the system on 10 servers means 2 s of queueing, so replies arrive
// after the 1 s client timeout. The adaptive limit starts at the same wrong
// value and walks down to what the servers can really do.
func TestAdaptiveRecoversFromAWrongInitialLimit(t *testing.T) {
	static, adaptive := base(Static, 3), base(Adaptive, 3)
	static.StaticLimit, adaptive.StaticLimit = 200, 200
	s, a := Run(static).Goodput(), Run(adaptive).Goodput()
	if s > 0.3*capacity {
		t.Fatalf("static limit 200: goodput %.1f, want a collapse below 30", s)
	}
	if a < 0.8*capacity {
		t.Fatalf("adaptive from 200: goodput %.1f, want at least 80", a)
	}
}
go
// Command loadsim prints goodput for every admission policy at several
// offered loads. It is deterministic and finishes in well under a second.
package main

import (
	"fmt"
	"time"

	"academy/load-shedding/shed"
	"academy/load-shedding/sim"
)

func main() {
	modes := []sim.Mode{sim.Unbounded, sim.Static, sim.QueueBudget, sim.Tiered, sim.Adaptive}
	loads := []float64{0.5, 1, 2, 4}
	fmt.Println("capacity = 100 req/s (10 servers x 100 ms), client timeout 1 s")
	fmt.Printf("%-16s", "policy")
	for _, l := range loads {
		fmt.Printf(" %7.1fx", l)
	}
	fmt.Println("   (goodput, requests/s)")
	for _, m := range modes {
		fmt.Printf("%-16s", m)
		for _, l := range loads {
			r := sim.Run(sim.Config{
				Mode: m, Servers: 10, Service: 100 * time.Millisecond, ClientTimeout: time.Second,
				Offered: l, Duration: 60 * time.Second, StaticLimit: 20, Budget: 300 * time.Millisecond,
			})
			fmt.Printf(" %8.1f", r.Goodput())
		}
		fmt.Println()
	}
	fmt.Println()
	fmt.Println("share of each tier answered in time at 4x offered load")
	fmt.Printf("%-16s %13s %9s %14s %10s\n", "policy", "CRITICAL_PLUS", "CRITICAL", "SHEDDABLE_PLUS", "SHEDDABLE")
	for _, m := range modes {
		r := sim.Run(sim.Config{
			Mode: m, Servers: 10, Service: 100 * time.Millisecond, ClientTimeout: time.Second,
			Offered: 4, Duration: 60 * time.Second, StaticLimit: 20, Budget: 300 * time.Millisecond,
		})
		fmt.Printf("%-16s %12.0f%% %8.0f%% %13.0f%% %9.0f%%\n", m,
			100*r.GoodShare(shed.CriticalPlus), 100*r.GoodShare(shed.Critical),
			100*r.GoodShare(shed.SheddablePlus), 100*r.GoodShare(shed.Sheddable))
	}
	fmt.Println()
	fmt.Println("a limit of 200 is wrong for 10 servers: 60-second average goodput at 3x offered load")
	for _, m := range []sim.Mode{sim.Static, sim.Adaptive} {
		r := sim.Run(sim.Config{
			Mode: m, Servers: 10, Service: 100 * time.Millisecond, ClientTimeout: time.Second,
			Offered: 3, Duration: 60 * time.Second, StaticLimit: 200, Budget: 300 * time.Millisecond,
		})
		fmt.Printf("%-16s goodput %6.1f req/s\n", m, r.Goodput())
	}
}

The Go angle ​

  • Concurrency limits are a semaphore with memory. A buffered channel of size L is the static limit; the limiter package is the same idea with a moving L and a latency feedback path. Admit with a non-blocking attempt, never with a blocking send: blocking is queueing, and queueing is what shedding avoids.
  • context.Context is the deadline. Pass the client's deadline down (http.Server does not read X-Request-Start; your middleware does) and check ctx.Err() before expensive steps, so doomed requests stop early (Timeouts, Retries & Jitter).
  • Keep the reject path allocation-light. http.Error with a short body, no logging inside the hot path other than a counter increment. The Builders' Library warns that an accidental log line can make rejection costlier than service.
  • Inject the clock. Every package takes clock.Clock, so tests advance time by hand and the simulator replays 60 simulated seconds in milliseconds.
  • net/http has no built-in concurrency limit. http.Server.MaxHeaderBytes, ReadTimeout, IdleTimeout and golang.org/x/net/netutil.LimitListener limit connections, not in-flight requests; for per-request admission you need middleware like the one above.
  • Go's scheduler hides queues. Goroutines are cheap, so a Go service rarely shows a thread-pool queue; the queue is in memory, in the accept backlog and on locks. Track in-flight requests, not goroutines.
  • Beware retries in http.Client. The standard library's Transport retries some idempotent requests on connection reuse errors; for overload policy wrap it as throttle.Transport does.

Laravel ​

Example: queue-time shedding, tiered routes and expiring jobs ​

Laravel 13 has no load-shedding feature of its own. Its throttle middleware and RateLimiter are per-identity rate limiting (Rate Limiting). For overload you combine the proxy's X-Request-Start stamp, a worker budget and route middleware.

The proxy stamps arrival time (NGINX $msec is "current time in seconds with the milliseconds resolution"; Heroku documents X-Request-Start as "unix timestamp (milliseconds) when the request was received by the router"):

nginx
location / {
    proxy_set_header X-Request-Start "t=${msec}";
    proxy_pass http://octane;
}

The tier enum and the header parser are plain PHP:

php
<?php

declare(strict_types=1);

namespace App\Overload;

/**
 * The four criticality values from Google's SRE book, chapter 21.
 * Lower case value = what clients send in the X-Priority header.
 */
enum Tier: string
{
    case CriticalPlus = 'critical_plus';
    case Critical = 'critical';
    case SheddablePlus = 'sheddable_plus';
    case Sheddable = 'sheddable';

    /** Unknown or missing labels are CRITICAL: never shed what nobody labelled. */
    public static function fromHeader(?string $value): self
    {
        return self::tryFrom(strtolower(trim((string) $value))) ?? self::Critical;
    }

    /** Share of the worker budget this tier may use (1.0 = everything). */
    public function threshold(): float
    {
        return match ($this) {
            self::CriticalPlus => 1.0,
            self::Critical => 0.9,
            self::SheddablePlus => 0.7,
            self::Sheddable => 0.5,
        };
    }
}
php
<?php

declare(strict_types=1);

namespace App\Overload;

/**
 * Reads the X-Request-Start header a proxy stamps on the request.
 * NGINX:  proxy_set_header X-Request-Start "t=${msec}";   (seconds, ms resolution)
 * Heroku: unix milliseconds. Some APMs use microseconds.
 */
final class RequestStart
{
    /** @return float|null unix time in seconds, or null if the header is unusable */
    public static function parse(?string $header): ?float
    {
        if ($header === null) {
            return null;
        }
        $value = preg_replace('/^t=/', '', trim($header)) ?? '';
        if (! is_numeric($value) || (float) $value <= 0) {
            return null;
        }
        $number = (float) $value;

        return match (true) {
            $number >= 1e15 => $number / 1e6, // microseconds
            $number >= 1e11 => $number / 1e3, // milliseconds
            default => $number,               // seconds with a fraction
        };
    }

    /** Seconds the request waited before PHP started working on it. */
    public static function queueSeconds(?string $header, ?float $now = null): ?float
    {
        $start = self::parse($header);

        return $start === null ? null : max(0.0, ($now ?? microtime(true)) - $start);
    }
}

The in-flight gauge is an interface with a cache-backed implementation (use the Redis store for a fleet-wide count). It is an estimate, not a lock:

php
<?php

declare(strict_types=1);

namespace App\Overload;

/** Counts requests being worked on right now, per host or per fleet. */
interface InflightGauge
{
    /** Try to take one slot; false when `$limit` slots are taken. */
    public function enter(int $limit): bool;

    public function leave(): void;

    public function current(): int;
}
php
<?php

declare(strict_types=1);

namespace App\Overload;

use Illuminate\Contracts\Cache\Repository;

/**
 * In-flight counter on top of the cache store (use Redis for a fleet-wide
 * number, the `array`/`apc` store for one host). The key has a short TTL, so a
 * worker that dies between enter() and leave() leaks a slot for at most that
 * long. This is an estimate, not a lock: it is meant to drive shedding, not
 * to guarantee a hard cap.
 */
final class CacheInflightGauge implements InflightGauge
{
    public function __construct(
        private readonly Repository $cache,
        private readonly string $key = 'shed:inflight',
        private readonly int $ttlSeconds = 30,
    ) {
    }

    public function enter(int $limit): bool
    {
        $this->cache->add($this->key, 0, $this->ttlSeconds);
        $now = (int) $this->cache->increment($this->key);
        if ($now > $limit) {
            $this->cache->decrement($this->key);

            return false;
        }

        return true;
    }

    public function leave(): void
    {
        if ((int) $this->cache->get($this->key, 0) > 0) {
            $this->cache->decrement($this->key);
        }
    }

    public function current(): int
    {
        return max(0, (int) $this->cache->get($this->key, 0));
    }
}
php
<?php

declare(strict_types=1);

namespace App\Providers;

use App\Overload\CacheInflightGauge;
use App\Overload\InflightGauge;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\ServiceProvider;

final class OverloadServiceProvider extends ServiceProvider
{
    public function register(): void
    {
        // Redis gives a fleet-wide count; use Cache::store('array') for one process.
        $this->app->bind(InflightGauge::class, fn (): InflightGauge => new CacheInflightGauge(
            Cache::store('redis'),
            key: 'shed:inflight:' . gethostname(),
        ));
    }
}

The middleware applies the queue budget and the tier share, answers 503 with Retry-After and a jittered value, and releases the slot in terminate. Laravel's docs say terminable middleware gets "a fresh instance of the middleware from the service container" unless registered as a singleton, which is why the slot flag travels on the request, not on the instance.

php
<?php

declare(strict_types=1);

namespace App\Http\Middleware;

use App\Overload\InflightGauge;
use App\Overload\RequestStart;
use App\Overload\Tier;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Symfony\Component\HttpFoundation\Response;

/**
 * Drops work on purpose to protect goodput.
 *
 *  1. Queue-time budget: the proxy stamped X-Request-Start; if the request
 *     already waited longer than its budget, the client has probably given
 *     up, so answer 503 immediately instead of doing useless work.
 *  2. Worker budget: lower tiers may only use a share of the workers.
 *
 * Usage:  Route::get('/search/suggest', ...)->middleware('shed:sheddable');
 */
final class ShedLoad
{
    public function __construct(private readonly InflightGauge $gauge)
    {
    }

    public function handle(Request $request, Closure $next, string $tier = 'critical'): Response
    {
        $routeTier = Tier::fromHeader($tier);
        $tier = Tier::fromHeader($request->header('X-Priority', $routeTier->value));
        // A client may lower its own priority but never raise it above the route's.
        if ($tier->threshold() > $routeTier->threshold()) {
            $tier = $routeTier;
        }

        $budget = (float) config('shedding.queue_budget_seconds.' . $tier->value, 0.0);
        $waited = RequestStart::queueSeconds($request->header('X-Request-Start'));
        if ($budget > 0 && $waited !== null && $waited > $budget) {
            return $this->refuse($tier, 'queue_budget', $waited);
        }

        $workers = (int) config('shedding.workers', 8);
        $slots = max(1, (int) ceil($workers * $tier->threshold()));
        if (! $this->gauge->enter($slots)) {
            return $this->refuse($tier, 'concurrency', $waited);
        }

        // Released in terminate() so the slot is held while the response is built.
        $request->attributes->set('shed.entered', true);

        return $next($request);
    }

    /** Terminable middleware: runs after the response is sent. */
    public function terminate(Request $request, Response $response): void
    {
        if ($request->attributes->get('shed.entered') === true) {
            $this->gauge->leave();
        }
    }

    private function refuse(Tier $tier, string $reason, ?float $waited): Response
    {
        // Count by tier and reason; never log request bodies or customer data.
        Log::info('request shed', ['tier' => $tier->value, 'reason' => $reason, 'queue_seconds' => $waited]);

        $retryAfter = random_int(1, 3); // jitter so refused clients do not return together

        return response('Service Unavailable', 503, [
            'Retry-After' => (string) $retryAfter,
            'X-Shed-Reason' => $reason,
            'Cache-Control' => 'no-store',
        ]);
    }
}
php
<?php

declare(strict_types=1);

return [
    // Octane workers (one request at a time each). Keep equal to --workers.
    'workers' => (int) env('SHED_WORKERS', 8),

    // Maximum age of a request when PHP picks it up, per tier, in seconds.
    'queue_budget_seconds' => [
        'critical_plus' => 5.0,
        'critical' => 2.0,
        'sheddable_plus' => 1.0,
        'sheddable' => 0.5,
    ],
];
php
<?php

declare(strict_types=1);

use App\Http\Middleware\ShedLoad;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Middleware;

return Application::configure(basePath: dirname(__DIR__))
    ->withMiddleware(function (Middleware $middleware): void {
        // Alias so routes can say ->middleware('shed:sheddable').
        $middleware->alias(['shed' => ShedLoad::class]);
    })
    ->create();
php
<?php

declare(strict_types=1);

use Illuminate\Support\Facades\Route;

// Checkout is what the business exists for: shed last.
Route::post('/checkout', fn () => response()->json(['ok' => true]))
    ->middleware('shed:critical_plus');

// Order history: normal production traffic.
Route::get('/orders', fn () => response()->json([]))
    ->middleware('shed:critical');

// Typeahead and recommendations are nice to have: shed first.
Route::get('/search/suggest', fn () => response()->json([]))
    ->middleware('shed:sheddable');

// Exports run for minutes and can be retried tomorrow.
Route::get('/reports/export', fn () => response()->streamDownload(fn () => print('id'), 'r.csv'))
    ->middleware('shed:sheddable_plus');

Queue jobs expire by age. retryUntil() bounds the retry window, and Skip::when() deletes a job that waited longer than its TTL without counting it as a failure:

php
<?php

declare(strict_types=1);

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\Middleware\Skip;
use Illuminate\Queue\SerializesModels;

/**
 * A queued job that is only worth running while it is fresh.
 * `retryUntil()` bounds the whole retry window; `Skip::when()` deletes the
 * job (no failure, no retry) when it waited in the queue longer than its TTL.
 */
final class SendDigest implements ShouldQueue
{
    use Dispatchable;
    use InteractsWithQueue;
    use Queueable;
    use SerializesModels;

    /** Seconds a digest stays useful after it was dispatched. */
    public const TTL_SECONDS = 600;

    public int $enqueuedAt;

    public function __construct(public int $userId)
    {
        $this->enqueuedAt = time();
    }

    /** @return array<int, object> */
    public function middleware(): array
    {
        return [
            Skip::when(fn (): bool => time() - $this->enqueuedAt > self::TTL_SECONDS),
        ];
    }

    public function retryUntil(): \DateTimeInterface
    {
        return now()->addSeconds(self::TTL_SECONDS);
    }

    public function handle(): void
    {
        // Build and send the digest for $this->userId.
    }
}

A unit test for the parser and the tier default (PHPUnit):

php
<?php

declare(strict_types=1);

namespace Tests\Unit;

use App\Overload\RequestStart;
use App\Overload\Tier;
use PHPUnit\Framework\TestCase;

final class RequestStartTest extends TestCase
{
    public function test_it_reads_seconds_milliseconds_and_microseconds(): void
    {
        $this->assertEqualsWithDelta(1700000000.123, RequestStart::parse('t=1700000000.123'), 0.001);
        $this->assertEqualsWithDelta(1700000000.123, RequestStart::parse('1700000000123'), 0.001);
        $this->assertEqualsWithDelta(1700000000.123, RequestStart::parse('t=1700000000123000'), 0.001);
        $this->assertNull(RequestStart::parse('garbage'));
        $this->assertNull(RequestStart::parse(null));
    }

    public function test_queue_seconds_is_the_age_of_the_request(): void
    {
        $this->assertEqualsWithDelta(2.0, RequestStart::queueSeconds('t=1700000000.000', 1700000002.0), 0.0001);
    }

    public function test_unlabelled_traffic_is_critical(): void
    {
        $this->assertSame(Tier::Critical, Tier::fromHeader(null));
        $this->assertSame(Tier::Sheddable, Tier::fromHeader(' SHEDDABLE '));
    }
}

The Laravel angle ​

  • Octane workers are your concurrency limit. The docs: "By default, Octane will start an application request worker for each CPU core provided by your machine", changed with php artisan octane:start --workers=4. A worker handles one request at a time, so --workers is a hard in-flight cap, and the rest queue in the application server. Keep the shedding.workers config equal to it. Octane also restarts a worker after 500 requests by default (--max-requests) and applies a 30-second max_execution_time.
  • PHP-FPM has the same shape. pm.max_children is the in-flight cap; extra connections wait in the listen backlog, which is where X-Request-Start age grows. Set the budget so requests that sat longer than the client timeout are refused unread.
  • Alias and route parameters. $middleware->alias(['shed' => ShedLoad::class]) in bootstrap/app.php and ->middleware('shed:sheddable') on routes are standard Laravel 13 middleware features (withMiddleware, route middleware parameters).
  • Do not use throttle for overload. throttle:60,1 limits a caller to 60 requests a minute whatever the server's state. It does not know about queue wait or worker use.
  • Queues: retryUntil() and Skip::when() are documented queue features. Also set --max-time and --timeout on workers, and keep the worker timeout below retry_after, or a slow job is handed to a second worker while the first still runs (duplicate work during overload).
  • Horizon can autoscale workers per queue (balance: auto); combine it with shedding and scale on queue wait, not CPU.
  • Client side: Http::retry(3, fn (int $attempt, Exception $e) => ...) accepts a closure that computes the sleep in milliseconds (documented in the HTTP client chapter); read Retry-After from the RequestException response there, and gate retries with a cache-backed budget through the when: argument. Mark non-idempotent calls so they never retry.

Solving the classic problems ​

ProblemSolutionHowAdvantageCost or limit
Goodput collapses at 2x loadConcurrency limitCap in-flight; refuse the restPlateau at capacityLimit must track capacity
Static limit goes stale after a deployAdaptive limitGradient or Vegas from latencyNo manual tuningNeeds bounds, a clean minRTT
Old requests clog the queueQueue-time budgetX-Request-Start, timeout queue, CoDelNo work for gone clientsClocks must agree
Batch job starves interactive trafficTiersSHEDDABLE_PLUS for batch with a 70% shareInteractive stays fastNeeds honest labels
One tenant floods the APIPer-customer quotaIn-flight or CPU quota per key, 429Others unaffectedPer-key state
Retry storm after a brownoutRetry budget and adaptive throttling10% retries, 3 attempts, client rejects locallyBounded amplificationClient libraries must cooperate
Slow dependency pins all workersIn-flight limit plus deadlineLimit per dependency; drop on deadlineOther routes surviveSee Bulkheads
Health checks shed, fleet shrinksPrioritise pingsExempt /healthz from sheddingFleet stays in rotationKeep it cheap
Shedding hides load from the autoscalerScale on shed rateExport shed counter; HPA external metricCapacity follows demandMetrics pipeline delay
Stale jobs processed hours lateJob TTLretryUntil(), Skip::when(), RabbitMQ TTLFresh work firstExpired work needs a DLQ
Whole fleet saturated, retries multiply"Don't retry" markerHeader on 503 when histogram shows widespread retriesStops explosionsNeeds retry-count propagation
Memory spike kills podsOverload manager and evictionEnvoy stop_accepting_requests; kubelet evictionSoftControlled degradationEvicts instead of refuses

Retry storm after a brownout ​

A 30-second dependency slowdown makes 503s; every client retries three times; the retries arrive as the dependency recovers and knock it over again. Fix in layers: the server answers 503 with Retry-After and jitter, the client uses throttle.Transport (three attempts, 10% budget, local rejection), and only the layer directly above retries. Test with the simulator at 3x and a StaticLimit of 200 (the lab).

Batch versus interactive ​

The nightly export shares a service with checkout. Label exports SHEDDABLE_PLUS (70% of the limit), checkout CRITICAL_PLUS. In Laravel Route::get('/reports/export', ...)->middleware('shed:sheddable_plus'); in Go X-Priority: SHEDDABLE_PLUS from the batch client or a Classify function that reads the route. Google goes further: batch clients go through a "batch proxy" that "acts like a fuse".

sql
-- Job table with an explicit expiry, so stale work is never claimed (PostgreSQL).
CREATE TABLE jobs (
    id          bigserial PRIMARY KEY,
    tier        smallint    NOT NULL,          -- 0 critical_plus .. 3 sheddable
    payload     jsonb       NOT NULL,
    enqueued_at timestamptz NOT NULL DEFAULT now(),
    expires_at  timestamptz NOT NULL
);
CREATE INDEX jobs_claim ON jobs (tier, enqueued_at);

-- Claim the best fresh job; expired rows are skipped, not worked.
SELECT id, payload
FROM jobs
WHERE expires_at > now()
ORDER BY tier, enqueued_at
FOR UPDATE SKIP LOCKED
LIMIT 1;

-- Sweep expired work out of the way (dead-letter first if you need an audit).
DELETE FROM jobs WHERE expires_at <= now();

-- Last-line database shedding: fail fast instead of queueing forever.
ALTER ROLE web SET statement_timeout = '3s';
ALTER ROLE web SET lock_timeout = '1s';
ALTER ROLE web CONNECTION LIMIT 50;

The claim query filters on expires_at in the WHERE clause (an index predicate cannot use now(), which is not immutable), and the DELETE sweep keeps expired rows from accumulating. FOR UPDATE SKIP LOCKED is the queue-claim idiom from Locks & Concurrency Control.

Choosing ​

SituationRecommendationExtra techniqueReason
New HTTP service, one teamStatic concurrency limit = workers x 2, queue-time budgetLoad test to 4xSimplest thing that plateaus
Autoscaled fleet, changing capacityAdaptive limit (gradient) per instanceMin and max boundsFixed numbers go stale
Mixed interactive and batchFour tiers, thresholds 100/90/70/50Propagate tier in a headerBatch loses first
Public multi-tenant APIPer-customer quota plus shared limit429 with Retry-AfterNoisy neighbour isolation
Behind NGINX or HAProxy onlylimit_conn, timeout queue, maxconnDry-run firstNo code change
Envoy or Istio meshAdaptive concurrency filter plus overload managerprevious_hosts retry predicateShedding without app code
Laravel on Octane or FPMX-Request-Start budget plus worker gaugeTier per routeMatches one-request-per-worker
Queue consumers, stale data uselessTTL and drop-headDead-letter to inspectFreshness over completeness
Queue consumers, loss unacceptablereject-publish and slow the producerBackpressureLossless
Kubernetes node memory pressureSet requests and PriorityClassevictionSoft with graceControlled victims
Clients you controlAdaptive throttling and retry budgetRetry-After honouredStops amplification
Safety-critical pathsNever shed, over-provision, isolate with bulkheadsCRITICAL_PLUSShedding is for what can fail

In architecture: from a single process to a distributed system ​

Monolith (one process, one database) ​

One Laravel app on Octane or PHP-FPM with 8 workers and one PostgreSQL. The in-flight limit is the worker count; the queue is the web server's accept backlog. The simplest correct setup: NGINX limit_conn for abusive IPs, the shed middleware with a queue budget, checkout critical_plus, search suggestions sheddable, and statement_timeout on the database. Health checks are exempt.

Modular monolith / multiple databases ​

Modules share workers but not importance. Put the tier on the module's routes, give each module its own database pool, and give batch modules a separate queue and worker pool. A shared in-flight gauge makes the busiest module visible; a per-module share (Percentage enforcement in Netflix's terms) stops the reporting module from taking all workers.

Microservices ​

Request flow with criticality propagated end to end:

text
     Hop   Service         Receives                       Does
1    1     edge (Envoy)    X-Priority from the client     validates, may only lower; stamps X-Request-Start
2    2     gateway         tier, customer id              per-customer quota -> 429; passes tier on
3    3     orders          tier=CRITICAL                  admits at 90% of its adaptive limit; calls payments with the same tier
4    4     payments        tier=CRITICAL                  admits; 503 + Retry-After if over
5    5     orders          503 from payments              retries once (budget ok) then returns a degraded order page

Each service has its own adaptive limit; the retry happens only one layer above the rejecting service. Google's rule: "requests should only be retried at the layer immediately above the layer that is rejecting them". See Service Communication and Cascading Failures. A service mesh can do part of this without code (Service Mesh & the Sidecar Pattern).

Distributed data (replicas, caches, sharded stores) ​

Shedding on a stateful tier needs more care. A hot shard overloaded while others idle needs per-shard limits, not a global one (Sharding at System Level). Read replicas absorb shed reads only if lag is bounded (Replication). A cache flush multiplies load on the database: use a stampede guard (Caching) and shed SHEDDABLE reads at the database proxy. Connection poolers (PgBouncer) are admission control for PostgreSQL: a full pool is a queue, and query_wait_timeout is a queue timeout (Connection Pooling). Cross-region: shift traffic away before shedding (Load Balancing), as Google notes balancing so that "no datacenter receives more traffic than it has the capacity to process".

Scaling path ​

LoadDesign
1x (hundreds of req/s)Worker count as limit, statement_timeout, health checks exempt
10xQueue-time budget, two tiers (critical and sheddable), per-IP limit_conn at NGINX
100xAdaptive limit per instance, four tiers, per-customer quotas, shed-rate autoscaling, client throttling libraries
1000xTier propagation across services, Envoy overload manager at the ingress, per-shard limits, cell-based isolation, regular overload game days

Lab ​

The simulator is deterministic and runs in under a second (this output was actually produced by go run ./cmd/loadsim in the snippet module).

bash
cd docs/snippets/system-design/load-shedding/go
go test -race ./...
go run ./cmd/loadsim
text
capacity = 100 req/s (10 servers x 100 ms), client timeout 1 s
policy               0.5x     1.0x     2.0x     4.0x   (goodput, requests/s)
unbounded            50.0    100.0      3.2      2.2
static-limit         50.0    100.0    100.2    100.2
queue-budget         50.0    100.0    100.5    100.5
tiered-static        50.0     91.7     99.6    100.1
tiered-adaptive      50.0    100.0    100.2    100.2

share of each tier answered in time at 4x offered load
policy           CRITICAL_PLUS  CRITICAL SHEDDABLE_PLUS  SHEDDABLE
unbounded                   0%        0%             1%         1%
static-limit               25%       25%            26%        25%
queue-budget               24%       25%            26%        25%
tiered-static             100%       85%            23%         0%
tiered-adaptive           100%       85%            23%         0%

a limit of 200 is wrong for 10 servers: 60-second average goodput at 3x offered load
static-limit     goodput    2.3 req/s
tiered-adaptive  goodput  100.1 req/s

How to read it, as five numbered experiments:

  1. Collapse. unbounded at 2x gives 3.2 req/s against a capacity of 100: the server is busy and useless. Change Mode to static-limit and the same load gives 100.2.
  2. Tiers. At 4x, every tier-blind policy serves about 25% of every tier. tiered-* gives CRITICAL_PLUS 100%, CRITICAL 85%, SHEDDABLE 0%. CRITICAL is below 100% because CRITICAL_PLUS plus CRITICAL is 80 req/s at 4x, close to the 100 req/s capacity, and CRITICAL stops at 90% of the limit.
  3. False positives. tiered-static at 1.0x shows 91.7 instead of 100: lower tiers are refused at 50 to 90% of the limit even when the system could carry them. This is the price of tiers; the adaptive limit recovers it because it has headroom above the worker count.
  4. A wrong static limit. With limit 200 on 10 servers the queue holds up to 190 requests, wait about 1.9 s, past the 1 s timeout: 2.3 req/s. The adaptive limit starts at the same 200 and walks down: 100.1 req/s.
  5. Change the numbers. Edit Budget in cmd/loadsim/main.go to 1.5 s and watch queue-budget stop protecting clients with a 1 s timeout; set Service to 200 ms with a limit of 20 and see the capacity halve.

Broker and Laravel parts of the lab are written as commands with expected output (expected, not run):

bash
# RabbitMQ: bounded queue with reject-publish and a 60 s TTL (expected, not run)
rabbitmqctl set_policy shed "^notify\." \
  '{"max-length":1000,"overflow":"reject-publish-dlx","message-ttl":60000,"dead-letter-exchange":"dlx"}' \
  --apply-to queues
# expected: Setting policy "shed" for pattern "^notify\." to "{...}" with priority "0" for vhost "/" ...
# when the 1001st message arrives, a publisher with confirms gets basic.nack

# Laravel: worker pinned at 2, stale request is shed (expected, not run)
php artisan octane:start --workers=2
curl -i -H 'X-Request-Start: t=1700000000.000' -H 'X-Priority: sheddable' http://127.0.0.1:8000/search/suggest
# expected: HTTP/1.1 503 Service Unavailable
#           Retry-After: 2
#           X-Shed-Reason: queue_budget

Common misconceptions ​

BeliefReality
Shedding load is a failureIt is a controlled, chosen failure of the least valuable work; the alternative is uncontrolled failure of all of it
High throughput proves healthThroughput includes work for clients who timed out; only goodput counts
Overloaded servers should stop accepting trafficThey should accept what they can finish and refuse the rest (Google SRE book)
CPU at 80% is the overload signalQueue wait or in-flight count is closer to the cause; CPU is a proxy
A longer queue is saferA longer queue converts load into latency and wasted work
429 is the code for all shedding429 is for one caller over its rate; server-wide overload is 503
A priority queue is load sheddingIt orders waiting work but never refuses any; it needs an admission limit
Autoscaling removes the needScaling is slower than overload, and shedding can hide the load from CPU-based scalers
Retries make the system reliable under overloadWithout a budget they multiply the load up to threefold
Load tests to peak traffic are enoughTest far beyond breaking point and look for the plateau
Tier labels from clients can be trustedClients can only lower their tier; the route or the gateway sets the ceiling
Median latency shows shedding is workingFast refusals drag the median down; track admitted latency separately

Cheat sheet ​

TopicWhat to remember
GoalKeep goodput flat at capacity when offered load keeps rising
Limit unitConcurrency, not RPS: in-flight = RPS x latency
Early signalQueue wait (age at pickup) and in-flight against a limit
AlgorithmsAIMD (loss), Vegas (delay), gradient (delay trend); all need min and max bounds
QueueBounded, with TTL; drop-head for freshness, reject-publish for lossless
TiersCRITICAL_PLUS, CRITICAL, SHEDDABLE_PLUS, SHEDDABLE at 100/90/70/50% of the limit
Status503 + Retry-After for server overload; 429 for caller over quota
Reject pathCheaper than the work, no logging of bodies, no I/O
ClientAdaptive throttling K=2, 3 attempts, 10% retry budget, honour Retry-After
LayersEdge for bulk, service for truth, queue for freshness, database as last line
AutoscalingScale on shed rate or queue wait, not on CPU that shedding keeps low
Metricsshed count by tier and reason, goodput, limit, admitted-only latency
TestRamp to 4x with a priority mix; pass means a plateau, not a cliff
ProductsNGINX limit_conn, HAProxy timeout queue, Envoy adaptive concurrency and overload manager, RabbitMQ overflow, Octane --workers

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 — What is the difference between throughput and goodput, and why can throughput be at maximum while goodput is zero? Must-know ​

Answer

Answer: Throughput counts all requests handled; goodput counts only those that finished successfully within the client's deadline. Under overload the server keeps working on requests whose clients timed out, so throughput stays high and goodput collapses.

2 — Why is a concurrency limit a better unit than requests per second? Must-know ​

Answer

Answer: RPS ignores how long each request holds a worker, and capacity changes with latency and fleet size. Little's Law (in-flight = RPS x latency) shows concurrency tracks the real capacity automatically; an RPS limit goes stale.

3 — Describe how Vegas and the gradient controller decide to lower the limit. Good to know ​

Answer

Answer: Vegas estimates the queue as limit x (1 - minRTT/sampleRTT) and lowers the limit when that exceeds beta. Envoy's gradient controller computes gradient = (minRTT + B) / sampleRTT and sets limit' = gradient x limit + sqrt(limit), so rising latency pulls the gradient below 1 and shrinks the limit.

4 — When should a server answer 503 and when 429? Must-know ​

Answer

Answer: 503 for server-side overload that affects everyone (concurrency limit, queue budget, overload manager); 429 when one caller exceeded its own rate or quota. Both should carry Retry-After.

5 — What are the four Google criticality values and which are shed first? Good to know ​

Answer

Answer: CRITICAL_PLUS, CRITICAL, SHEDDABLE_PLUS, SHEDDABLE. Lower criticalities are rejected sooner as utilisation rises, so SHEDDABLE goes first and CRITICAL_PLUS last.

6 — Why does the queue-time budget need a timestamp from the proxy? Important ​

Answer

Answer: Only the front door knows when the request really arrived; inside the app the request already left the queue. The proxy's X-Request-Start lets the app compute the wait and drop requests the client has abandoned.

7 — What does a retry budget do, and with what numbers? Important ​

Answer

Answer: It limits retry amplification: up to three attempts per request and retries only while retries are below about 10% of requests, which caps worst-case growth at roughly 1.1x instead of 3x.

8 — Compare drop-head and reject-publish in RabbitMQ. Good to know ​

Answer

Answer: Drop-head (the default) discards the oldest message when full, keeping the queue fresh and hiding loss from producers. Reject-publish refuses the newest message and sends basic.nack with publisher confirms, which pushes back on producers.

9 — How can load shedding break CPU-based autoscaling? Important ​

Answer

Answer: If shedding keeps CPU below the scaling target, the autoscaler never sees the excess demand. Scale on shed rate, queue wait or offered concurrency instead.

10 — Why must latency metrics exclude shed requests? Important ​

Answer

Answer: Refusals are very fast; if 60% of traffic is shed, the median looks excellent while admitted requests may be slow. Record admitted latency separately and count sheds by tier and reason.

11 — What should an overload test look like and what result passes? Important ​

Answer

Answer: Ramp offered load well beyond capacity with a realistic priority mix, ideally also with a fixed fleet and with removing instances. A pass is a goodput plateau near capacity and near-full success for high tiers; a cliff to near zero fails.

Glossary ​

TermMeaning
Load sheddingRefusing some work on purpose to protect the work that is accepted
GoodputRate of replies that are successful and in time
ThroughputRate of all requests handled, useful or not
Overload detectionMeasuring signals that show demand exceeds capacity
Queue wait timeTime a request waited before work began (sojourn time)
In-flight requestsRequests admitted and not yet finished
Concurrency limitMaximum in-flight requests
Adaptive concurrency limitA limit recomputed from latency or loss samples
Little's Lawin-flight = arrival rate x time in system
AIMDAdditive increase, multiplicative decrease, the TCP-style loss-based rule
VegasDelay-based limit estimate from minRTT and sample RTT
GradientLimit rule from the ratio of unloaded to sampled latency (Envoy, Netflix Gradient2)
minRTTLowest latency seen, the no-queue baseline
CoDelControlled Delay: drop on persistent queue delay above a target (RFC 8289)
Queue timeoutMaximum time a request may wait in a queue (HAProxy timeout queue)
Admission controlThe decision whether to let a request in
CriticalityA per-request label ranking importance, used to choose who is shed
Priority tierOne of the criticality classes
CRITICAL_PLUSHighest criticality, serious user-visible impact if it fails
SHEDDABLELowest criticality, partial unavailability expected
Per-customer quotaResource cap for one caller, shed only that caller
Cost-based sheddingAdmission by estimated resource cost, not request count
503 Service UnavailableHTTP status for temporary server overload (RFC 9110)
429 Too Many RequestsHTTP status for a caller over its rate (RFC 6585)
Retry-AfterHeader with seconds or a date to wait before retrying
Partial resultsA cheaper, incomplete answer instead of an error
BackoffWaiting longer between successive retries
Retry budgetCap on retries relative to requests (about 10%)
Adaptive throttlingClient rejects locally once accepts fall behind requests
Rate limitingEnforcing an agreed rate per identity
BackpressureThe receiver's pace transmitted to the sender
Message TTLMaximum age of a message in a queue
Drop-headOn overflow discard the oldest message
Reject-publishOn overflow refuse the new message
Dead letterWhere discarded or expired messages go for inspection
AutoscalingAdding or removing instances based on metrics
Envoy adaptive concurrencyEnvoy HTTP filter with a gradient controller
Overload managerEnvoy subsystem mapping resource pressure to actions
limit_connNGINX directive limiting concurrent connections per key
Resource pressureNode memory, disk or PID shortage in Kubernetes
EvictionThe kubelet terminating pods to reclaim resources
X-Request-StartProxy-added header with request arrival time
Shed countCounter of refused requests by tier and reason
Goodput metricSuccessful replies within the SLO per second

References ​

Built by Morteza Negahi