Timeouts, Cancellation and Bounded Concurrency
Cap how many calls are in flight with a semaphore, put one deadline over the whole fan-out with asyncio.timeout, keep partial results, and cancel cleanly.
Contentsand lesson path
On this page
- The problem
- Step 1: bound concurrency with a semaphore
- Step 2: one deadline, partial results
- Step 3: cancellation you can survive
- Mistakes to watch for
- Check your understanding
- Apply it
- Review prompt
Lessons of Async I/O in Python
- Concurrency for I/O: The Event Loop Mental Model Concept · 20 min
- Coroutines, Tasks and Task Groups Worked example · 25 min
- Timeouts, Cancellation and Bounded Concurrency Worked example · 20 min
- Lab: Find the Call That Blocks the Loop Lab · 25 min
- Check: Sequential, Concurrent or Blocked? Knowledge check · 6 questions
What you will learn
- Run concurrent I/O with task groups or gather, bounding concurrency with a semaphore and applying timeouts and cancellation.
Prerequisites: Python Foundations
01. The problem
The fan-out from the previous lesson started three calls at once. Now scale it: the reading-list service wants to check 5,000 book links against an upstream that allows twenty concurrent requests. Unbounded fan-out fails three ways at once. You hammer the upstream until it answers with 429 Too Many Requests. You hold 5,000 sockets, timers and response buffers in memory for as long as the slowest one takes. And a single slow call can hold the whole response for as long as it lasts: an await with no timeout waits as long as the awaited thing does, and httpx's default timeout fires only after 5 s of network inactivity, so an upstream that keeps trickling bytes can stretch one call far beyond that.
Three tools, one per failure: an asyncio.Semaphore to cap how many calls are in flight, asyncio.timeout to put one deadline over the whole operation, and partial-results bookkeeping so a deadline leaves you with whatever finished. All of them rest on cancellation behaving properly, so the lesson ends with what a well-behaved task does when it is cancelled. The upstream from the previous lesson is still running on port 8137; every output below is from a real run against it. The timestamps move by some milliseconds between runs and machines, so the timed blocks are marked illustrative.
02. Step 1: bound concurrency with a semaphore
import asyncio
import httpx
BASE = "http://127.0.0.1:8137"
T0 = 0.0
def at(message: str) -> None:
elapsed = asyncio.get_running_loop().time() - T0
print(f"[{elapsed:5.2f}s] {message}")
async def fetch(client: httpx.AsyncClient,
sem: asyncio.Semaphore, job: int) -> None:
async with sem:
at(f"job {job}: acquired a slot")
response = await client.get(f"{BASE}/services/job",
params={"d": 0.20})
response.raise_for_status()
at(f"job {job}: finished")
async def main() -> None:
global T0
async with httpx.AsyncClient() as client:
await client.get(f"{BASE}/services/warmup") # open the pool
sem = asyncio.Semaphore(2)
T0 = asyncio.get_running_loop().time()
at("six jobs, at most two at a time")
async with asyncio.TaskGroup() as tg:
for job in range(6):
tg.create_task(fetch(client, sem, job))
at("all six jobs done")
asyncio.run(main())[ 0.00s] six jobs, at most two at a time
[ 0.00s] job 0: acquired a slot
[ 0.00s] job 1: acquired a slot
[ 0.20s] job 0: finished
[ 0.20s] job 2: acquired a slot
[ 0.21s] job 1: finished
[ 0.21s] job 3: acquired a slot
[ 0.41s] job 2: finished
[ 0.41s] job 4: acquired a slot
[ 0.41s] job 3: finished
[ 0.41s] job 5: acquired a slot
[ 0.61s] job 4: finished
[ 0.61s] job 5: finished
[ 0.61s] all six jobs doneAll six tasks are created instantly, but only two ever hold a slot: async with sem: admits two, and the rest park at that line until a slot frees. Six 0.20 s jobs through two slots take three waves, about 0.6 s — you can read the waves straight off the timestamps. (Which of two jobs in a wave finishes first can change from run to run.) Two details make this correct rather than accidentally working. The semaphore is created once, outside the tasks: a shared counter is the whole point. And async with (not manual acquire()/release()) guarantees the slot is returned even when the request raises, so a burst of errors cannot drain the pool permanently. Choose the limit from the outside world — the upstream's documented concurrency cap, or your database pool size — not from your own patience.
One more bound is hiding in plain sight: the httpx.AsyncClient has its own connection-pool limit (100 connections by default), so even an unguarded fan-out through one client stops at the pool edge — usually after doing the damage of a hundred simultaneous requests. A semaphore is how you take deliberate control of that number instead of inheriting whatever the defaults hand you.
03. Step 2: one deadline, partial results
A semaphore bounds how many; a timeout bounds how long. The reading-list contract here: wait at most 0.50 s for enrichment, then answer with whatever arrived.
import asyncio
import httpx
BASE = "http://127.0.0.1:8137"
T0 = 0.0
def at(message: str) -> None:
elapsed = asyncio.get_running_loop().time() - T0
print(f"[{elapsed:5.2f}s] {message}")
async def call(client: httpx.AsyncClient, name: str,
delay: float) -> dict:
at(f"{name}: GET, upstream takes {delay:.2f} s")
try:
response = await client.get(f"{BASE}/services/{name}",
params={"d": delay})
response.raise_for_status()
except asyncio.CancelledError:
at(f"{name}: cancelled")
raise
at(f"{name}: finished")
return response.json()
async def main() -> None:
global T0
async with httpx.AsyncClient() as client:
await client.get(f"{BASE}/services/warmup") # open the pool
calls: dict[str, asyncio.Task] = {}
T0 = asyncio.get_running_loop().time()
at("three calls under one 0.50 s deadline")
try:
async with asyncio.timeout(0.50):
async with asyncio.TaskGroup() as tg:
for name, delay in (("a", 0.20), ("b", 0.40),
("c", 2.00)):
calls[name] = tg.create_task(
call(client, name, delay))
except TimeoutError:
at("TimeoutError: the 0.50 s deadline passed")
kept = {
name: task.result()["service"]
for name, task in calls.items()
if task.done() and not task.cancelled()
}
at(f"partial results kept: {kept}")
asyncio.run(main())[ 0.00s] three calls under one 0.50 s deadline
[ 0.00s] a: GET, upstream takes 0.20 s
[ 0.00s] b: GET, upstream takes 0.40 s
[ 0.00s] c: GET, upstream takes 2.00 s
[ 0.20s] a: finished
[ 0.41s] b: finished
[ 0.50s] c: cancelled
[ 0.50s] TimeoutError: the 0.50 s deadline passed
[ 0.50s] partial results kept: {'a': 'a', 'b': 'b'}At the deadline, asyncio.timeout cancels whatever the async with block is waiting on; the task group passes the cancellation down to its children and waits for them to actually stop; then the timeout context converts the cancellation into a plain TimeoutError at the exit line. That is why the except TimeoutError sits outside both context managers: by the time you catch it, everything inside is provably stopped — nothing keeps running in the background.
Partial results come from the task handles you kept. Tasks that finished before the deadline hold their values; the cancelled one is filtered out with task.cancelled(). The dictionary comprehension turns three tasks and a deadline into a usable answer: enrichment for two services, a missing entry for the third. On a heavily loaded machine b can miss the deadline too and be cancelled along with c; that is the deadline doing its job, and the result is still a well-formed, smaller dictionary. Two refinements worth knowing: asyncio.wait_for is the older, per-call form of the same idea, and per-call timeouts do not by themselves bound a fan-out made of many sequential calls — one overall deadline like this one does.
In a request handler the deadline belongs at the edge of the work the caller is paying for: wrap the whole fan-out, as here, rather than scattering little timeouts through helper functions. One number then governs the response, and it is the number you can defend to the client — which is what the timing logs in the lab for this skill will prove.
04. Step 3: cancellation you can survive
Everything above leans on cancellation working: the group must be able to stop a child, and the child must not fight back. The rule is short. asyncio.CancelledError inherits from BaseException, not Exception, so a normal except Exception: will not swallow it — but a bare except: will. If you catch it, do your cleanup and raise it again. finally blocks run as usual:
import asyncio
async def worker(name: str) -> None:
try:
print(f"{name}: started")
await asyncio.sleep(5) # stands in for a slow upload
print(f"{name}: finished normally")
except asyncio.CancelledError:
print(f"{name}: cancelled - closing its connection")
raise
finally:
print(f"{name}: cleanup in finally runs either way")
async def main() -> None:
task = asyncio.create_task(worker("loader"))
await asyncio.sleep(0.10)
task.cancel()
try:
await task
except asyncio.CancelledError:
print("main: loader was cancelled, no result")
asyncio.run(main())loader: started
loader: cancelled - closing its connection
loader: cleanup in finally runs either way
main: loader was cancelled, no resultThe worker was cancelled mid-sleep, yet the connection close and the finally cleanup both ran, and main sees the cancellation at the await task line. A task that follows this shape can be cancelled at any suspension point without leaking whatever it holds — which is exactly what a task group or a timeout needs from your code. The same shape appears inside the call function of step 2, where the log line c: cancelled came from a handler exactly like this one.
05. Mistakes to watch for
06. Check your understanding
07. Apply it
Build the bounded link-checker from the practice for this skill: a shared httpx.AsyncClient, a semaphore sized to a limit you can defend (the upstream's cap, or 20 if undocumented), one overall asyncio.timeout, and a response that reports both what succeeded and what did not arrive in time.
Then stress the design on purpose: lower the semaphore to 1 and confirm throughput drops; set the deadline below the fastest call and confirm the response is still well-formed with an empty result set. A bound you have never hit is a bound you cannot trust.
08. Review prompt
Without looking back: draw the shape of code that fans out under a semaphore with one overall deadline and keeps partial results, naming where the except TimeoutError goes and why. Then explain why asyncio.CancelledError inherits from BaseException rather than Exception, and what a bare except: around an await does to a timeout.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.