Skip to content

Adaptive concurrency

Many applications hardcode concurrency, for example ThreadPoolExecutor(max_workers=10), asyncio.Semaphore(100), or anyio.CapacityLimiter(20). RESOURCERA replaces those guesses with limits derived from the same snapshots, capacity estimates, and reservations used by admission:

Resource intelligence → capacity estimate → concurrency recommendation → resource-aware admission.

Two ResourceManager methods make up the API:

  • recommend_concurrency(requirements, *, min_concurrency=1, max_concurrency=None) returns a one-off ConcurrencyRecommendation.
  • adaptive_concurrency(requirements, *, min_concurrency=1, max_concurrency=None, max_waiters=None, wait_timeout_seconds=..., admission_wait_timeout_seconds=...) is an async context manager that yields a ConcurrencyController. Omitted timeouts use configuration; explicit None waits indefinitely.

max_concurrency defaults to ResourceConfig.max_concurrency. A recommendation or limit never leaves the [min_concurrency, max_concurrency] range.

Recommendations

recommendation = await manager.recommend_concurrency(
    {"cpu": 1.0, "memory": "512MiB"},
    min_concurrency=1,
    max_concurrency=32,
)
print(recommendation.recommended_limit)
print(recommendation.limiting_resource)
print(recommendation.reason)

The result reports:

  • the recommended limit and bounds;
  • the raw estimated_limit;
  • capacity_known;
  • the limiting resource;
  • the full CapacityResult;
  • the snapshot ID and age;
  • the applied safety margin;
  • assumptions;
  • a reason;
  • confidence between 0 and 1.

Confidence reflects measurement quality and reduced monitoring detail.

A recommendation is advice, not a guarantee. Another workload, or another process that shares the coordination database, can claim the capacity before you use it.

Workers for a ThreadPoolExecutor

There is no separate worker API: a worker count is a concurrency recommendation for the workload that the threads run. Describe what each task needs, and optionally label it with a profile such as io-bound, cpu-bound, memory-bound, network-bound, disk-bound, gpu-bound, or mixed.

recommendation = await manager.recommend_concurrency(
    {"memory": "64MiB", "profile": "io-bound"},
    max_concurrency=32,
)
executor = ThreadPoolExecutor(max_workers=recommendation.recommended_limit)

A profile describes the workload category; it never invents resource demands. For I/O-bound threads, CPU cores alone do not limit the count. Declare the memory, disk, or network each task uses instead. RESOURCERA never applies a cores * 2 style rule.

Adaptive controllers

async with manager.adaptive_concurrency(
    {"cpu": 0.5, "memory": "256MiB"},
    min_concurrency=1,
    max_concurrency=50,
) as controller:
    async with controller.slot():
        await execute_workload()

Each slot() is bounded by the controller's local limit and holds a logical lease. Because every slot holds a lease:

  • controllers for different workloads share one reservation ledger;
  • no controller bypasses or double-counts the others;
  • the global ResourceConfig.max_concurrency and cross-process coordination still apply.

On exit, the slot releases its capacity and lease. Slots are single-use.

A background task re-evaluates capacity every concurrency_adjustment_interval_seconds. It uses the cached snapshot and the existing capacity estimate; acquiring a slot never triggers resource discovery. You can also call await controller.adjust() yourself.

Adjustment policy

The controller adjusts within the configured bounds:

  • Initial limit. The first reliable evaluation sets the limit directly. If capacity is unknown, the snapshot is too old, or monitoring is degraded, the limit stays at the minimum. The first reliable estimate then calibrates the limit directly instead of probing upward one step at a time.
  • Decreases. These are immediate. When the target falls below the active count, admitted work keeps running, and new slots wait until active work drains below the limit. RESOURCERA never cancels work merely because a limit falls.
  • Increases. Increases are cautious and require fresh measurements and monitoring that is not degraded. Each increase adds concurrency_increase_step.
  • Unknown or stale capacity. The limit is held; it is never treated as unlimited. Admission rejects work that needs an unmeasurable dimension, so slots fail with AdmissionRejectedError until the measurement is usable.
  • Overload feedback. controller.signal_overload(reason) halves the limit immediately when the application observes local resource overload. For remote service feedback, use a separate remote controller. It is owner-only; see Event-loop ownership.

