Cancellation and timeouts

suggest change

Any operation that waits on something outside your program (a network server, a database, a child process, another thread) can take much longer than expected, or never finish. A robust program puts a limit on how long it waits and has a way to stop work that is no longer needed.

Python gives you different tools depending on how the work runs:

Work runs in Timeout Cancellation
asyncio task asyncio.timeout(), asyncio.wait_for() task.cancel(), raises CancelledError inside the task
thread join(timeout), Future.result(timeout) cooperative only, e.g. a threading.Event flag
blocking call timeout= argument (sockets, subprocess, queue, locks) not possible from outside; use the timeout
child process subprocess.run(timeout=...) terminate() / kill()

The key difference: an asyncio task can be cancelled at any await, while a thread can't be stopped from outside at all. It has to check a flag and exit on its own.

All examples were run with Python 3.13.

asyncio.timeout()

asyncio.timeout(delay) (Python 3.11+) is an async context manager that limits how long the code inside it may run. When the time is up, it cancels the current task and raises TimeoutError at the async with statement:

import asyncio

async def fetch(delay):
    await asyncio.sleep(delay)
    return f"done after {delay}s"

async def main():
    async with asyncio.timeout(1.0):
        print(await fetch(0.2))

    try:
        async with asyncio.timeout(0.5):
            print(await fetch(2))
    except TimeoutError:
        print("fetch took too long")

asyncio.run(main())
done after 0.2s
fetch took too long

The timeout covers the whole block, not each await in it, so it's an easy way to put a single limit on several steps. Since Python 3.11, asyncio.TimeoutError is just an alias of the built-in TimeoutError, so catch TimeoutError.

Deadlines and rescheduling

asyncio.timeout_at(when) takes an absolute deadline in event loop time (loop.time()) instead of a delay. The context manager object also lets you set or move the deadline after entering the block with reschedule(), and check whether it fired with expired(). Passing None means "no deadline yet":

import asyncio

async def main():
    loop = asyncio.get_running_loop()
    deadline = loop.time() + 1.0
    try:
        async with asyncio.timeout_at(deadline):
            for step in range(1, 4):
                await asyncio.sleep(0.4)
                print(f"step {step} done")
    except TimeoutError:
        print("ran out of time")

    try:
        async with asyncio.timeout(None) as cm:
            # no deadline yet; set one once we know how long we can wait
            cm.reschedule(loop.time() + 0.2)
            await asyncio.sleep(1)
    except TimeoutError:
        print("expired:", cm.expired())

asyncio.run(main())
step 1 done
step 2 done
ran out of time
expired: True

asyncio.wait_for()

asyncio.wait_for(aw, timeout) is the older, function-style way to do the same thing for a single awaitable. If it doesn't finish in time, the awaitable is cancelled and TimeoutError is raised:

import asyncio

async def fetch(delay):
    await asyncio.sleep(delay)
    return f"done after {delay}s"

async def main():
    print(await asyncio.wait_for(fetch(0.1), timeout=1))
    try:
        await asyncio.wait_for(fetch(5), timeout=0.3)
    except TimeoutError as e:
        print("timed out:", type(e).__name__, isinstance(e, asyncio.TimeoutError))

asyncio.run(main())
done after 0.1s
timed out: TimeoutError True

In Python 3.12+ wait_for() is implemented on top of asyncio.timeout(), so they behave the same. Use whichever reads better: wait_for for one call, timeout() for a block of code.

Cancelling a task

task.cancel() asks a task to stop. The next time the task is suspended at an await, asyncio.CancelledError is raised inside it. The exception unwinds the coroutine like any other, so try/finally blocks and async with exits run, which is where you release resources:

import asyncio

async def worker():
    print("worker: started")
    try:
        while True:
            await asyncio.sleep(0.1)
    except asyncio.CancelledError:
        print("worker: got CancelledError, cleaning up")
        raise
    finally:
        print("worker: finally block ran")

async def main():
    task = asyncio.create_task(worker())
    await asyncio.sleep(0.3)
    task.cancel()
    try:
        await task
    except asyncio.CancelledError:
        print("main: task was cancelled")
    print("cancelled():", task.cancelled())

