Course contents

07. Messaging and Event-Driven Systems Lesson 10 of 10

Backpressure

Watch producers outrun consumers: an unbounded queue grows forever, a bounded one sheds load, flow control slows producers, an edge limit rejects early.

15 minIntermediate7 steps
Loading the interactive simulation…
Loading the knowledge check…

Summary

  • When the arrival rate exceeds the processing rate, a backlog grows without limit; a queue cannot fix that.
  • An unbounded queue hides overload as rising latency; a bounded queue rejects early and caps waiting at about capacity ÷ throughput.
  • Flow control (blocking puts, credits, windows) slows producers that can wait, and moves the pressure upstream.
  • Whatever cannot wait must be shed, and the earliest point (the edge) is the cheapest.
  • Backpressure buys time; only more capacity or cheaper work removes a sustained gap.
Deep diveHow it works, trade-offs, failure modes, misconceptions and the interview angle.

What it is

Backpressure is any mechanism that lets a slower downstream component push back on a faster upstream one, so that work arrives no faster than it can be handled. The push-back can be waiting (the producer is blocked or only sends what it was granted) or refusing (the producer gets an error and must slow down, retry later or give up). Load shedding is the refusing half: deliberately rejecting work you cannot finish.

Why it exists

A queue decouples producers from consumers in time, but not in capacity. If messages arrive at 60 per second and are processed at 40, the backlog grows by 20 every second, forever. With an unbounded queue nothing fails at first: every publish succeeds, while the time from publish to processing climbs steadily. Eventually memory or disk runs out, messages expire, or the results arrive too late to matter, and by then the backlog takes a long time to drain. Backpressure makes the overload visible early and decides on purpose where the excess goes.

How it works

Bounded queues. Give every queue and buffer a limit. When it is full, a publish is rejected immediately (or blocks, see below). The limit also caps waiting: by Little's law, a full queue of N items drained at rate X holds a new item for about N ÷ X. A queue of 100 drained at 40 per second means at most about 2.5 s of waiting.

Blocking and credit-based flow control. If the producer can wait, it should. The simplest form is a blocking put on a bounded in-process buffer. Across a network, the receiver grants credit and the sender stays within it: TCP's receive window, HTTP/2 and gRPC flow-control windows, AMQP consumer prefetch, and Reactive Streams' request(n) all work this way. The pressure moves upstream hop by hop: the producer slows down, so its own callers wait or its own buffers fill.

Shedding at the edge. Pressure that travels upstream eventually reaches a component that cannot wait: a public client, a sensor, a partner's webhook. There the system must say no. A gateway or load balancer enforcing a rate limit (token bucket, leaky bucket) answers the excess with 429 Too Many Requests, ideally with Retry-After, before the request consumes any downstream resources. Overloaded services can also return 503 and shed lower-priority traffic first.

Signals for producers. Rejections only help if producers react: retry with exponential backoff and jitter, cap retries, and degrade (skip a non-essential step, batch more) instead of hammering. A producer that retries instantly turns load shedding into a retry storm.

Capacity. Backpressure keeps the system healthy during overload; it does not process the rejected work. For lasting load, add consumers or make each message cheaper, ideally with autoscaling on queue depth or message age, with the bounded queue and edge limit covering the minutes autoscaling takes to react.

When to use it

  • Always: every queue, buffer, thread pool and connection pool should have an explicit bound and a defined behaviour when full.
  • Flow control for internal pipelines where producers can safely wait (stream processing, batch imports, service-to-service streaming).
  • Edge rate limiting and load shedding for public APIs, ingestion endpoints and anything exposed to traffic you do not control.

When not to

  • Do not block producers that hold scarce resources while waiting (request threads, database transactions, locks): blocking there spreads the overload to unrelated work.
  • Do not rely on blocking for public clients; they will time out and retry, adding load.
  • Do not bound a queue so tightly that ordinary bursts are rejected; size it for the burst you want to absorb and the wait you can tolerate.

Trade-offs

Choice You gain You pay
Unbounded queue No rejections, simplest code Unbounded latency and memory; overload discovered late
Bounded queue, reject when full Bounded wait, early explicit signal Rejected work; producers must handle errors
Blocking / credit-based flow control No drops while every hop can wait Pressure (and latency) moves upstream; risk of blocked threads
Rate limit at the edge Cheapest rejection, protects everything behind it Must pick limits; may reject when there was spare capacity
Larger buffer Absorbs longer bursts Longer worst-case wait; slower drain after overload
Autoscaling consumers Removes sustained overload Reacts in minutes; costs money; may overload the next dependency

