← All posts

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:

A curve of time in system against utilisation: 2 times the service time at 50 per cent, 5 times at 80, 10 times at 90 and 20 times at 95 per cent Time in system for an M/M/1 queue, in multiples of the service time 0x 5x 10x 15x 20x 0% 25% 50% 75% 100% 2x 5x 10x 20x utilisation of the server or worker pool
Figure 1. Waiting explodes as a server approaches full use.

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

ConstraintWhat happens past itTypical work it bindsHow to size for it
CPUThrottling: everything gets slowerParsing, rendering, local modelsProcesses up to the cgroup's CPU allowance
MemoryThe kernel kills a processPDF and spreadsheet conversion, OCR, large documentsContainer limit divided by peak memory per task
Provider rate limit429 responses and retriesLLM and embedding callsRate times latency, adjusted live
Downstream servicesTheir latency rises, then they failDatabases, storage, internal APIsA budget per dependency, not per caller
FairnessShort jobs wait behind long onesMixed light and heavy work in one poolSeparate 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:

ToolDefault concurrencyNote
Temporal Python workerFixed-size 100 slots for each slot kindApplies when no max_concurrent_* argument and no tuner is given
Celery, prefork poolThe number of CPUs on the machineIn a container with a CPU limit the host count overstates what the worker may use
Gunicorn1 worker, 1 threadThe WEB_CONCURRENCY environment variable overrides the worker count
Uvicorn1 worker process--limit-concurrency has no documented default; once set, excess requests get a 503 and are not queued
ThreadPoolExecutormin(32, (os.process_cpu_count() or 1) + 4)From Python 3.13; 3.8 to 3.12 use os.cpu_count()
ProcessPoolExecutoros.process_cpu_count()From Python 3.13; earlier versions use os.cpu_count()
asyncio.Semaphore1The 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):

Bars of run time: serial 2.74 seconds; threads 2.15 to 2.70 seconds at 1, 2, 4 and 8 threads; processes 3.03 seconds at 1, 1.50 at 2, 1.46 at 4 and 1.60 at 8 Eight CPU-bound tasks in a 2-CPU container (seconds, median of 3) serial 2.74 s threads x 1 2.49 s threads x 2 2.15 s threads x 4 2.49 s threads x 8 2.70 s processes x 1 3.03 s processes x 2 1.50 s processes x 4 1.46 s processes x 8 1.60 s Threads share one interpreter lock; processes scale to the CPUs the cgroup allows, and no further.
Figure 2. Threads do not scale CPU-bound Python; processes scale to the cgroup's CPUs.

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:

Bars of peak container memory: 169 MiB for one task, rising by about 153 MiB per task to 932 MiB for six; seven and eight were killed at the 1 GiB limit Container memory peak by number of concurrent 150 MiB tasks (1 GiB limit, measured) 0 256 512 768 1024 limit 169 1 323 2 474 3 627 4 780 5 932 6 OOM 7 OOM 8 concurrent tasks
Figure 3. Peak memory grows linearly with concurrency until the kernel ends it.

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:

Arrivals go either to one shared pool of four slots or to two separate pools of two. With a shared pool, light tasks wait up to 193 ms at the 95th percentile; with separate pools, 1 ms, while heavy tasks wait up to 1,747 ms instead of 195 Arrivals 30 heavy, 120 light Shared pool 4 slots, everyone Separate pools 2 heavy + 2 light light wait p95, shared 193 ms light wait p95, separate 1 ms heavy wait p95, shared 195 ms heavy wait p95, separate 1746 ms Run time: 4.48 s shared, 6.13 s separate. Light tasks 20 ms, heavy 400 ms.
Figure 4. Separate pools protect light work and tax heavy work.

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:

Bars: one after another 3.03 seconds; at most 4 at once 0.80; at most 8 at once 0.42; all 30 at once 0.12 Thirty independent downloads of about 100 ms (seconds, measured) one after another 3.03 s at most 4 at once 0.80 s at most 8 at once 0.42 s all 30 at once 0.12 s
Figure 5. Independent I/O should not wait in line.

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:

Bars of successful requests per second by fixed limit: 11.2 at a limit of 2, 22.7 at 4, then 41.5 at 8, 16, 32 and 64, while rejections rise from 0 to 142, 1,458, 3,933 and 9,200 per second Fixed concurrency limits against a provider that allows 40 requests per second (measured) 0 10 20 30 40 50 11.2/s limit 2 0 429/s 22.7/s limit 4 0 429/s 41.5/s limit 8 142 429/s 41.5/s limit 16 1,458 429/s 41.5/s limit 32 3,933 429/s 41.5/s limit 64 9,200 429/s Bars: successful requests per second. Below: rejections per second from a client that retries at once.
Figure 6. Past rate times latency, a higher limit buys only rejections.

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)
A saw-tooth line of the concurrency limit over 12 seconds: it climbs slowly and halves on each rejection, averaging 6.8 while capacity is 40 requests per second and 3.9 after capacity halves at 6 seconds; thick lines mark rate times mean latency, 7.0 and then 3.4 An adaptive limit finds the provider's capacity, and follows it when it halves (measured) 0 4 8 12 0 s 3 s 6 s 9 s 12 s capacity 40/s to 20/s 3.4 Thick lines: rate x mean latency in each phase, 7.0 then 3.4. Mean limit: 6.8 before the drop, 3.9 after. concurrency limit over time
Figure 7. The adaptive limit saw-tooths around rate times latency, and follows it down.
Client, capacity halved after 6 sSuccessful requests in 12 sRejections
Fixed limit of 83695,402
Fixed limit of 3236950,537
Adaptive (AIMD)35022

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.

Producers feed a durable task queue, then worker slots, then a shared rate budget, then the provider; excess work waits in the queue Where work waits on its way to a provider Producers uploads, API Task queue durable, visible Worker slots limit x workers Rate budget token bucket Provider 429 past its limit excess work waits here A limit that holds in one worker does not hold across ten. Slots and bucket must add up to the provider's budget.
Figure 8. Excess work should wait in the queue, where it is visible and cheap.

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