AlgoViz

Thread pool

medium 70 min

A few threads that live long, one queue with a limit, and a loop: take, run, repeat.

Watch lesson5:06

Sizing

Workers, queue length, and the time a task waits

The point: two numbers, workers and queue length, and both come from a question about time.

Workers

Three examples, worked out

WorkWait WCompute COn 8 coresAnd then?
Shrink a picture0 ms200 ms8 + 1 = 9Done
Call a payment service190 ms10 ms8 x (1 + 19) = 160The service allows 40 at once, so 40
Read and compute30 ms30 ms8 x (1 + 1) = 16Measure 12, 16, 20
The middle row is the usual one. The processor is not what is scarce.

Queue

A length is a time

If 40 workers finish 200 tasks per second together, a queue of 1,000 is five seconds of waiting. Choose the longest time a caller may wait, and multiply.

Queue length

Lqueue=tmax×NworkersSL_{queue} = t_{max} \times \frac{N_{workers}}{S}
With at most 0.5 s of waiting, 40 workers and 0.2 s per task: 0.5 x 200 = 100 places.
Python
import mathdef plan(cores, wait_ms, compute_ms, scarce=None, patience_s=0.5):    workers = math.ceil(cores * (1 + wait_ms / compute_ms))    if wait_ms == 0:        workers = cores + 1    if scarce is not None:        workers = min(workers, scarce)    per_second = workers / ((wait_ms + compute_ms) / 1000)    if wait_ms == 0:        per_second = min(per_second, cores / (compute_ms / 1000))    return workers, round(per_second), int(patience_s * per_second)print("pictures", plan(8, 0, 200))print("payments", plan(8, 190, 10, scarce=40))
From four facts to two numbers.
Edit and run it in your browser

Full

What near 100 percent feels like

One worker, random arrivals and random task times (the M/M/1 model)

BusyAverage time in the system, in task times
50 percent1 / (1 - 0.5) = 2
80 percent1 / (1 - 0.8) = 5
90 percent1 / (1 - 0.9) = 10
95 percent1 / (1 - 0.95) = 20
A simple model, not your server. But the shape is true: the last bit of use costs the most waiting. Full use is the goal for a batch at night, not for people who wait.

Response times are high and all workers are busy. What do you do?

BreaksDouble the workers
How
Change the number and look.
Limit
If the database is the bottleneck, it gets more to do at once and becomes slower.
Choose when
Never without a look at where they wait.
WorksLonger queue
How
Accept more.
Limit
The same speed, longer waits, later errors.
Choose when
For short bursts only.
StrongSee where workers stand
How
Take a dump. All in one call: that resource is the limit, protect it. All computing: the cores are. Then refuse early.
Limit
Needs a minute of looking.
Choose when
Always first.