Skip to content
IT Vizag
← Async & Performance

▶ 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

Lesson 7 of 10 · 2 min read

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

🔒 Code example: sign up free (above) to unlock it.
  • async def defines a coroutine: a function that can pause.
  • await means "pause here until this is ready, and let other tasks run meanwhile".
  • asyncio.gather runs several coroutines at the same time and returns their results in order.
  • asyncio.run starts 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), not time.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:

🔒 Code example: sign up free (above) to unlock it.

Timeouts

🔒 Code example: sign up free (above) to unlock it.

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.
Tip: The keyword async spreads upwards: to await something, your function must be async too. Plan where the async boundary is, usually at main().

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.

Saved on this device. Sign in to keep progress everywhere.

Share with a friend