Learn / Advanced / Lesson 4

async and await

13 min Tested on Python 3.15Updated By
In short

async def defines a coroutine — a function that can pause at each await while it waits for something, letting other coroutines run in the meantime. asyncio.run() starts the event loop, and asyncio.gather() or a TaskGroup runs many coroutines concurrently in a single thread. Async shines when a program handles hundreds or thousands of network connections.

Your first coroutine

Python · run on your computer
import asyncio

async def greet(name: str, delay: float) -> str:
    await asyncio.sleep(delay)      # pause here; others may run
    return f"Hello, {name}"

async def main() -> None:
    message = await greet("Ana", 0.5)
    print(message)

asyncio.run(main())
Output
Hello, Ana
  • Calling greet(...) doesn't run it; it creates a coroutine object.
  • await runs a coroutine and waits for its result — only allowed inside async def.
  • asyncio.run(main()) starts the event loop: the scheduler that switches between coroutines.

Running many at once

Python · run on your computer
import asyncio
import time

async def fetch(url: str) -> str:
    await asyncio.sleep(1)          # pretend network call
    return f"data from {url}"

async def main() -> None:
    start = time.perf_counter()
    results = await asyncio.gather(
        fetch("a.com"), fetch("b.com"), fetch("c.com")
    )
    print(results)
    print(f"{time.perf_counter() - start:.1f}s")

asyncio.run(main())
Output
['data from a.com', 'data from b.com', 'data from c.com']
1.0s

Three one-second waits finish in one second, all in a single thread. gather returns results in the order you passed the coroutines.

TaskGroup: structured and safe

Python · run on your computer
import asyncio

async def job(name: str, seconds: float) -> str:
    await asyncio.sleep(seconds)
    return name

async def main() -> None:
    async with asyncio.TaskGroup() as tg:
        slow = tg.create_task(job("report", 0.3))
        fast = tg.create_task(job("email", 0.1))
    print(fast.result(), slow.result())

asyncio.run(main())
Output
email report

A TaskGroup (Python 3.11+) waits for every task when the block ends. If one task fails, the others are cancelled and the error is raised — no forgotten background tasks.

Timeouts

Python · run on your computer
import asyncio

async def slow_api() -> str:
    await asyncio.sleep(5)
    return "finally"

async def main() -> None:
    try:
        async with asyncio.timeout(1):
            print(await slow_api())
    except TimeoutError:
        print("Gave up after 1 second")

asyncio.run(main())
Output
Gave up after 1 second

Limiting concurrency

Python · run on your computer
import asyncio

limit = asyncio.Semaphore(3)     # at most 3 at a time
active = 0
peak = 0

async def call_api(i: int) -> int:
    global active, peak
    async with limit:
        active += 1
        peak = max(peak, active)
        await asyncio.sleep(0.1)
        active -= 1
        return i * 2

async def main() -> None:
    results = await asyncio.gather(*(call_api(i) for i in range(10)))
    print(sum(results), "peak concurrency:", peak)

asyncio.run(main())
Output
90 peak concurrency: 3

Threads or async?

Threadsasyncio
Best forTens of I/O tasks, existing sync librariesHundreds to thousands of connections
LibrariesAny (requests, database drivers)Async ones (httpx, asyncpg)
SwitchingThe OS decides, at any momentOnly at await, so fewer race conditions
Used byScripts, data jobsFastAPI, chat servers, LLM streaming

Practice

Estimate the gain from async. Given call durations durations = [1.2, 0.4, 0.9, 0.3] (seconds), print the total time if you await them one by one, then the time with gather (they overlap, so it's the slowest one). Round both to 1 decimal.

Expected output:
2.8
1.2
Your code

Quick check

1. What happens when you call an async def function without await?

2. Why is time.sleep() a problem inside a coroutine?

3. What does asyncio.Semaphore(5) help with?

Use AI at work

Python is the base of AI. On AIMates you learn to use AI tools well in your daily job.

Visit AIMates →