asyncio.run(main())
worker: started
worker: got CancelledError, cleaning up
worker: finally block ran
main: task was cancelled
cancelled(): True

Things to know about cancellation:

Cleanup can await, and cancel() can carry a message

The cleanup code in an except CancelledError or finally block can itself await, for example to flush a buffer or close a connection gracefully. cancel(msg) attaches a message that shows up in the exception's args:

import asyncio

async def worker():
    try:
        await asyncio.sleep(10)
    except asyncio.CancelledError:
        print("worker: cancelled, flushing buffers...")
        await asyncio.sleep(0.1)   # async cleanup is allowed
        print("worker: flushed")
        raise

async def main():
    task = asyncio.create_task(worker())
    await asyncio.sleep(0.1)
    task.cancel("shutting down")
    try:
        await task
    except asyncio.CancelledError as e:
        print("main: cancelled with message:", e.args)

asyncio.run(main())
worker: cancelled, flushing buffers...
worker: flushed
main: cancelled with message: ('shutting down',)

Keep that cleanup short. If it can hang, wrap it in its own asyncio.timeout().

Don't swallow CancelledError

If you catch CancelledError you must re-raise it. Swallowing it makes the task ignore the request and keep running:

import asyncio

async def bad_worker():
    for i in range(5):
        try:
            await asyncio.sleep(0.1)
        except asyncio.CancelledError:
            print("ignoring cancel")   # BUG: swallows cancellation
    return "finished anyway"

async def main():
    task = asyncio.create_task(bad_worker())
    await asyncio.sleep(0.15)
    task.cancel()
    print(await task)
    print("cancelled():", task.cancelled())

asyncio.run(main())
ignoring cancel
finished anyway
cancelled(): False

This also breaks asyncio.timeout(), TaskGroup and shutdown in asyncio.run(), because they all depend on cancellation getting through. With an infinite loop instead of range(5), the program would hang forever. Watch out for broad handlers like except BaseException: or a bare except: in async code for the same reason.

Protecting work with asyncio.shield()

Sometimes part of the work must finish even if the caller gives up, for example writing a record that has already been charged for. asyncio.shield(aw) keeps cancellation of the outer task from reaching the inner awaitable:

import asyncio

async def save_to_db(record):
    await asyncio.sleep(0.5)
    print(f"saved {record}")

async def handler():
    print("handler: start")
    await asyncio.shield(save_to_db("order-42"))
    print("handler: done")   # never printed

async def main():
    try:
        await asyncio.wait_for(handler(), timeout=0.1)
    except TimeoutError:
        print("handler timed out")
    await asyncio.sleep(0.6)   # give the shielded save time to finish

asyncio.run(main())
handler: start
handler timed out
saved order-42

The handler itself is still cancelled; only save_to_db keeps running in the background. If the event loop shuts down before it finishes, it's lost anyway, so for important work keep a reference to the task and await it during shutdown.

TaskGroup: cancel the siblings

asyncio.TaskGroup (Python 3.11+) runs several tasks and waits for all of them. If one task fails, the group cancels the others and raises an ExceptionGroup. Wrapping the whole group in asyncio.timeout() gives all tasks a shared deadline:

import asyncio

async def download(name, delay, fail=False):
    try:
        await asyncio.sleep(delay)
        if fail:
            raise ConnectionError(f"{name} failed")
        print(f"{name} finished")
        return name
    except asyncio.CancelledError:
        print(f"{name} cancelled")
        raise

async def main():
    try:
        async with asyncio.TaskGroup() as tg:
            tg.create_task(download("a", 0.1))
            tg.create_task(download("b", 0.2, fail=True))
            tg.create_task(download("c", 1.0))
    except* ConnectionError as eg:
        print("errors:", [str(e) for e in eg.exceptions])

    try:
        async with asyncio.timeout(0.3):
            async with asyncio.TaskGroup() as tg:
                tg.create_task(download("x", 0.1))
                tg.create_task(download("y", 5))
                tg.create_task(download("z", 5))
    except TimeoutError:
        print("group timed out")

asyncio.run(main())
a finished
c cancelled
errors: ['b failed']
x finished
y cancelled
z cancelled
group timed out

