Back to Explore
GuideVibeFix editorialUpdated Nov 23, 2026

Getting Started with Python asyncio: Let Three Waits Overlap

Asking three suppliers one by one takes 1.5 seconds; asking them together takes 0.5. This guide covers everyday asyncio: async/await, gather, create_task, TaskGroup, timeouts and rate limiting — every example actually run on Python 3.12.3.

Real photo: three swimmers doing freestyle in their own lanes of an indoor pool, lane lines dividing the water into parallel lanes

Morning Light Bookshop needs a new batch of books, so it asks three suppliers for a quote. The old way is to ask one at a time: call supplier A, wait while they check stock and give a price, then call B, then C. Three calls, half a second each, one and a half seconds in total. The new way is to send all three requests at once and let each supplier go and check while you wait — whoever answers first gets written down first, and the whole thing takes half a second, the time of the slowest supplier, not the sum of all three.

That is the problem async programming solves: a program spends a lot of its life waiting — waiting for a network reply, waiting for a file to be read, waiting for someone to answer. While it waits, the computer is idle, and async lets the program do something else in that gap, then pick up where it left off when the result comes back. The standard tool for this in Python is called asyncio. It ships with the standard library, so there is nothing extra to install. This guide walks through its everyday uses from the beginning: how to write your first async function, how to run several tasks together, what to do about errors and timeouts, and when not to use it at all. Every code sample was actually run on Python 3.12.3 and every output quoted is a real result; the bookshop and the suppliers are fictional, the code and the numbers are real.

First, the distinction: async is not multithreading

When people first hear about asyncio, they picture "doing several things at once" and assume it is the same as multithreading. The difference is large. With threads, the operating system schedules several threads that genuinely run in parallel. With async, there is a single thread and a set of rules for cooperating: when a task hits something it has to wait for, it steps aside voluntarily, the event loop runs another task, and the first task comes back when its result arrives. The official docs put it plainly: asyncio is a library for writing concurrent code with the async/await syntax, and it is a good fit for IO-bound and high-level structured network code.

That distinction decides what asyncio is good at and what it is not. It is good at waiting: waiting on a network, on a disk, on someone answering. Waiting costs almost no processor, so hundreds of tasks can wait at once without strain. It is not good at computing: crunching numbers or running heavy loops, because only one task is on the processor at any moment, and while one task computes, the others wait. There is a section near the end about when not to use it.

One more word to learn first: the event loop. Think of it as the receptionist at the bookshop door. Every task tells it what it is waiting for, and it keeps a list; when a result arrives, it calls the waiting task back to continue. You rarely manage the loop yourself — asyncio.run builds it, runs your code, and closes it. Your job is to write your functions and dispatch your tasks.

Your first async function: async def and await

A normal function is defined with def. An async function adds async in front:

import asyncio

async def fetch_supplier(name, delay, price):
    await asyncio.sleep(delay)
    return f"{name}: ${price}"

async def main():
    result = await fetch_supplier("Supplier A", 0.5, 59.9)
    print(result)

asyncio.run(main())

There are three new pieces here. async def defines a coroutine function, and calling it does not run it — it returns a coroutine object. await means "wait here until the result comes back", and while waiting it hands the spot to the event loop so other tasks can run. asyncio.run is the entry point of the program: it builds an event loop, runs the main coroutine to completion, and closes the loop.

The measured output is simply:

Supplier A: $59.9

asyncio.sleep stands in for waiting: it steps aside, waits the given number of seconds, and comes back. In a real program you would replace it with a network request or a file read, written the same way. One detail matters: asyncio.sleep(0.5) needs its await. Without await it is a coroutine object nobody is waiting on, and nothing happens at all.

A beginner's first trap: forgetting await

Calling an async function and forgetting await is the most common beginner mistake, and the hardest to spot, because the program does not crash and does not complain — it just quietly does nothing. The official docs warn about this directly: simply calling a coroutine will not schedule it to be executed. Here is what I measured:

async def hello():
    return "hello"

c = hello()
print("calling hello() without await gives:", c)

The measured output:

calling hello() without await gives: <coroutine object hello at 0x75307e28b270>

The body of hello never ran. hello() returned only a coroutine object — a task that has not started yet. The hexadecimal address is different on every run, so yours will not match mine; that is normal. Worse, if you do not even keep the object, it gets garbage collected, and Python adds a warning when it exits:

RuntimeWarning: coroutine 'hello' was never awaited

(The warning is prefixed with your own file name and line number; the line above is the core message with that prefix removed.) It means "you created a task and never let it run". The correct version awaits it:

