Skip to content

Backpressure: Let Slow Consumers Slow Down Fast Producers

How bounded buffers, watermarks and explicit rejection let a slow downstream push back on fast producers instead of buffering until something crashes.

18 min readSystem pattern

Keep every buffer between a producer and a consumer bounded, and when it fills, send an explicit signal upstream (block, reject or reduce credit) so the producer's rate converges to what the consumer can actually sustain. Data waits where it is cheap and safe to wait, not in a process that will be OOM-killed.

Backpressure is how a system says "not now" to whatever is feeding it. A stage that can't keep up doesn't quietly pile work into memory. It tells its producer to slow down, wait, or try later, and that signal travels back up the chain until it reaches something that can afford to hold the data. This guide uses one scenario throughout. Larkspur Grid's meter-ingest gateway accepts readings from 120,000 smart electricity meters and writes them to a time-series database. It ran fine for a year. Then a routine compaction slowed the database down, the gateway's in-memory queue grew without limit, and the pod was killed with minutes of readings still in memory. The fix was not a bigger queue. It was a bounded one that can refuse work.

The problem

A situation where the obvious design starts to hurt.

Larkspur's meters each send a batch of readings every 10 seconds, about 12,000 readings per second in total. The gateway, a Node.js service on a pod with a 4 GiB memory limit, validated each batch, pushed it onto an in-process array and returned 202 straight away. A writer loop took rows off that array and batch-inserted them into the time-series database. That database normally absorbs about 18,000 rows per second, so the array stayed close to empty.

One night the database started a 20-minute compaction and insert throughput dropped to about 5,000 rows per second. The gateway kept returning 202 at 12,000 per second, so the array grew by 7,000 readings every second. Each parsed reading took roughly 1.2 KB of heap. After about eight minutes the pod reached its 4 GiB limit and the kernel killed it. Everything still in the array, around 3.3 million readings already acknowledged to meters, was lost. The meters had received 202 and had deleted those readings from local flash.

The restart made things worse. Meters that saw connection resets retried at the same moment, the new pod filled its array in under a minute, and it was killed again. The service flapped for 25 minutes.

The root cause was not the slow database. Slow dependencies are normal. The root cause was a queue with no bound and an API that said yes to everything, so the only feedback the system ever gave was a crash.

The solution

What the pattern proposes.

Bound the buffer and make the gateway able to say no.

The in-process array became a bounded buffer with a capacity of 60,000 readings, about 72 MB and roughly 5 seconds of peak inflow. Admission is all-or-nothing per batch. When depth reaches the high watermark of 48,000, the gateway stops admitting and answers new batches with 503 and a Retry-After of 5 to 15 seconds, randomised per response. It resumes only once the writer has drained the buffer to the low watermark of 24,000. The gap between the two watermarks keeps the gateway from switching between accepting and rejecting on every request.

The writer pulls 500 rows at a time and only asks for more after an insert succeeds, so its demand is set by the database's real speed. A 202 now means the reading is inside a bounded buffer that the writer will flush within seconds. It no longer means a reading went into a heap that might never be flushed.

The meters already had six hours of flash storage. On a 503 they keep the batch, wait for Retry-After, and resend it together with newer readings. During the next compaction the gateway admitted roughly 5,000 readings per second and rejected the rest. Meters spooled about 8.4 million readings across the fleet. Once compaction finished, the 6,000 rows per second of spare write capacity cleared the backlog in about 23 minutes. Memory never went past 100 MB and no reading was lost.

The pattern is the chain: a bounded buffer, an explicit signal when it fills, and a producer that can hold data somewhere durable while it waits.

An everyday analogy

The same idea, outside software.

Think of a bakery whose display case holds 40 loaves. The bakers don't keep baking and stacking bread on the floor when sales are slow. When the case is nearly full they stop shaping dough and leave it proofing in the fridge, where it keeps for a day. They start again once the case has emptied to about half. The fridge is the meter's flash storage: a slower, cheaper place where work can wait without spoiling, and the full case is the signal that tells the bakers to stop.

