Video in progress
How do you calculate a thread pool size, and how do you verify that decision?
For CPU-bound work it's around the number of cores; for IO-bound work you start from the formula cores × (1 + wait/compute) or from Little's law. But that's only a starting point: the final value is set by load testing and by downstream limits.
📖 Answer
There are two formulas, and both are only for estimating.
CPU-bound (image compression, encryption): N_threads ≈ N_cpu or N_cpu + 1. More threads only add context switches.
IO-bound: N_threads ≈ N_cpu × (1 + W/C), where W is wait time and C is compute time. Say 8 cores, and a request waits 90 ms on the DB and uses 10 ms of CPU: 8 × (1 + 9) = 80.
Little's law looks at it from the other side: concurrency = throughput × latency. With 400 requests per second at 200 ms each, there are on average 80 requests in flight at any moment. If the pool is smaller than that, the queue grows.
In practice, though, the bottleneck often isn't threads:
- if the Hikari pool has 20 connections, 180 of 200 threads are waiting for a connection;
- if a partner API limits you to 50 requests per second, adding threads only produces more 429 errors.
Here's what I do:
- I take a starting value from the formula.
- With a load test (Gatling/k6), I change the pool size and plot p99 latency and throughput.
- I pick a value a bit below the "knee" of the graph.
- In prod I monitor
executor.active,executor.queuedand the time spent waiting in the queue.
If one JVM has several pools (Tomcat, @Async, a Kafka consumer), look at them together by their sum: even if each one is "right" on its own, together they can choke the CPU.
Sign up to mark studied questions and save your progress.