If capacity collapses while work runs, the limit can remain at the active count and decrease as work finishes. Use signal_overload if you need to reduce the limit below the active count sooner.

Backpressure, cancellation, and shutdown

  • At most max_waiters tasks wait for a permit; it defaults to ResourceConfig.max_waiters. Additional callers are rejected with AdmissionRejectedError. Waiters are served in FIFO order.
  • controller.state.pending_count counts permit waiters; admission_waiter_count counts controller operations awaiting admission, and total_pending_count sums the two without double counting. Admission attempts include those currently being evaluated, not only those in the manager's queue. Use manager.admission_state() for the separate manager-wide queue.
  • wait_timeout_seconds bounds the permit wait, while admission_wait_timeout_seconds independently bounds the subsequent lease wait. Omitting either uses its ResourceConfig default: indefinitely for permits (concurrency_wait_timeout_seconds=None) and five seconds for admission. Passing None explicitly waits indefinitely at that stage; positive finite values set a deadline. Zero, negative and non-finite values are invalid. Both queues remain bounded even when waits are indefinite. The lease wait happens in the manager's admission queue, so it appears in manager.admission_state() with liveness heartbeats; permit waits have none. See Waiter liveness heartbeats.
  • Cancelling a waiter leaves no permit or lease behind.
  • Leaving the adaptive_concurrency block closes the controller. Pending waiters at either stage receive ManagerStateError, and running slots finish normally.
  • Closing the manager cancels admission contexts that are still active. Their leases are released, and the controller closes.
  • A lost lease cancels its slot and raises ReservationError.

Event-loop ownership

This contract applies to adaptive controllers and to remote controllers.

  • Owner. A controller belongs to one event loop: the loop running when it was created, otherwise the first event loop that successfully binds it. Ownership is the identity of that loop, checked together with the thread running it; thread identity alone never establishes ownership. Binding is atomic, so when several loops race to first use, exactly one becomes the owner and the others are rejected. The owner never changes.
  • Owner-only operations. For adaptive controllers: reading state or current_limit, adjust(), signal_overload(), entering and leaving slots, and leaving the controller context. A call from another thread, from another event loop (including a later loop on the same thread), from outside any event loop, or after the owning loop has ended raises RuntimeError and changes nothing. Before a controller is bound, its state may be read from anywhere.
  • Lifecycle. Create and use a controller within the lifetime of the event loop that owns it. Reusing one across sequential anyio.run() calls, or reading its state after its loop has ended, is unsupported and raises RuntimeError; capture any state you need before the loop ends, and create a new controller for each new event loop.
  • Worker threads. Marshal owner-only calls onto the owning loop with anyio.from_thread.run_sync, for example anyio.from_thread.run_sync(controller.signal_overload).
  • Shutdown. manager.close() may run on another thread or event loop. It marks each controller closed immediately and schedules waiter cancellation on the owning loop; if that loop has already ended there is nothing to wake, and closing still succeeds.

ThreadPoolExecutor submissions

ThreadPoolExecutor has no public way to resize its workers after construction, and RESOURCERA does not touch its private internals. Instead, size the executor from a recommendation and bound submissions with a controller:

with ThreadPoolExecutor(max_workers=recommendation.recommended_limit) as executor:
    async with manager.adaptive_concurrency(
        {"memory": "64MiB"}, max_concurrency=recommendation.recommended_limit
    ) as controller:
        result = await controller.run_sync(executor, blocking_function, argument)

