Sub topic 14
Bounding concurrency with asyncio.Semaphore
This chapter assumes you know how to create tasks, use asyncio.TaskGroup, and write async with blocks. It shows how to cap the number of tasks that run a section of code at the same time.
Why bound concurrency
A task group starts every task you give it right away. If you create 10,000 tasks that each call a web API, you open 10,000 connections at once. The server may rate-limit you, or you may run out of file descriptors. You want all the work scheduled, but only a few pieces running at any moment.
An asyncio.Semaphore is a counter of permits. A task takes a permit to enter a protected section and returns it on exit. When no permits are left, other tasks wait at the async with line until one is released.
A semaphore with a task group
The example below starts 10 tasks but lets only 3 run the protected section at once. It tracks the peak number of tasks inside that section so you can check the limit.
import asyncio
active = 0
peak = 0
async def fetch(i, sem):
global active, peak
async with sem:
active += 1
peak = max(peak, active)
await asyncio.sleep(0.1)
active -= 1
return i
async def main():
sem = asyncio.Semaphore(3)
async with asyncio.TaskGroup() as tg:
tasks = [tg.create_task(fetch(i, sem)) for i in range(10)]
print([t.result() for t in tasks])
print("peak concurrency:", peak)
asyncio.run(main())The program prints the ten results, then peak concurrency: 3. The group still waits for all tasks, so the structured-concurrency guarantees are unchanged. The semaphore only controls who may enter the section.
Always use async with
Use async with sem: and avoid calling acquire() and release() by hand. The context manager releases the permit when the block exits, including when the task is cancelled or raises an error. With manual calls, a forgotten release() in an error path permanently lowers your limit.
Interaction with timeouts
Where you put asyncio.timeout decides what it measures. A timeout around the whole async with sem: block counts the time spent waiting for a permit. A timeout inside the block counts only the work.
import asyncio
async def call(sem):
async with sem:
try:
async with asyncio.timeout(1):
await asyncio.sleep(5)
except TimeoutError:
print("call timed out")
async def main():
sem = asyncio.Semaphore(2)
async with asyncio.TaskGroup() as tg:
for _ in range(4):
tg.create_task(call(sem))
asyncio.run(main())Here each call gets one second of real work. Four tasks and two permits mean the second pair starts only after the first pair times out. If the timeout wrapped async with sem: instead, the second pair would often time out while still waiting in line.
Limits of this pattern
- All the task objects exist from the start, so with millions of items memory use grows. In that case, use a fixed number of worker tasks that read from an
asyncio.Queue. - A semaphore limits concurrency, not rate. It does not enforce "at most 50 requests per second".
asyncio.BoundedSemaphoreraisesValueErrorif you release more times than you acquired. It helps catch accounting mistakes.
Exercise
You wrap asyncio.timeout(2) around async with sem: and the work inside takes 1 second. With a semaphore of 1 and 5 tasks started together, which tasks can time out, and why?
Show answer
The tasks that wait too long for the permit. The timeout starts before the permit is acquired, so it includes queue time. The first task finishes in 1 second and the second in 2 seconds, so the second may hit the deadline. Tasks 3 to 5 time out while waiting. Moving the timeout inside the async with sem: block makes it measure only the work.