Read Code Fast

Lesson 9 Async and concurrency

5 min read · Python · Quiz

await in a loop, gather, timeouts and retries

What you'll learn

  • Spot await inside a loop and say when running together is faster
  • Catch a missing await before it hides a bug
  • Know when steps must stay in a row

AI loves to put await inside a loop. It works, it passes the tests, and it makes your page three times slower than it needs to be.

The idea

Async code waits for slow things: the network, the disk, a database. await means pause here until the answer is back. Calling an async def function gives you a coroutine, a not-yet answer. Forget the await and you hold the coroutine instead of the answer.

The speed question is: are these waits in a row or together? await inside a loop is one after another. asyncio.gather starts them all, then waits once. Together is faster, but only when no step needs the result of another.

prices.py
1async def load_prices(ids):2    prices = []3    for pid in ids:4        price = await fetch_price(pid)5        prices.append(price)6    return prices789async def load_prices_fast(ids):10    return await asyncio.gather(*(fetch_price(i) for i in ids))111213async def refresh_all(ids):14    prices = await load_prices_fast(ids)15    await save_cache(prices)16    return prices
  1. Line 4 await inside a loop: each call waits for the one before it. Ten ids means ten waits in a row. Fine when order matters, slow when it doesn't.
  2. Line 10 gather starts every call first, then waits once. The results come back in the same order as ids.
  3. Line 15 Imagine save_cache(prices) without its await: the body would never run, and Python would only warn that the coroutine "was never awaited". Check every call to an async function.

Take away

  • await in a loop means one at a time; asyncio.gather means all together.
  • Every call to an async def function needs an await, or a reason why not.
  • Before running steps together, ask: does any step need another step's result?

Quiz: test yourself

7 questions: a quick quiz, then a review drill. Pick an answer to see why it's right.