Backpressure and Load Shedding

Keeping a system healthy when demand exceeds capacity: slowing producers, bounding queues, rejecting early and degrading gracefully.

What is it?

Every system has a maximum throughput. When more work arrives than it can finish, the excess has to go somewhere. If you don't decide where, it goes into unbounded queues and memory, latency climbs for everyone, timeouts fire, clients retry, load grows further, and the system collapses. This is congestive collapse or a retry storm.

There are only a few honest options when demand exceeds capacity:

- Backpressure: tell the producer to slow down ("not now"), so the pressure moves upstream instead of piling up inside. - Load shedding: reject some work quickly (HTTP 429/503) so the work you accept still finishes on time. - Prioritization: when you must drop something, drop the least important work first. - Graceful degradation: do a cheaper version of the work (skip recommendations, serve cached results). - Bulkheads: isolate resources so one overloaded dependency can't consume everything. - Admission control: decide at the door whether a request can be served in time, before spending anything on it.

The pro mindset: overload is a normal operating condition, not an edge case. Design what happens at 2x capacity before it happens.

Explain like I'm 10

A popular restaurant with a full kitchen doesn't seat everyone and let food take three hours. The host keeps a short waiting list, tells new arrivals 'we're full, try at 9', offers a simpler menu when slammed, and keeps a separate counter for takeaway so dine-in chaos doesn't block it.

Examples

Bounded concurrency with fast rejection

const MAX_IN_FLIGHT = 200;   // from load testing: past this, latency explodes
const MAX_WAITING = 100;     // short queue absorbs bursts, not sustained overload
let inFlight = 0;
const waiting: Array<() => void> = [];

async function admit<T>(handler: () => Promise<T>): Promise<T> {
  if (inFlight >= MAX_IN_FLIGHT) {
    if (waiting.length >= MAX_WAITING) {
      throw new AppError(AppErrorCode.Overloaded, "Server busy, retry later"); // -> 503 + Retry-After
    }
    await new Promise<void>((resolve) => waiting.push(resolve));
  }
  inFlight++;
  try {
    return await handler();
  } finally {
    inFlight--;
    waiting.shift()?.();
  }
}

A bounded queue in front of bounded concurrency. Under overload, extra requests fail in microseconds instead of timing out after 30 seconds and holding memory.

Priority-based shedding

type Priority = "critical" | "default" | "sheddable";

// Shed lower tiers first as utilization climbs.
function shouldShed(priority: Priority, utilization: number): boolean {
  if (priority === "sheddable") return utilization > 0.7; // prefetch, analytics, batch
  if (priority === "default") return utilization > 0.9;   // normal user reads
  return utilization > 0.98;                              // checkout, login
}

Callers tag requests (often via a header set at the edge). Under pressure, background and prefetch traffic disappears first, protecting the actions users and the business care about most.

Pull-based backpressure in a stream consumer

// Node streams: write() returns false when the buffer is full.
for await (const record of sourceStream) {
  const ok = destinationStream.write(transform(record));
  if (!ok) {
    await once(destinationStream, "drain"); // stop reading until the consumer catches up
  }
}

The reader only pulls more when the writer has room. Kafka consumers, Reactive Streams (request(n)) and TCP flow control all use the same idea.

How it works

Why unbounded queues are dangerous. Little's Law says L = λ × W: items in the system = arrival rate × time in system. If arrivals exceed service rate, the queue grows without limit, so wait time grows without limit. Requests then wait longer than their callers' timeouts, so the server does work nobody is waiting for. Throughput of useful work drops toward zero even though the server is 100% busy.

Backpressure propagates "slow down" upstream. In-process: bounded channels and blocking writes. Between services: pull-based consumption (Kafka consumers fetch at their own pace), credit-based flow (gRPC/HTTP/2 flow-control windows, Reactive Streams request(n)), or explicit signals (429 with Retry-After). Backpressure only works if the producer can slow down; user traffic usually can't, so at the edge you shed instead.

Load shedding. Reject cheaply and early: at the load balancer or the first middleware, before parsing bodies or calling databases. Signals for "overloaded": in-flight count, queue length, queueing delay (CoDel style: drop when requests have waited longer than a target), CPU, or latency over SLO. Return 503/429 with Retry-After so clients back off. Also drop requests whose deadline has already passed (deadline propagation): finishing them wastes capacity.

