Sub topic 14
Bounding concurrency with asyncio.Semaphore
This chapter assumes you can write async/await code, you know how asyncio.TaskGroup starts and waits for tasks, and you are on Python 3.11 or newer. You will learn how to cap the number of tasks that use a resource at the same time. You will also learn where to put that cap, and how it interacts with cancellation and timeouts.
Why unbounded concurrency causes trouble
A TaskGroup happily runs as many tasks as you give it. That is a problem when each task touches a limited resource:
- A remote API that returns errors above some request rate.
- A database pool with 20 connections.
- The operating system's limit on open file descriptors or sockets.
- Memory, when each task holds a large response.
If you start 10,000 tasks that each open a connection, the event loop will try to open them all at once. The usual symptoms are OSError: Too many open files, HTTP 429 responses, or timeouts caused by your own overload. You need a way to say "run these 10,000 jobs, but only 20 at a time."
How a semaphore works
An asyncio.Semaphore holds a counter of available permits. It is created with an initial value:
- Acquiring a permit decrements the counter. If the counter is 0, the caller suspends until another task releases a permit.
- Releasing a permit increments the counter and wakes one waiter. Waiters are served in first-come, first-served order.
In practice you use it as an async context manager, which acquires on entry and releases on exit.
Limiting a TaskGroup
The next example starts ten tasks but lets only three run their guarded section at once. It records the peak number of tasks inside the section, so you can see the limit hold.
import asyncio
async def fetch(sem, i, stats):
async with sem:
stats["running"] += 1
stats["peak"] = max(stats["peak"], stats["running"])
try:
await asyncio.sleep(0.1)
finally:
stats["running"] -= 1
return i * 2
async def main():
sem = asyncio.Semaphore(3)
stats = {"running": 0, "peak": 0}
async with asyncio.TaskGroup() as tg:
tasks = [tg.create_task(fetch(sem, i, stats)) for i in range(10)]
print([t.result() for t in tasks])
print("peak:", stats["peak"])
asyncio.run(main())The output is [0, 2, 4, 6, 8, 10, 12, 14, 16, 18] followed by peak: 3. The run takes about 0.4 seconds, because ten jobs at three per wave need four waves of 0.1 seconds.
All ten tasks exist from the start. The semaphore does not limit how many tasks are created. It limits how many are past the async with sem line. A suspended waiting task is cheap, but it still costs memory.
Choosing where the semaphore goes
Wrap only the part that needs the limit. A permit held during unrelated work wastes capacity.
async def process(sem, url):
async with sem: # limit only the network call
data = await download(url)
return parse(data) # CPU work runs outside the limitIf the semaphore wrapped the whole function, parse would hold a permit even though it does not use the network.
Semaphores, cancellation, and timeouts
A task waiting on async with sem is suspended at an await point, so it can be cancelled like any other task. Two rules follow.
- If a task is cancelled while waiting, it never received a permit, so the counter is unchanged.
- If a task is cancelled inside the block,
async withreleases the permit on the way out, as it does for any exception.
This is why you should prefer async with over manual acquire() and release() calls. If you must call them manually, put release() in a finally block that starts only after acquire() has succeeded.
A deadline can cover the waiting time, the work, or both. The position of asyncio.timeout decides which one. In the next example the timeout sits inside the semaphore, so each call gets a time budget that starts only once it has a permit. Time spent queueing does not count.
import asyncio
async def call(sem, i):
async with sem:
try:
async with asyncio.timeout(0.5):
await asyncio.sleep(0.2 * i)
except TimeoutError:
return f"call {i}: timed out"
return f"call {i}: ok"
async def main():
sem = asyncio.Semaphore(2)
async with asyncio.TaskGroup() as tg:
tasks = [tg.create_task(call(sem, i)) for i in range(5)]
for t in tasks:
print(t.result())
asyncio.run(main())Calls 0, 1, and 2 print ok because their work takes at most 0.4 seconds. Calls 3 and 4 print timed out because they need 0.6 and 0.8 seconds. Queue position has no effect on the result. The except TimeoutError is inside the task on purpose. A TimeoutError that escaped the task would count as a failure and make the TaskGroup cancel its siblings.
If you move asyncio.timeout outside async with sem, the deadline includes queue time. Late arrivals would then time out before they ever ran. Choose the placement that matches what the deadline means: "this call may take 0.5 seconds" or "I will wait 0.5 seconds in total."
Semaphore, BoundedSemaphore, and Lock
| Primitive | Permits | Extra `release()` calls |
|---|---|---|
| `asyncio.Lock` | Exactly 1 | Raises `RuntimeError` if the lock is not held |
| `asyncio.Semaphore(n)` | n | Silently raises the counter above n |
| `asyncio.BoundedSemaphore(n)` | n | Raises `ValueError` if the counter would exceed n |
A plain Semaphore accepts a release without a matching acquire. Your limit then grows without any error. BoundedSemaphore turns that bug into an exception, which makes it a good default when you call release() yourself.
import asyncio
async def main():
sem = asyncio.BoundedSemaphore(2)
async with sem:
pass
try:
sem.release() # more releases than acquires
except ValueError as exc:
print("caught:", exc)
asyncio.run(main())Common errors
- Sharing a semaphore across event loops. Create the semaphore inside a coroutine that runs under
asyncio.run. A semaphore that waits on one loop and is later used on another raisesRuntimeErrorsaying it is bound to a different event loop. This commonly happens in tests that callasyncio.runseveral times. - Nested acquisition. If a task holds a permit and then awaits a child task that needs a permit from the same semaphore, you can deadlock. With
Semaphore(1), a single recursive call is enough. Release the permit before waiting on dependent work, or use separate semaphores. - Semaphore(0). This starts with no permits, so every waiter blocks until something else calls
release(). A negative value raisesValueError. - Treating the limit as a rate limit. A semaphore bounds how many operations are in flight. It does not bound operations per second. Ten fast calls can still finish in a burst and the next ten start immediately.
- Creating a huge number of tasks. Waiting tasks cost memory. For very large inputs, start a fixed number of worker tasks that pull jobs from an
asyncio.Queue. The worker count is the concurrency limit, and no semaphore is needed.
Semaphores and graceful shutdown
When a TaskGroup aborts because one task failed, the group cancels all siblings. Tasks queued on the semaphore are cancelled where they wait. Tasks inside the guarded block run their finally clauses and release their permits. After the group exits, the semaphore's counter is back at its initial value, so a semaphore shared by later task groups is not left depleted. This is the property that makes semaphore plus TaskGroup a safe default combination.
Exercise
A TaskGroup starts 100 tasks. Each task runs async with sem: where sem = asyncio.Semaphore(5), and inside the block it waits on asyncio.sleep(1). About how long does the group take, and what happens to the 95 tasks that do not get a permit at first?
Show answer
About 20 seconds, because 100 tasks at 5 per wave need 20 waves of 1 second. The other 95 tasks exist from the start but are suspended at async with sem. Each one resumes, in arrival order, when a running task leaves the block and releases a permit.
Exercise
You want each call to a service to have at most 2 seconds to run, no matter how long it waited for a permit. Should asyncio.timeout(2) go outside or inside async with sem, and why?
Show answer
Inside. The timeout then starts after the permit is acquired, so queue time does not use up the 2 seconds. Outside the semaphore, the deadline would include the wait.