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

Operate

What to measure, what travels with a task, what leaks

The point: the pool sees all the work of your program. Measure there, and carry the request's context across, cleanly.

Code

Wrap every task

Time, deadline, context

Waiting and running are two different times. Only together with their difference do they tell you what to change.

import threadingimport timefrom contextvars import ContextVarrequest_id = ContextVar("request_id", default="none")class Stats:    def __init__(self):        self._lock = threading.Lock()        self.done = self.failed = 0        self.longest_wait = self.longest_run = 0.0    def add(self, waited, ran, ok):        with self._lock:            self.done += 1            self.failed += not ok            self.longest_wait = max(self.longest_wait, waited)            self.longest_run = max(self.longest_run, ran)

Line 5

Context that belongs to a request: an id for the log. It lives beside the thread, and the thread serves many requests.

1 of 2

Read the two times

WaitRunMeansDo
ShortShortHealthyNothing
LongShortToo few workers, or a burstMore workers if the cores are free
ShortLongThe task or its dependency is slowLook inside the task
LongLongThe dependency is slow and everything piles upLimit, break the circuit, refuse

Five gauges for each pool

  • Busy workers

    All busy for a minute is an alarm, even if nothing has failed yet.

  • Queue length

    Better as seconds: the age of the oldest task.

  • Refused

    Each refusal is a user. Count by reason: full, closed, expired.

  • Failed

    Errors stored in futures that nobody reads are seen only here.

  • Done per second

    Flat while the queue grows: the pool is the bottleneck.

Leaks

What stays in a thread

Left behindSeen asGuard
Thread-local valueUser B sees the name of user ASet and clear in one wrapper
Interrupt flagThe next task stops for no reasonClear it before the next task, as Java's pool does
Open transactionThe next task writes into itScope it inside the task
Lock still heldA hang, much laterwith or finally
A thread per task cleans up by dying. A pool does not. Everything that stuck to the thread stays.

Separate

Bulkheads

Reports take 20 s, clicks take 20 ms, and both use one pool of 20.

BreaksOne pool for everything
How
Simple.
Limit
Twenty reports, and no click is answered for 20 s.
Choose when
Only if all tasks are alike.
WorksPriorities
How
Clicks first in the queue.
Limit
A running report is not pushed aside. Twenty of them still block.
Choose when
Together with a limit on reports.
StrongTwo pools
How
Sixteen for clicks, four for reports, each with its own queue and policy.
Limit
Four workers may be idle while clicks wait. That is the price of safety.
Choose when
Different lengths or different dependencies.