This is structured concurrency: when the async with block exits, no task started in it is still running, whether it succeeded, failed or timed out. Prefer it over a loose collection of create_task() calls that you have to cancel by hand.

Timeouts that don't cancel: asyncio.wait() and as_completed()

asyncio.wait(tasks, timeout=...) returns two sets, done and pending, when the timeout expires. Unlike wait_for(), it does not cancel anything and does not raise; the pending tasks keep running until you decide what to do with them. asyncio.as_completed(timeout=...) raises TimeoutError but also leaves the remaining tasks running:

import asyncio

async def job(n):
    await asyncio.sleep(n * 0.2)
    return n

async def main():
    tasks = [asyncio.create_task(job(n)) for n in range(1, 6)]
    done, pending = await asyncio.wait(tasks, timeout=0.5)
    print("done:", sorted(t.result() for t in done))
    print("pending:", len(pending))
    for t in pending:
        t.cancel()
    await asyncio.gather(*pending, return_exceptions=True)
    print("all cancelled:", all(t.cancelled() for t in pending))

    # as_completed with an overall timeout
    tasks = [asyncio.create_task(job(n)) for n in (3, 1, 2, 10)]
    try:
        for coro in asyncio.as_completed(tasks, timeout=1.0):
            print("got", await coro)
    except TimeoutError:
        print("as_completed timed out")
        for t in tasks:
            t.cancel()

asyncio.run(main())
done: [1, 2]
pending: 3
all cancelled: True
got 1
got 2
got 3
as_completed timed out

After cancelling, gather(..., return_exceptions=True) waits for the tasks to actually finish their cleanup without raising their CancelledError into your code.

Blocking code in a thread can't be cancelled

asyncio.to_thread() and loop.run_in_executor() run a blocking function in a thread pool. A timeout around them stops your coroutine from waiting, but the thread keeps going, because threads can't be interrupted:

import asyncio
import time

def blocking_io():
    time.sleep(1)
    print("blocking_io: still finished")
    return 42

async def main():
    try:
        async with asyncio.timeout(0.2):
            await asyncio.to_thread(blocking_io)
    except TimeoutError:
        print("gave up waiting")
    await asyncio.sleep(1.0)

asyncio.run(main())
gave up waiting
blocking_io: still finished

If the blocking call has its own timeout parameter (most network libraries do), set it too, so the thread is released. See Asynchronous Executors for more on executors.

Stopping threads cooperatively

There is no Thread.kill() or Thread.cancel() in Python. Killing a thread at an arbitrary point could leave locks held and data half-written, so the thread has to stop itself. The usual way is a threading.Event that the thread checks regularly. Use event.wait(timeout) instead of time.sleep() so the thread wakes up immediately when asked to stop:

import threading
import time

def worker(stop: threading.Event):
    n = 0
    while not stop.is_set():
        n += 1
        # wait() doubles as an interruptible sleep
        stop.wait(0.1)
    print(f"worker: stopping after {n} iterations")

stop = threading.Event()
t = threading.Thread(target=worker, args=(stop,))
t.start()
time.sleep(0.35)
stop.set()
t.join(timeout=2)
print("alive:", t.is_alive())
worker: stopping after 4 iterations
alive: False

join(timeout) returns None whether or not the thread finished, so check is_alive() afterwards. A thread that must not block program exit can be created with daemon=True, but daemon threads are killed abruptly at exit without running their finally blocks. See also Stoppable Thread with a while Loop.

Futures: result(timeout) and cancel()

With concurrent.futures, Future.result(timeout) raises TimeoutError if the result isn't ready in time. Future.cancel() only works for a task that is still waiting in the queue. Once it has started running, cancel() returns False and the task runs to completion:

import time
from concurrent.futures import ThreadPoolExecutor, TimeoutError

def slow(n):
    time.sleep(n)
    return n

with ThreadPoolExecutor(max_workers=1) as pool:
    fut = pool.submit(slow, 0.5)
    queued = pool.submit(slow, 0.1)
    try:
        fut.result(timeout=0.1)
    except TimeoutError:
        print("result not ready in time")
    print("cancel running:", fut.cancel())
    print("cancel queued: ", queued.cancel())
    print("result anyway: ", fut.result())