run_sync submits only while holding a slot, so the executor's queue cannot grow without bound. The permit and lease are released only after the submitted callable has finished:

  • If the caller is cancelled while the callable is still queued, the future is cancelled.
  • If the callable is already running, the cancellation is delivered after it completes, so capacity is never released while a thread is still working. Python cannot forcibly stop a running thread or native call, so cancellation may be delayed for as long as the callable runs.
  • Exceptions raised by the callable propagate to the caller.
  • run_sync never shuts the executor down. If the executor is already shut down, submit raises RuntimeError and the slot is released.

Changing the physical worker count

When a recommendation changes substantially and you need a different number of threads, rotate executors rather than mutating one:

  1. Create a new executor with the new max_workers.
  2. Route new run_sync calls to the new executor.
  3. Call old.shutdown(wait=True, cancel_futures=False) from a worker thread, for example with anyio.to_thread.run_sync, so the event loop is not blocked. Work that is already running or queued on the old executor completes, and each slot releases its permit when its own work finishes.
  4. Only the owner shuts down an executor, and RESOURCERA never does.

The controller's limit continues to bound total submissions across both executors during the rotation.

asyncio and AnyIO

Controllers use AnyIO, so they work in asyncio programs and under AnyIO's backends. Replace a fixed semaphore or limiter with a slot:

async def guarded(item):
    async with controller.slot():
        return await handle(item)


results = await asyncio.gather(*(guarded(item) for item in items))

Network-bound work

Interface bandwidth does not determine safe request concurrency. Request concurrency also depends on payload sizes, latency, remote performance, connection pools, rate limits, and retries. RESOURCERA does not guess these, and it has no HTTP-client integration. Instead:

  • configure network_capacity_bytes_per_second, because interface link speed is not a reliable ceiling;
  • derive the per-operation requirement from your own estimate, for example bytes_per_operation / expected_seconds;
  • keep the connection-pool or API rate limit as max_concurrency;
  • feed remote service signals to a separate remote controller.
config = ResourceConfig(network_capacity_bytes_per_second=125_000_000)
async with (
    ResourceManager(config) as manager,
    manager.adaptive_concurrency(
        {"network_bytes_per_second": 2_000_000 / 0.5},
        max_concurrency=50,
    ) as controller,
):
    async with controller.slot():
        await make_request()

Without a configured ceiling, network capacity is unknown, so the controller stays at its minimum. A recommendation's assumptions also report the observed connection count when sample_process_connections is enabled.

Disk-bound work

Disk throughput ceilings are not portable, so configure disk_read_capacity_bytes_per_second and disk_write_capacity_bytes_per_second. Available throughput is the ceiling minus observed traffic, scaled by I/O pressure where the platform reports it, after the safety margin and claims. Queue depth and latency are recorded as assumptions when exposed and are never fabricated.

async with manager.adaptive_concurrency(
    {
        "disk_read_bytes_per_second": 50_000_000,
        "disk_write_bytes_per_second": 20_000_000,
        "profile": "disk-bound",
    },
    max_concurrency=40,
) as controller:
    async with controller.slot():
        await process_file(path)

Observing a controller

controller.state returns an immutable ConcurrencyState without performing any measurement. It contains:

  • the current and recommended limits;
  • the bounds;
  • the active and pending counts;
  • available permits;
  • the last evaluation and adjustment times;
  • the limiting resource and adjustment reason;
  • the last capacity estimate;
  • confidence and snapshot age;
  • CPU, memory, and I/O pressure;
  • whether the controller is closed;
  • a bounded history of ConcurrencyAdjustment records, sized by concurrency_history_size.

Limit changes are logged at INFO on the resourcera logger.

Overhead

Controllers reuse cached snapshots and capacity calculations. Adjustments run at most once per interval, while waiter queues, history, and background tasks (one per controller) are bounded. Measurement detail follows the strict overhead policy. When that policy degrades monitoring, controllers hold their limits instead of increasing.