Skip to blog content
From the notebook

asyncio.gather with a timeout: a deadline for the whole batch without losing the results that finished

Wrapping asyncio.gather in wait_for throws away every result when the deadline hits. Four ways to put one timeout on a batch of tasks, tested on Python 3.13: which keep the finished results, which cancel the slow tasks, and why as_completed(timeout=) leaves them running in the background.

Download .md

To give a whole batch of asyncio calls one deadline, don’t wrap gather in wait_for: when time runs out you get a TimeoutError and lose every result, including the ones that had already finished. Use asyncio.wait(tasks, timeout=...) instead. It returns the finished and unfinished tasks as two sets, so you keep what finished and cancel the rest yourself. In my test, 5 calls of 20 to 500 ms had a 200 ms deadline. wait_for(gather(...)) returned nothing. The asyncio.wait helper below returned the 3 results that made it, with a TimeoutError in place of each slow call. One pattern looks right and isn’t: as_completed(timeout=) raises on time but leaves the slow tasks running. Both of mine finished in the background after the caller had given up. Everything here was tested on Python 3.13.5.

Four patterns for a 200 ms deadline over 5 tasks of 20 to 500 ms. wait_for around gather keeps no results. timeout around a gather of tasks keeps 3 of 5, read from the tasks. as_completed with a timeout keeps 3 of 5 but leaves the 2 slow tasks running. wait with a timeout, then cancel, keeps 3 of 5 with a TimeoutError in place of the others.

Same 5 tasks, same 200 ms deadline: what each pattern leaves you with.

Why does wait_for around gather lose every result?

asyncio.wait_for(asyncio.gather(*coros), timeout) treats the gather as one awaitable. When the timeout hits, wait_for cancels the gather. That cancels every child task and raises TimeoutError. The gather never returns its list, so the three calls that finished in 20, 50 and 100 ms are gone.

naive.py
try:
    results = await asyncio.wait_for(asyncio.gather(*(job(i, d) for i, d in enumerate(DELAYS))), 0.2)
except TimeoutError:
    results = None  # the 3 calls that finished are lost too

That’s fine when the batch is all-or-nothing. It’s wasteful when each call is an LLM request you’ve already paid for, or a lookup the page can show without the slow ones. The same happens with async with asyncio.timeout(0.2): around a gather of coroutines.

How do you keep the results that finished?

Create the tasks yourself, give the whole batch to asyncio.wait with a timeout, and cancel whatever is still pending:

deadline.py
import asyncio

async def gather_with_deadline(aws, timeout: float):
    """Like gather(return_exceptions=True), but the whole batch shares one deadline.
    Calls that miss it are cancelled and come back as TimeoutError, in their original position."""
    tasks = [asyncio.ensure_future(a) for a in aws]
    if not tasks:
        return []
    done, pending = await asyncio.wait(tasks, timeout=timeout)
    for t in pending:
        t.cancel()
    await asyncio.gather(*pending, return_exceptions=True)  # let the cancellations finish
    return [
        TimeoutError() if t.cancelled() else (t.exception() or t.result())
        for t in tasks
    ]

With the 5 test calls and a 200 ms deadline, it returned ['r0', 'r1', TimeoutError, 'r3', TimeoutError] after 0.20 s. A call that raised is returned as its exception, like gather(return_exceptions=True), so a ValueError from one call doesn’t hide the others:

deadline_test.py
r = await gather_with_deadline([job(0, 0.01), boom(), job(2, 1.0)], 0.1)
# ['r0', ValueError('bad'), TimeoutError()]
assert await gather_with_deadline([], 1) == []

Three details matter:

  • ensure_future first. Since Python 3.11, asyncio.wait no longer accepts bare coroutines, and you need the task objects anyway to read results in order.
  • Cancel, then await the cancelled tasks. cancel() only requests cancellation. Awaiting them gives each one the chance to run its finally blocks, close connections and release a semaphore, before you return.
  • asyncio.wait never raises on timeout. It just returns early, which is what makes it the right tool here.

Why doesn’t as_completed with a timeout stop the slow tasks?

asyncio.as_completed(tasks, timeout=0.2) looks like the same thing: it yields results as they arrive, then raises TimeoutError at the deadline. But it doesn’t cancel anything. In my test, after the TimeoutError there were still 2 tasks running. Both then logged “finished” at 300 and 500 ms:

as_completed_leak.py
try:
    for f in asyncio.as_completed(tasks, timeout=0.2):
        got.append(await f)
except TimeoutError:
    pass
print(sum(not t.done() for t in tasks))  # 2: still running

For an LLM batch, that means you keep paying for, and rate-limiting yourself with, requests whose answers nobody will read. If you use as_completed, cancel the leftovers yourself in the except block.

What about asyncio.timeout or a TaskGroup?

Both work if you create the tasks first and keep the references. async with asyncio.timeout(0.2) around asyncio.gather(*tasks) cancels the unfinished tasks when the deadline hits. A TaskGroup inside asyncio.timeout does the same. The finished tasks still hold their results: in my test, tasks 0, 1 and 3 had results and 2 and 4 were cancelled, in both versions. You read them from the task objects:

taskgroup.py
try:
    async with asyncio.timeout(0.2):
        async with asyncio.TaskGroup() as tg:
            tasks = [tg.create_task(job(i, d)) for i, d in enumerate(DELAYS)]
except TimeoutError:
    pass
results = [t.result() if t.done() and not t.cancelled() else None for t in tasks]

The difference from gather_with_deadline: a TaskGroup cancels everything when one task raises, and raises an ExceptionGroup, so one bad call loses the batch. Pick it when one failure means the batch is wrong anyway. A plain gather without return_exceptions=True is the opposite surprise: it raises the first exception and leaves the other tasks running.

PatternFinished results keptSlow tasks after the deadlineOne task raises
wait_for(gather(*coros))nonecancelledraised; the others keep running, results lost
timeout() around gather(*tasks)yes, read from taskscancelledraised; the others keep running
as_completed(timeout=)the ones you awaitedstill runningraised when you await that one
TaskGroup inside timeout()yes, read from taskscancelledExceptionGroup; all others cancelled
wait(timeout=) + cancel (the helper above)yes, in ordercancelledreturned in place, others kept

How does this combine with a concurrency limit?

A batch deadline and a per-call limit answer different questions. The deadline says “the page needs an answer in 2 seconds”. The semaphore says “don’t send more than 10 requests at once”. Use both: wrap each call in the semaphore and per-call timeout from limiting concurrency with asyncio.Semaphore, then pass those coroutines to gather_with_deadline. Calls still queued for a slot at the deadline are cancelled before they start, so they cost nothing.

For calls that fail rather than run slow, add retries with backoff and a fallback model inside each call, not around the batch. In Node.js, the equivalent tools are Promise.allSettled with an AbortSignal; see limiting concurrent promises and cancelling an LLM request when the client disconnects.

Summary

  • wait_for(gather(...)) and timeout() around a gather of coroutines lose every result when the deadline hits.
  • asyncio.wait(tasks, timeout=...) returns finished and pending sets. Cancel the pending ones, await them, and read results from the tasks in order.
  • as_completed(timeout=) raises at the deadline but leaves the slow tasks running. Cancel them yourself.
  • timeout() with a TaskGroup, or around a gather of tasks you kept, cancels the slow tasks and leaves the finished results on the task objects. A TaskGroup also cancels everything when one task raises.
  • Put the batch deadline outside and the per-call semaphore and timeout inside.

More on calling LLM APIs in production: Production LLM engineering.

Part of the guide Production LLM engineering, which puts related articles in reading order.