DevPath
Foundation lesson · 14 min

Bound concurrent service work

Use timeouts and limits so one slow dependency cannot exhaust the service.

Async is not unlimited capacity

Creating thousands of coroutines at once can overload a database or API even if each call awaits. Limit in-flight operations with a semaphore or worker pool. Choose a limit based on the downstream service and measure latency under load.

Make cancellation useful

Set timeouts for network work and propagate cancellation where possible. On timeout, release resources in a finally block. Retry only transient failures and cap attempts; a permanent bad request will not improve with repetition.

limit = asyncio.Semaphore(8)
async def fetch_one(item):
    async with limit:
        return await asyncio.wait_for(client.get(item), timeout=5)

Measure the whole budget

A five-second timeout around each call can still produce a much longer request when calls happen in batches. Define an overall deadline and a per-call limit. Choose concurrency based on the dependency's capacity, then measure queueing and error rates. An async function that performs blocking CPU work can still stall the event loop.

Handle partial results intentionally

If one task fails, decide whether the whole operation fails or whether successful results remain useful. Record which inputs failed and why; do not silently drop them. When cancellation is requested, avoid starting more work and release any acquired semaphore permit. Tests should include one slow item, one failed item, and cancellation mid-batch.

Check your understanding

Why is gathering every request at once unsafe for a large input list?

Show explanation

It creates unbounded concurrent work and can exhaust connections or overload a dependency. Use a concurrency limit.

Try it at foundation level

Write pseudocode for fetching ten URLs with a limit of three concurrent requests and one overall deadline.

Check your work

At most three requests run at once, every request has a timeout, and cancellation releases any semaphore or open response.

Self-guided practice. This does not record assessed mastery.

Put this lesson into practice

A related activity in this module at mid level.

Try: Add exponential backoff with jitter

Further reading

Primary references for this module. Check the current version when behavior or framework guidance may have changed.