Alternatives

  • Drop oldest / sample: for telemetry and real-time feeds, discard stale messages instead of rejecting new ones.
  • Batching: let consumers process many messages per operation to raise throughput under load.
  • Priority queues and load shedding by class: keep serving important traffic (checkout) while shedding the rest (recommendations).
  • Graceful degradation: answer with less (cached or partial results) instead of nothing.
  • Admission control based on latency: adaptive concurrency limits that lower the number of accepted requests when latency rises.

Failure modes

  • Silent backlog: an unbounded queue grows for hours while every dashboard shows success; alerting on depth and the age of the oldest message catches it.
  • Bufferbloat: buffers everywhere along the path each add waiting time, so total latency explodes long before anything rejects.
  • Retry storms: producers retry rejections immediately and multiply the load.
  • Blocked threads: a producer blocks inside a request handler; the thread pool fills and unrelated endpoints stall.
  • Rejecting too deep: work is accepted at the edge, partly processed, and rejected three hops later, which wastes the work done so far.
  • Slow drain: after the overload ends, a huge backlog takes a long time to clear, and all of it is stale.

In production

Give every queue, buffer and pool an explicit bound and document what happens when it is full. Alert on queue depth and on the age of the oldest message, not just on errors. Rate limit at the edge per client or tenant, return 429 with Retry-After, and make producers back off with jitter. Prefer flow control between internal services that can wait, but never block a request thread on it. Autoscale consumers on backlog or message age, and load test past saturation to see where the system sheds. For an unbounded backlog under a traffic surge, try the Queue Backlog scenario in the Failure Lab.

Common misconceptions

  • "No errors means the system is coping." An unbounded queue reports success while latency grows without limit.
  • "A bigger queue fixes overload." It only delays the moment it fills, and makes every message wait longer.
  • "Backpressure means dropping messages." Dropping is one form; waiting (flow control) is the other. Both are deliberate.
  • "Rate limiting and backpressure are the same." A rate limit is a fixed admission rule at one point; backpressure is a signal from downstream capacity that propagates upstream.

Interview angle

When a design has a queue or a high-volume ingestion path, interviewers ask "what happens when consumers fall behind?" A strong answer quantifies the gap ("60 in, 40 out, +20/s, 72,000 per hour"), bounds the queue, says where load is shed (429 at the gateway, per tenant), how producers react (backoff with jitter), how long accepted messages may wait (capacity ÷ throughput), and how capacity catches up (autoscaling on message age). Mentioning that blocking moves pressure upstream until something can say no shows you understand the whole chain.

Model assumptions

The simulation is a simplified model, not a benchmark. Producers publish at the stated rate (Poisson). Two workers (three from the capacity step on) with 4 slots each take about 200 ms per message (lognormal, cv 0.3), about 40 messages per second for two workers. The unbounded queue is a capacity of 100,000; the bounded queue holds 100 and rejects publishes immediately when full. The ingest gateway admits traffic with a token bucket (36 per second, burst 20; later 60 per second, burst 40) and rejects the rest at once. The engine cannot block a producer: the credit tokens are a scripted illustration, and their effect is modelled by lowering the producers' rate to about 36 per second. Message wait is measured from publish to acknowledgement. Latency percentiles (P50, P95, P99) are computed over the requests that succeeded in the last 5 simulated seconds: failed, rejected and timed-out requests are not in them and are counted in the Errors tile, which is always shown next to them. Rejecting or timing out the slowest requests therefore improves the percentiles while making the system less reliable, so read the two together. Numbers show behaviour and orders of magnitude only.

