Limit Async Task Fan-Out With Semaphore

Run many async coroutines while capping concurrency with a semaphore, avoiding the flood of pending tasks that unbounded gathering creates.

PythonResilience

Code

pythonsnippet
28 lines
import asyncio
from typing import Awaitable, List, TypeVar

T = TypeVar("T")


async def gather_limited(
    tasks: List[Awaitable[T]], limit: int
) -> List[T]:
    if limit <= 0:
        raise ValueError("limit must be positive")
    semaphore = asyncio.Semaphore(limit)

    async def guarded(task: Awaitable[T]) -> T:
        async with semaphore:
            return await task

    return await asyncio.gather(*(guarded(t) for t in tasks))


async def fetch(i: int) -> str:
    await asyncio.sleep(0.01)
    return f"item-{i}"


async def main() -> None:
    results = await gather_limited([fetch(i) for i in range(20)], 5)
    print(len(results))

What the code does

Count the functions gather_limited, guarded, fetch and main as the entire surface area of Limit Async Task Fan-Out With Semaphore.

Asynchronous boundaries use await, so failures surface as exceptions at the call site rather than being swallowed. From asyncio it pulls Awaitable, List, TypeVar — the imports name exactly which library surface the snippet touches. The failure path is explicit — ValueError is raised when the guard condition holds.

What to watch for

  • Plan for an install step: asyncio is a real dependency, resolved by the package manager.
  • The guard limit <= 0 short-circuits the flow with an early raise when its condition holds.

Applying it

Signature: def gather_limited( tasks: List[Awaitable[T]], limit: int ) -> List[T]

gather_limited is the public entry point; everything else in the file exists to support it.

Statements that matter

async def main() -> None:
    results = await gather_limited([fetch(i) for i in range(20)], 5)
    print(len(results))
async def guarded(task: Awaitable[T]) -> T:
    async with semaphore:
        return await task
async def fetch(i: int) -> str:
    await asyncio.sleep(0.01)
    return f"item-{i}"

Interactive Tools for This Topic

FAQ

Does the code validate its input?
Validation comes first — `ValueError` marks the failure at `limit <= 0`, 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.