print("await hello() gives:", asyncio.run(hello()))

The measured output is await hello() gives: hello. The rule of thumb is simple: if you see <coroutine object ...> in your output, your first thought should be "I forgot an await somewhere". The same applies to asyncio.gather: calling it without await gives you an unstarted <_GatheringFuture pending>, and only after awaiting do you get ['done'].

The asyncio.run rule: call it once, at the top level

asyncio.run is made for the entry point of a program, and it has two rules. First, a program normally calls it just once, at the outermost level, in an entry function usually called main. Second, it cannot be called again from inside an event loop that is already running. I measured the second rule like this:

async def nested():
    try:
        asyncio.run(hello())
    except RuntimeError as e:
        print("RuntimeError:", e)

asyncio.run(nested())

The measured output:

RuntimeError: asyncio.run() cannot be called from a running event loop

In other words: a loop is already running, so you cannot start another one. Inside a running loop, you await other coroutines or dispatch new tasks with asyncio.create_task — you do not call asyncio.run again. This rule bites most often in Jupyter, because a notebook cell already runs inside an event loop: calling asyncio.run there raises this exact error, and the fix is to await directly in the cell, or wrap the logic in a coroutine and await that.

Waiting in turn versus waiting together: 1.5 seconds measured against 0.5

Back to the three suppliers. First, asking them one after another:

async def main_seq():
    t0 = time.monotonic()
    a = await fetch_supplier("Supplier A", 0.5, 59.9)
    b = await fetch_supplier("Supplier B", 0.5, 54.9)
    c = await fetch_supplier("Supplier C", 0.5, 62.0)
    print("sequential:", [a, b, c], "elapsed", round(time.monotonic() - t0, 1))

asyncio.run(main_seq())

Now asking them together, with asyncio.gather doing the work:

async def main_par():
    t0 = time.monotonic()
    res = await asyncio.gather(
        fetch_supplier("Supplier A", 0.5, 59.9),
        fetch_supplier("Supplier B", 0.5, 54.9),
        fetch_supplier("Supplier C", 0.5, 62.0),
    )
    print("parallel:", list(res), "elapsed", round(time.monotonic() - t0, 1))

asyncio.run(main_par())

The two measured outputs side by side tell the whole story:

sequential: ['Supplier A: $59.9', 'Supplier B: $54.9', 'Supplier C: $62.0'] elapsed 1.5
parallel: ['Supplier A: $59.9', 'Supplier B: $54.9', 'Supplier C: $62.0'] elapsed 0.5

Asking in turn costs 0.5 plus 0.5 plus 0.5, a total of 1.5 seconds; asking together runs the three half-second waits overlapping, so the total is 0.5 seconds — the time of the slowest supplier. gather returns its results in the same order you passed the tasks in, not in the order they finished, which is something you can rely on when writing code. The timings wobble by a few hundredths of a second from run to run; the values above are rounded to one decimal place.

The diagram below shows the two ways of waiting side by side: three blocks laid end to end on top, three blocks overlapping underneath.

Sequential waiting versus waiting together: three tasks that each wait 0.5 seconds take 1.5 seconds with sequential await and 0.5 seconds with asyncio.gather

One misunderstanding is worth clearing up: await is not "going to sleep", it is "stepping aside". In the sequential version, the first await steps aside, but the event loop has no other task to run, so it just waits. In the gather version, all three tasks are registered, so while one waits the loop runs another, and the waits overlap. Tasks can only overlap when they are genuinely waiting — on a network, a disk, a sleep. If all three tasks are busy computing, nobody steps aside, and running them together takes the same time as running them in turn.

create_task: dispatch first, collect later

gather fits the case where you know all the things you are waiting for and hand them over in one go. The other common case is dispatching tasks one by one, doing something else in the meantime, and collecting the results later. That is what asyncio.create_task is for:

async def slow_task(name, delay):
    await asyncio.sleep(delay)
    return name

async def main_tasks():
    t1 = asyncio.create_task(slow_task("check stock", 0.4))
    t2 = asyncio.create_task(slow_task("check price", 0.2))
    print("tasks created, waiting...")
    print(await t1, await t2)

The measured output:

tasks created, waiting...
check stock check price

The moment create_task is called, the task is scheduled on the event loop — it does not wait for the await to start running. main_tasks prints its line first and only then awaits t1 and t2 to collect the results. Checking the price takes 0.2 seconds and finishes first, but the code awaits t1 before t2, so the printed order is still "check stock check price". If you want results in the order they finish, asyncio.as_completed does that, but gather and create_task cover most everyday needs.