Structure

The pieces and how they relate.

Larkspur meter ingest: the bounded buffer's depth drives 503 responses back to meters, which spool readings to local flash.Smart meters calls Ingest gateway (POST /readings). Ingest gateway sends to Smart meters (202 or 503). Smart meters sends to Meter flash spool (spool on 503). Ingest gateway sends to Bounded buffer (offerAll(batch)). Batch writer calls Bounded buffer (drain(500)). Batch writer calls Time-series DB (batch insert). Bounded buffer sends asynchronously to Metrics (depth samples). Ingest gateway sends to Above high watermark. Batch writer sends to Pull, don't push.Smart meters120k devices, batchevery 10 sMeter flash spool6 h of readings perdeviceIngest gatewayadmits or rejectswhole batchesAbove highwatermark503 + Retry-After5-15 sBounded buffercap 60k, high 48k,low 24kMetricsdepth, reject rate,paused timeBatch writerpulls 500 rows perinsertPull, don't pushnext drain onlyafter insert acksTime-series DB18k rows/s, 5kduring compactionPOST /readings202 or 503spool on 503offerAll(batch)drain(500)batch insertdepth samples
Larkspur meter ingest: the bounded buffer's depth drives 503 responses back to meters, which spool readings to local flash.

Participants

Producer (smart meters)
Generates readings at a rate it doesn't control. It must be able to hold data when refused. Here that is six hours of flash per meter, and it honours Retry-After instead of retrying on its own schedule.
Admission point (ingest gateway)
The one place that decides whether work enters the system. It checks buffer state before acknowledging, and it returns 202 only when the whole batch fits.
Bounded buffer
A fixed-capacity queue that smooths short bursts. Its high and low watermarks turn depth into a two-state signal, accepting or paused, with hysteresis between them.
Consumer (batch writer)
Pulls a fixed chunk only after the previous write succeeded. Its pace is the true capacity of the system, and backpressure exists to carry that pace upstream.
Downstream store (time-series DB)
The slowest stage and the reason backpressure is needed. Its throughput changes with compaction, replication and disk pressure, so no fixed rate limit can track it.
Observability (metrics)
Records buffer depth, reject rate and time spent paused. Backpressure that works is silent to users, so this is how operators see that the system is shedding load and why.

Pseudocode

The solution to the scenario, language-neutral.

class BoundedBuffer:
  capacity, high, low
  items = queue()
  accepting = true

  offerAll(batch):
    if not accepting or size(items) + len(batch) > capacity:
      return false                  # caller must push back
    append all of batch to items
    if size(items) >= high:
      accepting = false             # pause admissions
    return true

  drain(max):
    out = take up to max items from front
    if not accepting and size(items) <= low:
      accepting = true              # resume with hysteresis
    return out

on POST /readings(batch):          # gateway
  if len(batch) > 500: return 413
  if buffer.offerAll(batch):
    return 202
  return 503 with Retry-After = random(5, 15) seconds

writer loop:                        # consumer pulls at its own pace
  forever:
    rows = buffer.drain(500)
    if rows is empty: sleep 50 ms; continue
    insert rows into tsdb with timeout 2 s, retry with backoff
    # next drain happens only after this insert finishes

meter on 503:                       # producer holds data durably
  keep batch in flash
  wait Retry-After
  resend oldest spooled readings first, merged up to 500 per batch

The code

The same solution in TypeScript, Python and PHP.

type IngestResult = { status: 202 } | { status: 503; retryAfterSeconds: number };

export class BoundedBuffer<T> {
  private items: T[] = [];
  private head = 0;
  private accepting = true;

  constructor(
    private readonly capacity: number,
    private readonly highWatermark: number,
    private readonly lowWatermark: number,
  ) {
    if (!(lowWatermark < highWatermark && highWatermark <= capacity)) {
      throw new Error("require low < high <= capacity");
    }
  }

