▶ Sign up free for the video, slides & prompts
The lesson below is open to all. Enter your email once to unlock every video, slide deck, prompt and code example on this device.
Checking…
async and await
asyncio explained with a coffee-shop analogy.
🎬 Video version coming soon — read it now
asyncio is Python's other way to handle many I/O waits at once. It uses one thread and switches between tasks whenever one is waiting. It scales to thousands of simultaneous connections, which is why modern web frameworks and AI SDKs support it.
The coffee-shop analogy
A café near RK Beach has one barista.
- Synchronous: take order 1, make it, wait for the milk to steam, serve it, then take order 2. Most of the time is spent watching the steamer.
- Asynchronous: take order 1, start the steamer, and while it heats, take order 2 and start that coffee. Serve each when it's ready.
Same single barista (one thread), far more customers served, because the waiting time is used.
async def and await
async defdefines a coroutine: a function that can pause.awaitmeans "pause here until this is ready, and let other tasks run meanwhile".asyncio.gatherruns several coroutines at the same time and returns their results in order.asyncio.runstarts the event loop from normal code.
In Colab or Jupyter, an event loop is already running, so write await main() directly in a cell instead of asyncio.run(main()).
The rule: never block the loop
Inside async code, use async versions of waiting operations:
await asyncio.sleep(1), nottime.sleep(1), which freezes everything- An async HTTP client like httpx, not
requests.get - The async client of an SDK, such as
AsyncAnthropic(lesson 9)
One blocking call stalls every task, like the barista staring at the steamer again.
Limiting concurrency
Starting 10,000 tasks at once can overwhelm a server. A semaphore caps how many run at a time:
Timeouts
Threads or asyncio?
- Threads: easiest when you have existing blocking code, like requests. A good choice for tens of tasks.
- asyncio: best for hundreds or thousands of connections, and with async frameworks like FastAPI. It needs async-compatible libraries throughout.
In one line
async def defines pausable tasks, await hands control back while waiting, gather runs many at once, and you must never block the loop.
Share with a friend