How to set a timeout with asyncio.wait_for in Python

Use asyncio.wait_for to bound an async function with a timeout, catching TimeoutError when it exceeds the limit.

Easy Python 3.8+ Aug 9, 2026 Concurrency & performance 13 views 0 copies

Python code

15 lines
Python 3.8+
import asyncio

async def slow_task():
    await asyncio.sleep(3)
    return "finished"

async def main():
    try:
        result = await asyncio.wait_for(slow_task(), timeout=1)
        print(result)
    except asyncio.TimeoutError:
        print("Task timed out")

if __name__ == "__main__":
    asyncio.run(main())

Output

stdout
Task timed out

How it works

asyncio.wait_for runs the coroutine slow_task() with a maximum duration. If the task doesn't finish within timeout, it cancels the task and raises asyncio.TimeoutError. The try/except block catches that error, allowing graceful handling. Since slow_task() sleeps 3 seconds but timeout is 1, it always times out. asyncio.run sets up and tears down the event loop automatically.

Common mistakes

  • Importing TimeoutError from builtins instead of asyncio.TimeoutError
  • Passing a coroutine object instead of awaiting it directly with wait_for
  • Forgot to handle cancellation side effects in the task

Variations

  1. Use `asyncio.timeout(1)` (Python 3.11+) as a context manager for cleaner syntax
  2. Wrap multiple coroutines with `asyncio.gather` and set an overall timeout

Real-world use cases

  • Enforcing API call limits to avoid hanging upstream HTTP requests in a web service.
  • Bounding database queries or slow I/O operations so a job doesn't block forever.
  • Adding a watchdog to a long-running background task that must fail fast on hung dependencies.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Concurrency & performance

Related tutorials and quizzes for this topic.