  get size(): number {
    return this.items.length - this.head;
  }

  get isAccepting(): boolean {
    return this.accepting;
  }

  // All-or-nothing: a batch is either fully admitted or fully rejected.
  offerAll(batch: readonly T[]): boolean {
    if (!this.accepting || this.size + batch.length > this.capacity) {
      return false;
    }
    for (const item of batch) this.items.push(item);
    if (this.size >= this.highWatermark) this.accepting = false;
    return true;
  }

  drain(maxItems: number): T[] {
    const n = Math.min(maxItems, this.size);
    const out = this.items.slice(this.head, this.head + n);
    this.head += n;
    // Compact occasionally so drain stays O(n) without unbounded array growth.
    if (this.head >= 4096 && this.head * 2 >= this.items.length) {
      this.items = this.items.slice(this.head);
      this.head = 0;
    }
    if (!this.accepting && this.size <= this.lowWatermark) this.accepting = true;
    return out;
  }
}

export function ingest<T>(buffer: BoundedBuffer<T>, batch: readonly T[]): IngestResult {
  if (buffer.offerAll(batch)) return { status: 202 };
  // 5-15 s with jitter so rejected producers do not return in lockstep.
  return { status: 503, retryAfterSeconds: 5 + Math.floor(Math.random() * 11) };
}

// Demo: capacity 10, pause at 8, resume at 3.
const buffer = new BoundedBuffer<number>(10, 8, 3);
for (let i = 0; i < 4; i++) {
  const r = ingest(buffer, [i, i, i]);
  console.log(`batch ${i}: status=${r.status} size=${buffer.size}`);
}
buffer.drain(4);
console.log(`after drain(4): size=${buffer.size} accepting=${buffer.isAccepting}`);
buffer.drain(3);
console.log(`after drain(3): size=${buffer.size} accepting=${buffer.isAccepting}`);

When to use it

Situations where it pays off.

  • A consumer's throughput varies with things you don't control, such as database compaction, a third-party API's latency or GC pauses, while producers keep a steady or bursty rate.

    A fixed rate limit is either too low on good days or too high on bad ones. A depth-based signal follows the consumer's actual speed from moment to moment.

  • Any in-process queue, channel or stream sits between two stages and currently has no maximum size.

    An unbounded queue turns a slow consumer into memory growth and then a crash that loses everything already acknowledged. Bounding it moves the failure to a clean, visible rejection.

  • Producers can hold or regenerate data: devices with local storage, upstream services with their own durable queue, or clients that can retry.

    Backpressure only helps if refused work has somewhere safe to wait. Where that holds, a 503 costs a bit of latency and loses nothing.

  • You are chaining streams or reactive pipelines (Node streams, Reactive Streams, gRPC streaming, Kafka consumers) where one stage can outpace the next.

    These frameworks have built-in demand signalling (highWaterMark, request(n), HTTP/2 flow-control windows, pause and resume). Using it correctly is backpressure. Wrapping a stage in an unbounded buffer turns it off.

How to implement it

Steps to introduce it in existing code.

  1. Find every buffer on the path: in-process arrays, channels, thread-pool queues, socket send buffers, broker topics. Give each one an explicit maximum based on memory and on how many seconds of delay you can accept. At Larkspur that was 60,000 readings, about 5 seconds and 72 MB.

  2. Decide what full means for each producer: block the caller (fine within one process), reject with a retryable status (right for clients across a network), or drop (only for data you can afford to lose, such as debug traces). Write the choice down per stage.

  3. Add high and low watermarks so the stage pauses near full and resumes well below it. A gap of 30 to 50 percent of capacity stops the accept/reject state from flipping on every batch.

  4. Make admission all-or-nothing per unit of work, and cap the unit size so one request can't fill the buffer. The gateway returns 413 for batches over 500 readings.

  5. Switch consumers from push to pull. The writer asks for the next 500 rows only after the database acknowledges the previous insert, so its demand matches what the store can take.

  6. Return a retryable signal with a hint: 503 or 429 plus a randomised Retry-After. Producers must honour it, keep the data, and resend oldest first.

  7. Instrument buffer depth, the fraction of time spent paused, and the reject rate per producer. Alert on sustained pausing, not on a single rejection. Backpressure doing its job should be visible but not paged at 3 a.m.

