Video in progress

The producer is fast, while the consumer (disk or network) is slow. How do you design backpressure in an IO pipeline?

Every buffer between stages has to be bounded, and what happens when it is full is chosen explicitly: wait (block), drop, or slow down the producer. An unbounded queue is not backpressure; it is a delayed OutOfMemoryError.

📖 Answer

A typical example: a service takes 50 thousand events per second from Kafka, compresses them and writes them as files to S3. What happens if S3 slows down for a few minutes? If there is a LinkedBlockingQueue (unbounded by default) in the middle, or an Executors.newFixedThreadPool (which also has an unbounded queue), the heap fills up and the service crashes, and the loss is larger than the outage itself.

Three main strategies:

  1. Blocking. A bounded queue where put() waits when full. With a Kafka consumer this works naturally: you simply don't poll, the offset isn't committed, and the data waits safely on the broker. (You use pause()/resume() only so as not to exceed max.poll.interval.ms.)
  2. Dropping or sampling. Metrics, debug logs: it is fine if some are lost. But the number of dropped items must itself be a metric.
  3. Slowing down the source. For load coming over HTTP, 429/503 + Retry-After; at the TCP level, stop reading from the socket: the kernel window closes and the sender slows down by itself.

In reactive stacks (Reactor, Reactive Streams) it exists through the request(n) protocol, but it only works if every link in the chain respects it. A single unbounded .onBackpressureBuffer() call, or a hidden subscribeOn + unbounded buffer inside, cancels the whole mechanism.

The questions I ask in a review:

  • Where is the buffer between each pair of stages, and what is its limit?
  • What does this stage do when it's full, and does that lead to data loss?
  • Are the queue depth and wait time visible in metrics? A "queue keeps filling" alert comes before the problem turns into an outage.

And on choosing the buffer size: a big buffer absorbs short bursts, but raises latency and the loss during a crash. The limit = the expected burst duration × the throughput difference: calculate it, then check it in a load test.