The lesson as textEvery step of the simulation, written out.
  1. 1. Producers slower than consumers

    Producers publish 30 messages per second. Two workers with 4 slots each take about 200 ms per message, so together they can process about 40 per second. The queue stays short: a message waits a fraction of a second before a worker picks it up.

    As long as the arrival rate stays below the processing rate, a queue only smooths small bursts. Backpressure is about the other case.

    Scene: Producers publish 30 messages per second to the Work Queue; two workers can process about 40 per second. The queue holds only a few messages and nothing fails.

    Key idea: A queue is stable only while the average arrival rate is below the consumers’ processing rate.

  2. 2. Faster in than out: the backlog never stops growing

    Producers now publish 60 per second; consumers still manage about 40. The queue has no practical limit, so every message is accepted and the producers see no errors at all.

    But the backlog grows by about 20 messages every second, and each new message waits behind all of them: the time from publish to processing climbs steadily. Nothing pushes back, so nothing tells the producers to slow down until memory, disk or users’ patience runs out.

    Scene: Producers publish 60 messages per second while workers process about 40. Every publish succeeds, but the queue grows by about 20 messages per second and messages wait longer and longer.

    Key idea: An unbounded queue turns overload into ever-growing latency, silently. Accepting work you cannot finish is not success.

  3. 3. Bound the queue and reject the overflow

    The queue is now bounded at 100 messages. Once it is full, a publish is rejected immediately and the producer gets an error it can act on: retry later, degrade, or report it. That is load shedding at the queue.

    About a third of publishes are rejected, roughly the 20 of 60 per second that consumers cannot handle. In exchange, the backlog never exceeds 100, and every accepted message is processed within about 100 ÷ 40 ≈ 2.5 s. Bounded latency for what you accept beats unbounded latency for everything.

    Scene: The queue holds at most 100 messages. When it is full, publishes are rejected at once, so about a third of them fail, but the backlog stays at or below 100 and accepted messages wait at most a few seconds.

    Key idea: A bounded queue caps waiting time (≈ capacity ÷ processing rate) and turns overload into an explicit, early signal.

  4. 4. Push back on the producer instead

    When producers are your own services, they can wait instead of failing. With credit-based flow control the consumer side grants credits ("I can take 8 more") and the producer only sends what it was granted: TCP windows, HTTP/2 and gRPC flow control and Reactive Streams request(n) all work this way. A blocking put on a full bounded buffer is the simplest version.

    The scripted tokens show credits flowing upstream before each batch. The effect, modelled here by the producers slowing to about 36 per second: no rejections and a short queue. The waiting moves upstream: the producers now buffer or slow their own callers, so the pressure has to end somewhere that can say no.

    Scene: Scripted credit tokens travel from the queue to the producers every half second, each followed by a batch of messages. The producers send about 36 per second, nothing is rejected and the queue stays short.

    Key idea: Backpressure propagates “slow down” upstream. It avoids drops only if every hop can wait, and the first hop that cannot must shed load.

  5. 5. Rate limit at the edge

    Not every producer can be slowed down: public clients and partners just keep sending at 60 per second. An ingest gateway in front of the queue now enforces a token bucket of 36 per second (burst 20) and answers the excess with 429 Too Many Requests before it costs anything downstream.

    The queue never fills: rejections happen at the gateway, none at the queue, and the backlog stays short. Rejecting at the edge is cheaper and clearer than rejecting deep inside, and a 429 with Retry-After tells well-behaved clients how to back off.

    Scene: Producers send 60 messages per second to an ingest gateway that admits about 36 per second and rejects the rest with 429. The queue stays short and never rejects anything.

    Key idea: Shed load as early as possible: a rate limit at the edge protects every component behind it.

  6. 6. Backpressure buys time; capacity fixes it

    Shedding load keeps the system healthy, but every rejected message is work not done. If the load is real and lasting, add consumers. A third worker raises processing to about 60 per second, and the gateway limit is raised to match (60 per second, burst 40).

    At 50 per second almost nothing is rejected and the queue stays short. Autoscaling consumers on queue depth or message age does this automatically, but it reacts in minutes; the bounded queue and the edge limit cover the gap.

    Scene: A third worker raises processing capacity to about 60 messages per second and the gateway admits up to 60 per second. At 50 per second almost nothing is rejected and the queue stays short.

    Key idea: Use backpressure and load shedding to survive overload, and capacity (scaling consumers) to end it.

  7. 7. Every queue needs a limit and a plan for full

    When producers outrun consumers, something has to give. An unbounded queue hides it until latency or memory explodes. A bounded queue rejects early and keeps latency bounded. Flow control slows producers that can wait. A rate limit at the edge sheds what cannot be slowed before it costs anything. More consumers remove the overload for good.

    To practise diagnosing an unbounded backlog under a traffic surge, try the Queue Backlog scenario in the Failure Lab.

    Scene: Producers send 50 messages per second through the rate-limited ingest gateway to a bounded queue consumed by three workers. Nothing is rejected and the queue stays short.

    Key idea: Bound every queue, decide where load is shed, propagate backpressure upstream, and scale on queue age.