Pros and cons

What you gain and what you pay.

Pros

  • Memory stays flat under any downstream slowdown. The gateway peaked under 100 MB during a 20-minute compaction that used to OOM-kill it in eight minutes.
  • Acknowledgements become honest: 202 means the data is in a bounded buffer that will be flushed within seconds, not in a heap that might vanish.
  • The system adapts to the consumer's real throughput automatically, with no hand-tuned rate limit to keep in sync with the database's performance.
  • Overload becomes a measurable, recoverable state (depth, reject rate) instead of a crash loop that has to be diagnosed from core dumps.

Cons

  • Producers have to cooperate. A client that ignores 503 or has nowhere to store data turns backpressure into data loss at the edge.
  • End-to-end latency rises during slowdowns. Larkspur readings arrived up to 25 minutes late after compaction, which hurt the near-real-time outage dashboard.
  • Pushing back on one shared buffer slows every producer, including high-priority ones, unless you add per-tenant or per-priority buffers.
  • Watermarks and capacity need tuning, and wrong values either reject too early on normal bursts or still allow too much memory before pausing.

Trade-offs

Decisions you'll have to make, each with its price.

  • Buffer capacity of 60,000 readings (about 5 s at peak) instead of 600,000 (about 50 s)

    You gain72 MB of heap instead of about 720 MB, and admitted data waits at most a few seconds, so a crash loses little.

    You payBursts longer than about 5 seconds reach the meters as 503s even on a healthy day, which adds retry traffic and latency for those meters.

  • Reject with 503 and Retry-After instead of holding the HTTP request open until space frees up

    You gainGateway connections and workers stay free. Overload costs one short response instead of thousands of hanging sockets.

    You payEach rejection is a wasted round trip and a resend, and producers must implement spooling and honour the header correctly.

  • Hysteresis with high 48,000 and low 24,000, instead of a single threshold

    You gainThe gateway switches state a few times per slowdown instead of on every batch, so meters see a stable answer.

    You payOnce paused, it rejects until 24,000 rows have drained, about 5 seconds at 5,000 rows per second, even though capacity freed up earlier.

  • One shared buffer instead of separate buffers per priority class

    You gainSimple to run and size, and all spare capacity is shared.

    You payA firmware-triggered resend of 3 days of history from 10,000 meters pushes back on live outage readings too. Larkspur later added a separate 10,000-reading buffer for priority traffic.

How it fails

What goes wrong in production and how to prevent it.

  • Rejected producers retry in sync, so the buffer drains, reopens, and is refilled in one second by the whole fleet

    What to doRandomise Retry-After per response (5 to 15 s), require jittered exponential backoff on the client, and cap resend batches at 500 so a reopening can't be swallowed in one burst.

  • A producer has no durable place to wait, such as an older meter model with 2 minutes of RAM, so long backpressure becomes silent loss at the edge

    What to doInventory producer buffering capacity before relying on rejection. For that fleet, add a durable intermediate queue in front of the gateway with 24 h retention, and alert when its lag exceeds 30 minutes.

  • An unbounded buffer hides elsewhere: a thread-pool queue, a logging library, a client SDK, or the socket layer, so memory still grows

    What to doAudit every hop and set explicit limits (pool queue size, stream highWaterMark, HTTP/2 window). Load-test with the database throttled to 25 percent and confirm resident memory stays flat.

  • Backpressure is in effect for hours and nobody notices, because users see slower data rather than errors

    What to doExport time spent paused and reject rate. Page when the buffer has been paused for more than 50 percent of a 10-minute window, because by then producers are using up their spool.

  • A cycle between stages, where the writer's errors go back into the same full buffer, deadlocks the pipeline

    What to doSend failed rows to a separate bounded retry queue or dead-letter store, never back into the buffer that is pushing back.

