Video in progress
What happens in a system if the producer sends data faster than the consumer can take it, and how do you apply backpressure?
A buffer or queue in between grows without limit — memory runs out, latency rises, and in the end something falls over. Backpressure means the slow side signals the fast side to "slow down": a bounded queue, blocking, rejecting, or pulling on demand.
📖 Answer
The classic mistake:
ExecutorService pool = Executors.newFixedThreadPool(8);
// uses a LinkedBlockingQueue inside — unbounded
for (Event e : incoming) {
pool.submit(() -> process(e));
}
If input is 10,000 per second and processing is 3,000, the queue grows by 7,000 every second. A few minutes later you get an OutOfMemoryError, and long GC pauses before that.
Use a bounded queue and choose explicitly what to do when it's full:
var pool = new ThreadPoolExecutor(
8, 8, 0, TimeUnit.SECONDS,
new ArrayBlockingQueue<>(1_000),
new ThreadPoolExecutor.CallerRunsPolicy()); // the caller runs it itself — slows down naturally
The options when it's full:
- block or run on the caller — the producer slows down;
- reject — 429/503 over HTTP, and the client tries later;
- drop the oldest — sensor data, price quotes, where only the latest value matters;
- spill to disk — that's exactly what a broker does.
Backpressure at different layers:
- in Kafka it's natural: the consumer pulls, takes at its own pace, and the rest waits on disk. You just need to watch the lag;
- Reactive Streams (Reactor, WebFlux) pass demand upstream through
request(n); - TCP itself has flow control — if the receiver doesn't read, the sender's
writeblocks; - between HTTP services — rate limits, concurrency limits, load shedding.
Make every queue in the system bounded, and decide in advance what happens when it's full. An "unbounded queue" just postpones the problem.
Sign up to mark studied questions and save your progress.