Adaptive concurrency limits. Instead of a hard-coded limit, measure latency and adjust the limit like TCP congestion control (AIMD, or gradient-based limiters such as Netflix's concurrency-limits library).

Prioritization. Tag traffic by importance (critical, default, sheddable, batch) and shed from the bottom. Serve queues LIFO under overload in some systems, since the newest request's caller is most likely still waiting.

Bulkheads. Separate thread pools, connection pools or whole instances per dependency or per tenant. If the recommendations service hangs, only its pool fills; checkout keeps its own capacity. Cell-based architecture is the bulkhead idea at infrastructure scale.

Graceful degradation. Pre-plan cheaper modes: static fallback, cached or stale results, disabling expensive features via flags, lower-quality media, fewer search results. Combine with circuit breakers so you stop calling a failing dependency.

Retry discipline. Retries multiply load exactly when the system is weakest. Use retry budgets (e.g. retries ≤ 10% of requests), exponential backoff with jitter, and retry at one layer only.

Throughput vs offered load

useful  |          ______________  with shedding (plateaus)
work    |        /
        |       /\
        |      /  \
        |     /    \____  without shedding (collapse)
        |____/__________\______________
             capacity          offered load ->

Request path with admission control

client -> [edge: rate limit] -> [admission: shed by priority]
            -> [bounded queue] -> [worker pool] -> [bulkhead pools per dependency]

Why does it exist?

Overload is guaranteed eventually: traffic spikes, a slow dependency, a bad deploy that halves capacity, a retry storm after a blip. A system with no explicit overload behaviour fails badly and slowly, and often stays down after the trigger is gone (a metastable failure). Explicit limits turn "everything is down" into "some requests got a fast error", which is far easier to recover from.

When to use it

- Every service that takes traffic it doesn't control: put bounds on concurrency, queue sizes and timeouts. - Data pipelines where producers can outpace consumers. - Multi-tenant platforms (per-tenant limits and bulkheads). - Systems with a clear importance ranking among requests (checkout vs browsing, user requests vs batch jobs).

When not to use it

- Don't shed work that can't be retried and must not be lost (an accepted payment). Accept it durably (write to a log or queue) and process it later instead. - Don't add elaborate priority tiers to a small internal tool; a simple concurrency limit and timeout is enough. - Backpressure doesn't help when the producer can't slow down (end users, sensors). There you need shedding, sampling or buffering to durable storage.

Common mistakes

  • Using unbounded queues and thread pools, so overload shows up as memory exhaustion and multi-minute latency instead of fast errors.

  • Shedding too late, after parsing, authenticating and querying, so rejected requests still consume most of the cost.

  • Retrying at every layer (client, gateway, service, mesh), multiplying load 3x–27x during an incident.

  • Setting limits from guesses instead of load tests, so they are either never hit or hit at normal traffic.

  • Having one shared connection pool for all dependencies, so one slow downstream starves everything (no bulkheads).

Practice exercises

  1. Easy:

    Explain why an unbounded queue makes latency worse under sustained overload, using Little's Law.

  2. Medium:

    An API serves checkout, product browsing, and a recommendations widget from the same fleet. Design priority classes and shedding thresholds, and describe what each user sees at 150% load.

  3. Hard:

    After a 30-second database blip, your service stays overloaded for an hour even though the database recovered. Explain the metastable failure and design changes (retries, queues, shedding, deadlines) that would let it recover on its own.

Interview questions

What is backpressure?

A mechanism for a slow consumer to signal producers to slow down, so excess work stays at the source instead of piling up in memory along the pipeline.

What is load shedding?

Deliberately rejecting some requests quickly when the system is at capacity, so the requests it does accept still meet their latency targets.

Why are bounded queues important?

Bounded queues cap memory and waiting time. With an unbounded queue, sustained overload grows latency without limit until every request times out, so the server does only wasted work.

What is a bulkhead?

Isolating resources (thread pools, connections, instances) per dependency or tenant so one slow or overloaded part can't consume capacity needed by the others.

What status code and headers should a shed request return?

Usually 503 (server overloaded) or 429 (client over its quota), with Retry-After so well-behaved clients back off instead of retrying immediately.

How do you decide what to shed first?

Classify requests by business importance and by whether they can be retried, then shed from the least important tier: prefetch and analytics first, normal reads next, critical writes like checkout last.

What is admission control and where should it happen?

Deciding whether to accept a request before spending resources on it, based on current load, priority and whether it can finish within its deadline. Do it as early and cheaply as possible, ideally at the edge or first middleware.

Why is deadline propagation useful under overload?

Each request carries its remaining time budget. Downstream services drop requests that can't finish in time instead of doing work whose caller has already given up, freeing capacity for live requests.

What is a metastable failure, and how do retries cause it?

A state where the system stays overloaded after the original trigger is gone, sustained by its own feedback loop. Retries add load when it's weakest, timeouts trigger more retries, and queues fill with stale work. Retry budgets, jittered backoff, bounded queues and shedding break the loop.

Static concurrency limits vs adaptive limits: trade-offs?

Static limits are simple and predictable but go stale as code, hardware and dependencies change. Adaptive limits (AIMD or latency-gradient based) track real capacity automatically but are harder to reason about and can oscillate, so they need sane floors and ceilings.