Video in progress

How do you build backpressure at the thread pool level in an asynchronous processing system?

The main idea is to give up the unbounded queue: a bounded queue, CallerRunsPolicy or an explicit rejection when it's full, and a Semaphore to limit the number of concurrent jobs. That way load slows down the producer, not the memory.

📖 Answer

Without backpressure, load doesn't disappear anywhere. It piles up in the queue, which means in the heap. First latency grows, then GC, then OOM.

Option 1: a bounded queue plus CallerRunsPolicy:

ThreadPoolExecutor pool = new ThreadPoolExecutor(
        16, 16, 0, TimeUnit.SECONDS,
        new ArrayBlockingQueue<>(1_000),
        Thread.ofPlatform().name("enrich-", 0).factory(),   // Java 21
        new ThreadPoolExecutor.CallerRunsPolicy());

When the queue is full, the thread that submitted the task runs it itself, and during that time it doesn't submit new ones. For a Kafka consumer that's a natural slowdown. But on an HTTP thread it raises the latency of that request, and there a fast rejection (503 or 429) is often better.

Option 2: an "in-flight" limit with a Semaphore:

private final Semaphore inFlight = new Semaphore(200);

CompletableFuture<Result> submit(Request r) {
    if (!inFlight.tryAcquire()) {
        return CompletableFuture.failedFuture(new OverloadedException());
    }
    return client.send(r).whenComplete((res, ex) -> inFlight.release());
}

This is especially needed for async clients: they don't block a thread, so the pool size limits nothing.

Option 3: at the source itself: in Kafka, max.poll.records and pause()/resume() on the consumer; in reactive streams, request(n).

Which one to choose depends on a business question: "what should happen when there's too much load?" Wait, reject, or drop stale data. Settle that first.