Bound asyncio Concurrency with a Semaphore

Limit concurrent asyncio tasks with a semaphore, keep input order in the results, and report per-task failures without cancelling the batch.

PythonResilience

Code

pythonsnippet
66 lines
import asyncio
import random
from collections.abc import Awaitable, Callable, Iterable
from dataclasses import dataclass
from typing import Generic, TypeVar

T = TypeVar("T")
R = TypeVar("R")


@dataclass(frozen=True)
class Outcome(Generic[R]):
    value: R | None
    error: BaseException | None

    @property
    def ok(self) -> bool:
        return self.error is None


async def bounded_map(
    items: Iterable[T],
    worker: Callable[[T], Awaitable[R]],
    *,
    limit: int,
) -> list[Outcome[R]]:
    if limit < 1:
        raise ValueError("limit must be at least 1")

    gate = asyncio.Semaphore(limit)

    async def guarded(item: T) -> R:
        async with gate:
            return await worker(item)

    outcomes = await asyncio.gather(
        *(guarded(item) for item in items),
        return_exceptions=True,
    )
    return [
        Outcome(value=None, error=item)
        if isinstance(item, BaseException)
        else Outcome(value=item, error=None)
        for item in outcomes
    ]


async def fetch(record_id: int) -> dict[str, int]:
    await asyncio.sleep(random.uniform(0.01, 0.04))
    if record_id == 4:
        raise RuntimeError(f"record {record_id} is unavailable")
    return {"id": record_id, "status": 200}


async def main() -> None:
    outcomes = await bounded_map(range(1, 8), fetch, limit=3)
    for outcome in outcomes:
        if outcome.ok:
            print("ok:", outcome.value)
        else:
            print("failed:", outcome.error)


if __name__ == "__main__":
    asyncio.run(main())

How it works

Count the classes from and Outcome and the functions ok, bounded_map, guarded and fetch as the entire surface area of Bound asyncio Concurrency with a Semaphore.

Iteration happens inside for item in outcomes — everything outside it runs once. Asynchronous boundaries use await, so failures surface as exceptions at the call site rather than being swallowed. Awaitable, Callable, Iterable, dataclass, Generic are the only symbols borrowed from asyncio — the coupling is explicit and narrow. The code refuses to proceed on bad state and throws ValueError and RuntimeError at its guard.

Returns a newly built value, leaving the inputs as they were.

What to watch for

  • asyncio must be installed first — the snippet imports it directly.
  • The guard limit < 1 short-circuits the flow with an early raise when its condition holds.

Putting it to use

The main signature reads def ok(self) -> bool

The demo output is labeled (ok:, failed:), so every printed line maps back to its originating operation.

The demo flow inside main is bounded_map — run the file to see it end to end.

Core lines

async def main() -> None:
    outcomes = await bounded_map(range(1, 8), fetch, limit=3)
    for outcome in outcomes:
        if outcome.ok:
            print("ok:", outcome.value)
        else:
            print("failed:", outcome.error)
raise RuntimeError(f"record {record_id} is unavailable")
return {"id": record_id, "status": 200}
async def guarded(item: T) -> R:
    async with gate:
        return await worker(item)

Interactive Tools for This Topic

FAQ

Does `ok` modify its input?
No — a new value is constructed for the result and the arguments are never written to.
How are precondition violations signaled?
Validation comes first — `ValueError` and `RuntimeError` marks the failure at `limit < 1`, before any partial work happens.
What does this need from the package registry?
These are real dependencies: `asyncio`. Without it the snippet will not load.