One rule from the official docs deserves attention here: keep a reference to the task object create_task returns — do not throw it away. The event loop only keeps weak references to tasks, so a task with no strong reference anywhere can be garbage collected before it finishes. The safest pattern is to collect background tasks in a set and have each task remove itself from the set with add_done_callback when it completes. If your tasks are a related group that should be waited for together, the TaskGroup covered below handles the references for you.

When something fails: by default, one failure fails the whole gather

What happens when one of the three suppliers is out of stock and its task raises an exception? I measured both behaviours with a task that raises ValueError:

async def failing(name):
    await asyncio.sleep(0.1)
    raise ValueError(f"{name} is out of stock")

async def main_exceptions():
    res = await asyncio.gather(
        fetch_supplier("Supplier A", 0.1, 59.9),
        failing("Supplier B"),
        return_exceptions=True)
    print("gather with return_exceptions=True:", res)
    try:
        await asyncio.gather(
            fetch_supplier("Supplier A", 0.1, 59.9),
            failing("Supplier B"))
    except ValueError as e:
        print("gather without it raises:", type(e).__name__, e)

The measured output:

gather with return_exceptions=True: ['Supplier A: $59.9', ValueError('Supplier B is out of stock')]
gather without it raises: ValueError Supplier B is out of stock

By default, if any task in a gather raises, the whole gather raises that exception, and the calling code has to catch it with try. With return_exceptions=True, exceptions are returned as ordinary results in the list, in the same positions as the tasks you passed in, so you can inspect them one by one afterwards: this item is a normal result, that item is a ValueError object. Which one to choose depends on the situation. Asking several suppliers for prices, where one being out of stock should not stop you seeing the other two quotes, calls for return_exceptions=True. If a single failure invalidates the whole batch, use the default behaviour and let the exception rise.

Timeouts: do not let one slow task hold up everything

In the real world, suppliers do not always answer on time — sometimes nobody picks up the phone. You cannot wait forever, so you put a limit on the wait. Since Python 3.11 the recommended tool is asyncio.timeout:

async def main_timeout():
    try:
        async with asyncio.timeout(0.2):
            await asyncio.sleep(1)
    except TimeoutError:
        print("timeout: the slow supplier was cut off after 0.2s")

The measured output is exactly that timeout line. asyncio.timeout(0.2) means: the waiting inside this with block gets at most 0.2 seconds, after which the waiting task is cancelled and a TimeoutError is raised. The cancellation only affects what is waiting inside the block — your code carries on afterwards and the program does not fall over. The older asyncio.wait_for does the same job, but for new code since 3.11, asyncio.timeout reads more clearly, and timeouts can be nested: an outer limit for the whole flow and a tighter one for a single step inside it.

TaskGroup: managing a group of tasks together

Python 3.11 added a more modern tool, asyncio.TaskGroup, for a group of related tasks that should be waited for and managed together:

async def main_group():
    async with asyncio.TaskGroup() as tg:
        r1 = tg.create_task(fetch_supplier("Supplier A", 0.2, 59.9))
        r2 = tg.create_task(fetch_supplier("Supplier B", 0.2, 54.9))
    print("TaskGroup:", [r1.result(), r2.result()])

The measured output:

TaskGroup: ['Supplier A: $59.9', 'Supplier B: $54.9']

TaskGroup has three advantages. First, you do not await the tasks yourself — leaving the async with block waits for every task in the group, and you read the results with .result() afterwards. Second, it holds the references to the tasks, so there is no garbage-collection worry. Third, if any task in the group fails, the rest are cancelled and the failures are combined into an exception group. The official docs also warn that TaskGroup and asyncio.timeout are implemented with cancellation internally, so a coroutine should not swallow CancelledError without re-raising it, or these tools will misbehave. For everyday batch work, TaskGroup is the less fiddly choice over bare create_task; gather is the simpler choice when all you want is a list of results.

Rate limiting: do not knock the other server over

Asking together is fast, but it should not be unlimited. In real life, firing off hundreds of requests at once can get you blocked by the other server, or exhaust your own memory first. The fix is a cap on how many run at once, using asyncio.Semaphore:

async def main_sem():
    sem = asyncio.Semaphore(2)
    running = {"n": 0, "max": 0}

    async def limited(name):
        async with sem:
            running["n"] += 1
            running["max"] = max(running["max"], running["n"])
            await asyncio.sleep(0.2)
            running["n"] -= 1
            return name

    res = await asyncio.gather(*[limited(f"job{i}") for i in range(5)])
    print("semaphore results:", res, "max concurrent:", running["max"])

The measured output:

semaphore results: ['job0', 'job1', 'job2', 'job3', 'job4'] max concurrent: 2

Semaphore(2) means at most two tasks are let through the door at once; the third waits outside until someone comes out. Five tasks at 0.2 seconds each, and the measured maximum running at once is exactly 2 — not one more. In real projects the number is usually somewhere between 5 and 20, depending on what the other side's rate limits allow. The official docs also list Lock, Event, Condition and Barrier as synchronisation primitives; they work much like the same-named tools in the threading module, except that they are not thread-safe and may only be used inside one event loop.

Blocking code does not belong here: use asyncio.to_thread

The easiest performance accident in async code is calling a blocking synchronous function inside an async function — time.sleep(0.3), reading a large file, or calling an old library's synchronous interface. A blocking call never steps aside, so the whole event loop freezes and every task waits for it. The fix is asyncio.to_thread, which sends the blocking work to a thread:

def blocking_work():
    time.sleep(0.3)
    return "stock file read"

async def main_thread():
    t0 = time.monotonic()
    res = await asyncio.to_thread(blocking_work)
    print("to_thread:", res, "elapsed", round(time.monotonic() - t0, 1))

The measured output:

to_thread: stock file read elapsed 0.3

to_thread hands blocking_work to a thread pool, and the event loop awaits the result — free to run other tasks in the meantime — until it comes back after 0.3 seconds. Remember the dividing line: inside async functions, only write things you await; wrap any synchronous blocking call in to_thread, or use a library that supports async in the first place. The reverse also holds: putting pure computation into to_thread does not make it faster, it only stops it blocking the loop — the computation itself still takes just as long.

When not to use asyncio

asyncio is not a cure-all, and there are cases where it creates more trouble than it saves. First, pure computation: arithmetic, image pixels, model inference — work with no waiting in it saves no time with async, and belongs with multiprocessing instead. Second, a program with a single quick task: building an async setup for a 0.1-second job is not worth it, and plain sequential code is clearer. Third, a project that already has a mature thread pool or synchronous codebase: mixing two concurrency models creates boundary problems, so staying consistent is better. Fourth, a team nobody in which is comfortable with async: async code is harder to debug than synchronous code, and forcing it on everyone slows the whole team down.

The test is really one sentence: does your program spend most of its time waiting? If the bulk of the time goes to waiting on a network, a database, files, or someone answering, asyncio is the right tool. If the bulk goes to computing, look at multiprocessing or another approach. Many real projects are a mix: asyncio takes requests at the network layer, and the computing goes to a process pool or to_thread, each side doing what it is good at.

One question beginners often ask: does learning asyncio make the synchronous code I already wrote a waste? Not at all. Synchronous style is the foundation async style stands on: how functions are organised, how exceptions are handled, how data is tidied up — those basics are the same in either style. asyncio only adds two new rules on top of the synchronous style: put async in front of the function and await where you wait. Code you already wrote sequentially often becomes async by swapping the slow waits for await and wrapping a batch of waits in gather, with the rest of the logic barely changing. Writing the synchronous version first, getting it right and running it, and only then converting it to async is the steadiest way to learn.

Wrap-up: a checklist

Run through this list when you write async code and you will avoid most of the traps: did every async call get its await — if you see a coroutine object, think "forgotten await" first; call asyncio.run only once, at the program entry point, never inside a running loop; wait for a batch of tasks together with gather or TaskGroup, remembering that gather returns results in the order the tasks were passed in; decide the error strategy up front — by default one failure fails the whole gather, and return_exceptions=True lets you handle each result separately; give slow tasks a timeout, preferably with asyncio.timeout; cap concurrency with a Semaphore; wrap blocking calls in to_thread so they never freeze the event loop; and keep references to background tasks, or hand them to a TaskGroup to look after.

For practice, take the bookshop example and swap in your own scenario: fetch data from three websites at once, read five files and total them up, or add a timeout and a rate limit to a slow interface. Run this guide's code as written on Python 3.12.3 first, then replace the sleeps and the made-up data one at a time. Once gather, TaskGroup and Semaphore feel natural, the next stop is an async networking library such as aiohttp — and you will find that none of what you learned today needs to change, only asyncio.sleep becomes a real network request.

Views 0Comments 0

Comments (0)

ME
0/1000
Loading comments...

Sources

Browse projectsPublish your project

Related articles