In a system design interview

When to bring it up and how to explain it.

Bring it up whenever a design has a fast producer and a slower or variable consumer: ingestion pipelines, log shipping, webhook fan-out, streaming APIs, or any time you draw a queue between two boxes and the interviewer asks what happens when the consumer slows down.

What you could say

I'd make sure no buffer in this path is unbounded, because an unbounded queue just converts a slow database into an out-of-memory crash, and we lose everything we already acknowledged. So the gateway gets a bounded buffer sized to a few seconds of peak traffic, say 60,000 readings, about 70 MB. It admits whole batches or nothing. When depth crosses a high watermark at 80 percent, it stops accepting and returns 503 with a jittered Retry-After. It resumes once the writer has drained to 40 percent, so it doesn't flap. The writer pulls 500 rows at a time and only asks for more after an insert commits, so the database's real throughput sets the pace for the whole chain. The important assumption is that producers can hold data. These meters have hours of flash, so a 503 just means the reading arrives later. If a producer couldn't hold data, I'd put a durable queue with a retention bound in front instead. I'd alert on time spent paused, because when backpressure is working nothing errors, it just gets slower.

Likely follow-ups

How does this differ from rate limiting?

A rate limit is a fixed contract per client, for example 1 request per 10 s per meter, and it protects against misbehaving producers. Backpressure follows the consumer's current capacity, which changes with compaction or failover. I'd use both: the limit catches a buggy device, and backpressure handles a slow database.

How would you pick the watermarks?

Capacity comes from memory budget and the delay I'm willing to hide, here about 5 s. The high watermark leaves room for in-flight batches already being parsed. The low watermark sits far enough below it that resuming lasts a few seconds at the degraded drain rate. Then I'd load-test with the database throttled and adjust based on reject rate on normal days.

What if one tenant floods the system?

A shared buffer would push back on everyone. I'd give each tenant or priority class its own bounded buffer, or a weighted fair share of one, so a bulk backfill gets 503s while live readings keep flowing.

Would you put Kafka here instead?

If producers couldn't spool, yes. A durable log buys hours of buffering. It still needs retention and quota limits, though, and consumer lag becomes the signal. Producers then get backpressure from broker quotas or failed acks instead of from my 503.

Relations with other guides

Patterns it's often confused or combined with.

Common questions

Short answers to the usual doubts.

Isn't a bigger buffer, or Kafka, enough?

A bigger buffer only delays the crash. At a 7,000 per second deficit, even 10 GB fills in about 20 minutes. A durable log like Kafka moves the problem from RAM to disk and retention. It is a better place to wait, but you still need a retention bound, a lag alert, and a rule for what producers do when the topic or its quota is full.

Should I block the producer or reject it?

Inside one process, blocking is usually right. An awaited write on a full channel costs nothing and propagates naturally. Across a network, prefer fast rejection with a retryable status. A blocked HTTP request holds a socket, a worker and a client timeout, and if enough of them pile up the gateway runs out of connections.

When is dropping data acceptable instead of pushing back?

When the data is sampled or replaceable: debug traces, cursor positions, a sensor value that will be superseded in 10 seconds. Larkspur drops gateway debug logs under pressure but never billing readings. Make the drop explicit and counted, never a side effect of a full queue.

Now, practise it

Put it to work straight away.

Tests, exercises and problems that use what you've just read.

Next guide5 of 5 · Messaging and scaleDataLoader Batching: Collapse N+1 Lookups Into One Call per RequestRead the next one