result not ready in time
cancel running: False
cancel queued:  True
result anyway:  0.5

To drop everything still queued when shutting down a pool, use shutdown(cancel_futures=True). Running tasks finish; queued ones are cancelled:

import time
from concurrent.futures import ThreadPoolExecutor

def slow(n):
    time.sleep(0.2)
    return n

pool = ThreadPoolExecutor(max_workers=2)
futures = [pool.submit(slow, n) for n in range(10)]
time.sleep(0.05)
pool.shutdown(wait=True, cancel_futures=True)
print("completed:", sum(f.done() and not f.cancelled() for f in futures))
print("cancelled:", sum(f.cancelled() for f in futures))
completed: 2
cancelled: 8

Timeouts on blocking calls

Because blocking calls can't be interrupted from outside, the timeout has to be passed to the call itself. Most of the standard library supports it.

subprocess.run(timeout=...) kills the child process and raises TimeoutExpired:

import subprocess
import sys

try:
    subprocess.run(
        [sys.executable, "-c", "import time; time.sleep(10)"],
        timeout=0.5,
    )
except subprocess.TimeoutExpired as e:
    print(f"killed after {e.timeout}s: {type(e).__name__}")
killed after 0.5s: TimeoutExpired

With Popen, use proc.wait(timeout=...) or proc.communicate(timeout=...), and call proc.kill() yourself when it raises. See Subprocess Library.

Sockets have no timeout by default, so a recv() from a server that never answers blocks forever. settimeout() (or the timeout argument to create_connection()) makes every operation raise TimeoutError instead:

import socket

# a server that accepts connections but never replies
server = socket.create_server(("127.0.0.1", 0))
host, port = server.getsockname()

with socket.create_connection((host, port), timeout=2) as conn:
    conn.settimeout(0.3)            # applies to every later recv/send
    try:
        conn.recv(1024)
    except TimeoutError as e:
        print("recv timed out:", e)
server.close()
recv timed out: timed out

The same applies to libraries built on sockets: urllib.request.urlopen(url, timeout=10), requests.get(url, timeout=(3, 10)), httpx.Client(timeout=...), database drivers' connect and query timeouts. Note that this is a per-operation timeout: a server that sends one byte every few seconds never triggers it, so you may still want an overall deadline.

Thread synchronization primitives take a timeout too. Each signals a timeout differently:

import queue
import threading

q = queue.Queue()
try:
    q.get(timeout=0.2)
except queue.Empty:
    print("no item within 0.2s")

lock = threading.Lock()
lock.acquire()
print("acquired again:", lock.acquire(timeout=0.2))

done = threading.Event()
print("event set:", done.wait(timeout=0.2))
no item within 0.2s
acquired again: False
event set: False

On Unix you can also interrupt blocking code in the main thread with signal.alarm() / SIGALRM; see Signals and graceful shutdown. It doesn't work on Windows or in other threads, so prefer explicit timeouts.

Propagating a deadline

A request that makes several calls usually has one overall time budget, not a separate timeout for each call. Compute an absolute deadline once with time.monotonic() (never time.time(), which jumps when the system clock is adjusted) and give each call whatever time is left:

import time

class Deadline:
    def __init__(self, seconds):
        self.end = time.monotonic() + seconds

    def remaining(self):
        left = self.end - time.monotonic()
        if left <= 0:
            raise TimeoutError("deadline exceeded")
        return left

def step(name, cost, deadline):
    budget = deadline.remaining()
    print(f"{name}: {budget:.2f}s left")
    time.sleep(min(cost, budget))   # a real call would pass timeout=budget

deadline = Deadline(0.5)
try:
    step("auth", 0.2, deadline)
    step("query", 0.2, deadline)
    step("render", 0.2, deadline)
    step("send", 0.2, deadline)
except TimeoutError as e:
    print("request failed:", e)
auth: 0.50s left
query: 0.30s left
render: 0.10s left
request failed: deadline exceeded

render gets only the 0.1 seconds that are left instead of its own fresh timeout, and send fails right away without starting work that couldn't finish in time.

In asyncio you get this for free: an outer asyncio.timeout() applies to everything awaited inside it, including nested timeouts, and whichever deadline comes first wins.

Summary

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents