sethserver.com Subscribe
None

Python Asyncio Tutorial: Async/Await, Tasks & Concurrency Guide

By Seth Black • Updated: March 18, 2026

Programming · 3 min read

Like this kind of writing? Get one email a week with notes on startups, AI, and the occasional strong opinion about Python: subscribe to the newsletter.

You know that feeling where your program is "working," but it's also just... waiting? Waiting on the network. Waiting on disk. Waiting on a database that's thinking real hard about returning three rows. That's where asyncio earns its keep.

The basic idea: stop standing around

Synchronous code is polite to a fault. Task A waits. Task B waits. Your CPU sits there doing nothing while the network thinks about life.

Async code doesn't wait. It starts task A, hits an await, switches to task B. Same thread. Less time wasted.

Here's the smallest example that actually shows the behavior:

import asyncio

async def greet(name: str):
    print(f"hi {name}")
    await asyncio.sleep(1)
    print(f"bye {name}")

async def main():
    await asyncio.gather(
        greet("ada"),
        greet("grace"),
        greet("linus"),
    )

asyncio.run(main())

All three say "hi" right away, then you wait one second, then all three say "bye." That one second covers all three greetings. If you expected three seconds, welcome to async.

Vocabulary you need

await vs create_task: the mistake everyone makes

If you await three network calls in a row, you're back to waiting in line. The fix is to start them first, then wait for all of them.

import asyncio

async def fetch_data(url: str):
    await asyncio.sleep(2)  # pretend this is the network
    return f"data from {url}"

async def main():
    urls = [
        "https://api.example.com/users",
        "https://api.example.com/products",
        "https://api.example.com/orders",
    ]

    tasks = [asyncio.create_task(fetch_data(u)) for u in urls]
    results = await asyncio.gather(*tasks)

    for r in results:
        print(r)

asyncio.run(main())

This is the pattern I reach for when I have independent I/O. Three API calls. Ten database queries. A pile of files to read. Start them, then gather.

Manual loop control (rare, but real)

Most of the time, asyncio.run() is the right answer. Sometimes you're integrating with something else and you need more control.

import asyncio

async def countdown(n: int):
    while n:
        print(n)
        await asyncio.sleep(1)
        n -= 1

loop = asyncio.get_event_loop()
try:
    loop.create_task(countdown(3))
    loop.run_until_complete(asyncio.sleep(4))
finally:
    loop.close()

I don't do this daily, but it's useful to recognize it when you're reading other people's code. Which you will. A lot.

A tiny chat server that shows why async exists

Async works well when you have many clients doing small reads/writes. A chat server is the cleanest demo.

import asyncio

class ChatServer:
    def __init__(self):
        self.clients = set()

    async def handle_client(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter):
        self.clients.add(writer)
        addr = writer.get_extra_info("peername")
        print(f"connected: {addr}")

        try:
            while True:
                data = await reader.read(100)
                if not data:
                    break

                msg = data.decode().strip()
                for client in list(self.clients):
                    if client is writer:
                        continue
                    client.write((msg + "\n").encode())
                    await client.drain()
        finally:
            self.clients.discard(writer)
            writer.close()
            await writer.wait_closed()
            print(f"disconnected: {addr}")

async def main():
    server = ChatServer()
    srv = await asyncio.start_server(server.handle_client, "127.0.0.1", 8888)
    async with srv:
        await srv.serve_forever()

asyncio.run(main())

One coroutine per client. No thread-per-connection nonsense. The event loop switches between them.

async with: you still need to clean up resources in async code

Resource management doesn't go away just because you added await.

import asyncio

class AsyncDatabaseConnection:
    async def __aenter__(self):
        await asyncio.sleep(1)  # connect
        return self

    async def __aexit__(self, exc_type, exc, tb):
        await asyncio.sleep(0.5)  # disconnect

    async def query(self, sql: str):
        await asyncio.sleep(0.5)
        return f"result for {sql}"

async def main():
    async with AsyncDatabaseConnection() as db:
        print(await db.query("select * from users"))

asyncio.run(main())

This pattern keeps your setup/teardown clean, even when exceptions show up.

Rules

Asyncio isn't hard. The hard part is noticing where you're accidentally blocking. Use a profiler. You'll find them.

For more practical patterns like handling timeouts, worker queues, and mixing sync code with async, check out these python asyncio Recipes.

-Sethers

Share this post
Newsletter

One email, once a week.

Notes on databases, systems, and the occasional strong opinion about Python. No spam, unsubscribe anytime.

Seth Black
Written by

Seth Black

Engineer and founder based in Texas. Writes about databases, AI, and running things in production. Embeds in small teams as lead engineer.

More from Programming

View all →
Programming

What's the Differences Between Relational, NoSQL, Vectors, and Caches

Apr 14, 2026
Programming

Git and Source Control in AI Land

Apr 14, 2026
Programming

Domains, DNS, and why it feels fragile

Apr 14, 2026