How Many at Once? Concurrency for AI Workers
Every worker has a number that decides how many things it does at once, and usually nobody chose it. Temporal's Python worker, for example, gives each worker "fixed-size 100 slots" for each kind of task unless told otherwise. In a document platform I worked on, many such workers shared one container. The default allowed thousands of simultaneous activities on a machine with memory for a handful, and an upload burst found that out with an out-of-memory kill.
Concurrency is usually treated as a speed knob. For document and LLM workers it is mostly a budget: memory, CPU, the provider's rate limit, and fairness between jobs. This post takes each constraint in turn, with measurements from a Docker lab (real cgroup limits for CPU and memory) and asyncio simulations (queues, fan-out, a rate-limited provider). The workloads are invented. The production lessons are described without figures.
In short
- Size concurrency by the scarcest resource, usually memory for document workers: in a 1 GiB container, six concurrent 150 MiB tasks peaked at 932 MiB and seven were killed. Arithmetic from the measured memory per task reproduces that cut-off.
- For CPU-bound Python, threads gave no consistent speed-up; two processes did, and processes beyond the two CPUs the cgroup allowed gave nothing more.
- Against a simulated provider that allowed 40 requests per second, any limit above 8 added rejections and no throughput. An adaptive limit tracked the capacity, including a sudden halving, with about 20 rejections where fixed limits had thousands.
- Bounded fan-out cut 30 serial downloads from 3.0 to 0.4 seconds. Parallelism can also change results when steps relied on order, so compare the parallel path with the sequential one.
- Check the defaults. Most worker frameworks pick a concurrency from the CPU count or a fixed number, and neither knows your container's memory or your provider's rate limit.
Queues first: why limits exist at all
Two results from queueing theory explain most of what follows. Little's law says the average number of items in a system equals the arrival rate times the average time each spends inside: L = λW. It holds for any arrival pattern in a stable system, over long-run averages, so it works as a sanity check on any measurement. The second result is about waiting. In the simplest single-server queue, M/M/1, the average time in the system is the service time divided by one minus the utilisation. It grows slowly at first, then explosively:
Real systems are not M/M/1, but the shape carries over. A worker pool, a database or an LLM provider run near 100 per cent utilisation is a queue that has stopped draining. Concurrency limits keep each resource on the flat part of the curve. Backpressure decides what happens to the work that does not fit.
What limits a worker
| Constraint | What happens past it | Typical work it binds | How to size for it |
|---|---|---|---|
| CPU | Throttling: everything gets slower | Parsing, rendering, local models | Processes up to the cgroup's CPU allowance |
| Memory | The kernel kills a process | PDF and spreadsheet conversion, OCR, large documents | Container limit divided by peak memory per task |
| Provider rate limit | 429 responses and retries | LLM and embedding calls | Rate times latency, adjusted live |
| Downstream services | Their latency rises, then they fail | Databases, storage, internal APIs | A budget per dependency, not per caller |
| Fairness | Short jobs wait behind long ones | Mixed light and heavy work in one pool | Separate pools, or priorities |
Kubernetes documents the first two rows: "cpu limits are enforced by CPU throttling", while "memory limits are enforced by the kernel with out of memory (OOM) kills". Exceeding the first costs time. Exceeding the second costs the process.
Know your defaults
Before tuning anything, find out what each layer does when you set nothing. These are the defaults in the current documentation of each tool, as of December 2026:
| Tool | Default concurrency | Note |
|---|---|---|
| Temporal Python worker | Fixed-size 100 slots for each slot kind | Applies when no max_concurrent_* argument and no tuner is given |
| Celery, prefork pool | The number of CPUs on the machine | In a container with a CPU limit the host count overstates what the worker may use |
| Gunicorn | 1 worker, 1 thread | The WEB_CONCURRENCY environment variable overrides the worker count |
| Uvicorn | 1 worker process | --limit-concurrency has no documented default; once set, excess requests get a 503 and are not queued |
ThreadPoolExecutor | min(32, (os.process_cpu_count() or 1) + 4) | From Python 3.13; 3.8 to 3.12 use os.cpu_count() |
ProcessPoolExecutor | os.process_cpu_count() | From Python 3.13; earlier versions use os.cpu_count() |
asyncio.Semaphore | 1 | The initial value is "1 by default"; asyncio.gather has no limit parameter at all |
Two patterns stand out. Several defaults come from the CPU count, which is the wrong input for memory-bound or rate-limited work, and, as the next section shows, can itself be wrong inside a container. The others are fixed numbers that ignore your hardware. Also multiply by the number of workers: a Temporal worker with 100 activity slots, run as ten replicas, allows 1,000 activities at once.
CPU: threads, processes and the GIL
In standard CPython, "only one thread executes Python bytecode at a time". I ran eight CPU-bound tasks in a container limited to two CPUs (median of three runs after a warm-up):
Threads took between 2.15 and 2.70 seconds against 2.74 for the serial run, and one thread was already faster than serial, so the differences are noise, not scaling. Two processes took 1.50 seconds, a 1.8 times speed-up. More processes than the two allowed CPUs added nothing.
Inside the same kind of container, os.cpu_count() reported 8, and so did Python 3.13's os.process_cpu_count(), which honours CPU affinity but not a CPU quota. A pool sized from either would run four times more processes than the cgroup allows, and several defaults in the table above are sized that way. Celery's worker guide says the same: "the host CPU count overstates what the worker may use".
Two things may change this picture. Python 3.14 makes the free-threaded build, without the global interpreter lock, "officially supported" (PEP 779). The release notes estimate its single-thread cost at roughly 5 to 10 per cent. On that separate build CPU-bound threads can scale, if every native library in the process supports it. And I/O-bound work, such as waiting on an LLM API or object storage, releases the lock while it waits, so threads and asyncio already serve it well.
Memory: the constraint that kills
For document workers, memory usually binds before CPU. I ran a task that allocates and touches 150 MiB, holds it briefly and releases it, with 1 to 8 copies at once in a process pool inside a 1 GiB container:
The peak grew by about 153 MiB per task on a base of about 16 MiB, so the cut-off is predictable: (1,024 - 16) / 153 ≈ 6.6, so six fit and seven do not, as the runs showed. The per-task figure was fitted to the same runs, so this checks consistency and does not forecast; on new inputs, measure the peak first.
The failed runs had one more detail. The parent did not exit with code 137. It exited with 1, because the process pool raised an error when its child was killed, while Docker still flagged the container as OOM-killed. A log line that says "broken process pool" can be an out-of-memory kill in disguise.
The arithmetic belongs in code, so that the slot count follows the container and not a constant:
"""Size a worker's concurrency from memory, not from CPU count."""
from pathlib import Path
def memory_slots(peak_per_task_mib: float, base_mib: float, headroom: float = 0.15) -> int:
"""Slots that fit the container: (limit x (1 - headroom) - base) / peak per task, at least 1.
Reads cgroup v2 (memory.max); on cgroup v1 the limit is in memory/memory.limit_in_bytes instead.
"""
raw = Path("/sys/fs/cgroup/memory.max").read_text().strip()
if raw == "max":
raise RuntimeError("no memory limit set; size slots from a measured budget instead")
limit_mib = int(raw) / 2**20
return max(1, int((limit_mib * (1 - headroom) - base_mib) // peak_per_task_mib))
With the measured numbers it returns 6 slots without headroom, the measured cut-off, and 5 with 15 per cent headroom, which is what I would deploy. Peaks vary with the input, and the previous post showed that a guard needs room to react.
In production we ended up with three tiers of concurrency, set by the memory footprint of each worker's heaviest activity and not by its speed: a few slots for native rendering and conversion, a few more for parsing and indexing, and more again for work that mostly waits on a model API and holds little memory. Every per-worker cap lived in one module with deploy-time overrides, so changing one needed no code edit. Two older concurrency settings turned out to be read by nothing at all. A limit that no test enforces is only a comment.
Workflow engines are starting to automate this. Temporal's resource-based slot supplier "hands out slots based on real-time CPU and memory usage" and accounts for container limits. Its tuning guide recommends fixed slots for tasks with "variable, or very high, per-task resource needs". Large documents fit that description.
Bulkheads: keeping light work out of heavy queues
A shared pool is efficient but unfair. When long tasks hold the slots, short tasks queue behind them. We once found a light, mostly network-bound step waiting for many minutes behind heavy conversions that shared its slots. Azure's architecture guide calls the fix the bulkhead pattern: "Isolate the elements of an application into pools so that if one element fails, the others continue to function." In a simulation, 30 heavy tasks of 400 ms and 120 light tasks of 20 ms arrived at random over four seconds:
Separate pools cut the light tasks' 95th-percentile wait from 193 ms to 1 ms. They also raised the heavy tasks' wait from 195 ms to 1.7 seconds and stretched the whole run from 4.5 to 6.1 seconds, because heavy work could no longer borrow idle light slots. That cost comes with the pattern. Decide which work must stay responsive and give it slots nobody else can take.
Fan-out: concurrent, bounded and ordered
The cheapest win is often the plainest. Several of our activities downloaded independent inputs one after another before every model call. In the simulation, 30 independent downloads of about 100 ms took:
The details of the helper matter more than the speed-up. Results must come back in input order, so prompts and outputs match the serial version whichever call returns first. A failure must be raised as itself, not wrapped, so callers' exception handling still works. Calls still running must be cancelled and queued ones never started. And the number in flight must be bounded, because "all at once" turns a long list into a denial-of-service attack on your own storage:
"""Bounded, ordered fan-out: results in input order, a failure raised as itself, the rest cancelled."""
import asyncio
from collections.abc import Awaitable, Callable, Iterable
from typing import TypeVar
T = TypeVar("T")
R = TypeVar("R")
async def gather_bounded(fn: Callable[[T], Awaitable[R]], items: Iterable[T], limit: int) -> list[R]:
"""Run fn over items with at most `limit` in flight; return results in input order.
On a failure, cancel everything still running or queued and raise that exception itself
(not wrapped in an ExceptionGroup), so callers keep their except clauses. If several tasks
failed before the wait returned, the earliest in input order wins.
"""
gate = asyncio.Semaphore(limit)
async def one(item: T) -> R:
async with gate:
return await fn(item)
tasks = [asyncio.ensure_future(one(i)) for i in items]
try:
if tasks:
await asyncio.wait(tasks, return_when=asyncio.FIRST_EXCEPTION)
failed = next((t for t in tasks if t.done() and not t.cancelled() and t.exception()), None)
if failed is not None:
raise failed.exception()
return [t.result() for t in tasks]
finally: # after a failure, or the caller's own cancellation: nothing left running
for t in tasks:
t.cancel()
await asyncio.gather(*tasks, return_exceptions=True)
Tests check each property: results in order, never more than the limit in flight, the original exception type, queued items never started after a failure, and nothing left running when the caller itself is cancelled, for example by a timeout. That last test failed on my first version, which cancelled the remaining tasks only on a failure. asyncio.TaskGroup also cancels "the remaining tasks in the group" on the first failure, but it raises an ExceptionGroup, which changes what callers must catch. That is why this helper does not use it.
Parallelism also has a correctness trap. We split long documents into chunks and extracted them concurrently. The sequential version had passed each chunk the column names accumulated so far. The parallel version gave every later chunk only the first chunk's column names, as a hint the model did not always follow. Chunks invented near-duplicate column names, the merged table grew extra columns, and the evaluation score fell sharply while row-level accuracy did not move. The fix was to map each chunk's columns deterministically onto the first chunk's set. The general rule: run the parallel path and the sequential one on the same inputs, and compare outputs as well as timings.
LLM providers: concurrency is a rate
Most hosted model APIs, Anthropic's included, limit rates and not concurrency. Anthropic's limits are "requests per minute (RPM), input tokens per minute (ITPM), and output tokens per minute (OTPM)", enforced with "the token bucket algorithm", and possibly over short intervals: a limit of 60 RPM "might be enforced as 1 request per second". Prompt caching helps too, since the default ITPM limits "count only uncached input tokens". Little's law converts a rate into the concurrency that achieves it: requests in flight equal rate times latency.
To see what happens around that point, I simulated a provider that allows 40 requests per second through a token bucket holding 10, with a median latency of about 150 ms. The client keeps a fixed number of requests in flight and retries a 429 at once:
Throughput rose with the limit until about 8 requests in flight, then stayed at 41.5 per second however high the limit went, while rejections rose from 142 to 9,200 per second. Little's law locates the knee: 41.5 per second times the mean latency of 0.173 seconds is 7.2 requests in flight. Throughput is slightly above 40 because the bucket starts full. A client that retries at once is the worst case; the next post covers retrying properly. Past the knee, a larger limit adds load on both sides and no output.
The knee also moves. Limits differ by model and tier, other traffic shares them, and providers slow down under load. So the limit should be found at run time, as TCP congestion control does it. Netflix's concurrency-limits library takes the same approach. It offers loss-based AIMD next to latency-based algorithms such as Vegas and Gradient, and notes that "we can use latency measurements to determine when queuing happens". The simplest version is loss-based: additive increase, multiplicative decrease.
"""An additive-increase, multiplicative-decrease concurrency limit, as TCP does for its congestion window."""
class AIMDLimit:
def __init__(self, initial: float = 4, floor: float = 1, ceiling: float = 256):
self.value, self.floor, self.ceiling = float(initial), float(floor), float(ceiling)
@property
def slots(self) -> int:
return int(self.value)
def on_success(self) -> None:
"""About +1 per round trip: each of `value` successes adds 1/value."""
self.value = min(self.ceiling, self.value + 1.0 / self.value)
def on_overload(self) -> None:
"""Halve on a 429, 529 or timeout: back off fast, probe back up slowly.
Minimal on purpose: every signal halves. Production versions decrease at most once per round trip,
so one burst of rejections from a single overload does not collapse the limit to the floor.
"""
self.value = max(self.floor, self.value / 2)
| Client, capacity halved after 6 s | Successful requests in 12 s | Rejections |
|---|---|---|
| Fixed limit of 8 | 369 | 5,402 |
| Fixed limit of 32 | 369 | 50,537 |
| Adaptive (AIMD) | 350 | 22 |
Against the fixed limits, the adaptive limit gave up 5 per cent of throughput and avoided 99.6 per cent of the rejections of the smaller fixed limit. Two more runs gave 353 and 356 successes and 21 and 24 rejections. The limit saw-toothed around a time-weighted average of 6.8 slots while the provider allowed 40 requests per second, and 3.9 after the halving. Rate times mean latency was 7.0 and 3.4 in the two phases. This minimal version halves on every rejection. Production versions decrease at most once per round trip, so one burst of rejections does not collapse the limit, and they treat timeouts and 529 overload errors like 429s.
Backpressure: where the work waits
A limit decides how much runs. Backpressure decides where the rest waits. The Reactive Manifesto states the goal: a component under stress should "communicate the fact that it is under stress to upstream components" and not fail or drop messages. Queues are the usual mechanism. In Temporal, a worker "polls for a message only when it has spare capacity", so excess tasks stay in the task queue, durable and visible, and do not pile up in memory.
Azure's queue-based load levelling guide adds a warning: "autoscaling without bounding consumers' aggregate downstream rate only moves the overload to downstream dependencies". Ten autoscaled workers with a limit of 8 each put 80 requests in flight against the same provider, and the per-worker limit protects nothing. A budget like a provider's rate limit has to be enforced across workers. One way is to give each worker its share of the global budget. The other is a bucket they all draw from.
The bucket below paces calls to a rate. It works alongside a concurrency limit: slots bound memory and in-flight work, the bucket bounds the rate. For an LLM call, n can be an estimated token count, to pace tokens per minute as well as requests.
"""A token bucket: pace calls to a rate budget, on top of a concurrency limit."""
import asyncio
import time
from typing import Awaitable, Callable, Protocol
class RateLimiter(Protocol):
"""What a worker needs. A shared-store version can replace the in-process one."""
async def acquire(self, n: float = 1.0) -> None: ...
class TokenBucket:
"""In-process bucket: `rate` tokens per second, at most `burst` saved up."""
def __init__(self, rate: float, burst: float,
clock: Callable[[], float] = time.monotonic,
sleep: Callable[[float], Awaitable[None]] = asyncio.sleep):
self.rate, self.burst = rate, burst
self._clock, self._sleep = clock, sleep
self._tokens, self._stamp = float(burst), clock()
self._lock = asyncio.Lock() # one waiter at a time keeps the queue first-in, first-out
def _refill(self) -> None:
now = self._clock()
self._tokens = min(self.burst, self._tokens + (now - self._stamp) * self.rate)
self._stamp = now
async def acquire(self, n: float = 1.0) -> None:
"""Wait until `n` tokens are available, then take them (n may be a token count for an LLM call)."""
if n > self.burst:
raise ValueError("request larger than the bucket can ever hold")
async with self._lock:
self._refill()
if self._tokens < n:
await self._sleep((n - self._tokens) / self.rate)
self._refill()
# A rounding error can leave the balance a hair below zero; the next refill repays it.
self._tokens -= n
Tests use a fake clock, so the timing checks are exact: 25 calls through a bucket of 5 at 200 per second take 0.1 seconds, and eleven concurrent callers share one budget.
This version lives in one process, so it only enforces a per-worker share. To share one budget across workers, keep the balance in a store they all reach, and make "refill, check, take" one atomic operation there, for example a script in Redis or a single conditional update in a database. Time should come from the store, not from each worker's clock. The RateLimiter interface stays the same, so workers do not change. I have not built or measured that version.
A checklist
- Know your defaults: find the concurrency each framework allows when you set nothing, and multiply by the number of workers.
- Size memory-heavy work by container limit divided by peak memory per task, with headroom; read the limit from the cgroup.
- Use processes for CPU-bound Python, up to the cgroup's CPU allowance, not
os.cpu_count(). - Put light and heavy work in separate pools when light work must stay responsive, and accept the cost to heavy work.
- Fan out independent I/O with a bounded, ordered helper that raises a failure as itself and cancels the rest, including when the caller is cancelled.
- Run parallel and sequential paths on the same inputs and compare outputs.
- Treat provider limits as rates: target rate times latency, and adapt the limit from 429s, 529s and timeouts.
- Enforce shared budgets across workers, not only within each one, and let excess work wait in the queue.
Sources
- Little's law and the M/M/1 queue
- Kubernetes: resource management for pods and containers
- Python glossary: global interpreter lock, PEP 779 and What's new in Python 3.14
- Python documentation: asyncio tasks and TaskGroup, asyncio synchronisation primitives and concurrent.futures
- Gunicorn settings and Uvicorn settings
- Celery: workers and concurrency
- Temporal: worker performance and runtime tuning, task queues and the Python Worker API
- Azure Architecture Center: bulkhead pattern and queue-based load levelling
- The Reactive Manifesto: glossary, back-pressure
- Netflix concurrency-limits
- Claude API: rate limits