Thread pool
medium 70 minA 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.
Read the two times
| Wait | Run | Means | Do |
|---|---|---|---|
| Short | Short | Healthy | Nothing |
| Long | Short | Too few workers, or a burst | More workers if the cores are free |
| Short | Long | The task or its dependency is slow | Look inside the task |
| Long | Long | The dependency is slow and everything piles up | Limit, 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 behind | Seen as | Guard |
|---|---|---|
| Thread-local value | User B sees the name of user A | Set and clear in one wrapper |
| Interrupt flag | The next task stops for no reason | Clear it before the next task, as Java's pool does |
| Open transaction | The next task writes into it | Scope it inside the task |
| Lock still held | A hang, much later | with or finally |
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.