Video in progress

How does ThreadPoolExecutor's unbounded queue lead to a slow OOM, and how do you design the pool?

Inside Executors.newFixedThreadPool there is an unbounded LinkedBlockingQueue. If tasks arrive faster than they are processed, the queue grows without limit, and each task holds its request data. The heap fills slowly, and latency goes up first. You need to bound the queue and have an explicit policy for when it is full (reject, backpressure).

📖 Answer

// harmless looking from the outside
ExecutorService pool = Executors.newFixedThreadPool(16);
// inside: new LinkedBlockingQueue<Runnable>()  — Integer.MAX_VALUE capacity

The scenario: webhooks arrive, and each one does pool.submit(() -> process(payload)). An external API slowed down, and process takes 2 s instead of 50 ms. The incoming flow didn't change. The queue holds 10 thousand, 100 thousand, a million tasks, each with a 20 KB payload. Within minutes the heap is full. Before that, a task at the end of the queue waits for minutes, meaning those tasks are already pointless.

In a heap dump this is clearly visible: millions of LinkedBlockingQueue$Node, with the pool object as the dominator.

The right design:

var pool = new ThreadPoolExecutor(
        16, 16, 0, TimeUnit.SECONDS,
        new ArrayBlockingQueue<>(500),                    // the bound
        Thread.ofPlatform().name("webhook-", 0).factory(),   // Java 21
        new ThreadPoolExecutor.AbortPolicy());            // when full: RejectedExecutionException

What to do when it is full is a business decision:

  • AbortPolicy: return 429/503 upstream, and the client retries later;
  • CallerRunsPolicy: the calling thread runs the task itself, which is natural backpressure (the HTTP threads slow down);
  • put the task into a persistent queue (Kafka, DB), if you can't afford to lose it.

Monitoring: queue length, active threads, number of rejected tasks, with Micrometer's ExecutorServiceMetrics. Set an alert on queue length.

The same problem shows up with unbounded fan-out through CompletableFuture.supplyAsync, with Reactor's unbounded buffers, and when reading from a Kafka consumer and dropping into an internal queue. The rule is one: every queue in the system should be bounded.