Skip to content
AgenticAIWiki
  1. Learn
  2. Part 0
  3. 1. Engineering prerequisites for AI apps
  4. 1.1

Lesson 1.1 · 1 of 7 · 7 min read · Reviewed 24 Nov 2026

Python async and await for concurrent calls

By the end, you can

  • Explain what await does and why it lets one program wait on many model calls at once.
  • Run several calls concurrently with asyncio.gather and cap them with a semaphore.

A model call is mostly waiting. Your code sends a request, then sits idle for a second or more while the model generates tokensToken: The unit a model reads and writes: a word, part of a word, a space or a symbol, mapped to an integer id.. If you have 50 documents to summarise and call them one after another, your program spends nearly all of its time doing nothing.

async code fixes this. It lets one program start a call, and while that call waits on the network, start the next one.

The three words

Word What it means
async def Defines a coroutine: a function that can pause in the middle
await “Pause me here until this finishes, and let something else run meanwhile”
event loop The scheduler that decides which paused coroutine runs next

Calling an async def function does not run it. It returns a coroutine object. Something has to await it, or hand it to the event loop with asyncio.run.

A worked example

import asyncio
import anthropic

client = anthropic.AsyncAnthropic()
limit = asyncio.Semaphore(5)          # at most 5 calls in flight

async def summarise(doc: str) -> str:
    async with limit:
        msg = await client.messages.create(
            model="<model id>", max_tokens=200,
            messages=[{"role": "user", "content": f"Summarise:\n{doc}"}],
        )
        return msg.content[0].text

async def main(docs: list[str]) -> list[str]:
    return await asyncio.gather(*(summarise(d) for d in docs))

summaries = asyncio.run(main(["doc one", "doc two", "doc three"]))

With three documents at about 2 seconds each, the sequential version takes about 6 seconds. The gather version takes about 2, because the three waits overlap. The results come back in the same order as the input list, even if the second call finished first.

Most model SDKs ship an async client alongside the normal one (here AsyncAnthropic). The same pattern works with httpx.AsyncClient for plain HTTP.

Concurrency is not parallelism

Python runs one line of your code at a time. await does not create threads or use more CPU cores. It just stops your program sitting idle. That is exactly what you want for I/O-bound work such as API calls, database queries and file downloads. For CPU-heavy work, such as running a local model on your own machine, async does not help.

Why the semaphore matters

gather on 500 coroutines starts 500 requests at once. The provider will answer many of them with 429429 error: The HTTP status for too many requests: you hit a rate limit. (rate limited), and your retries will make it worse. A Semaphore(5) lets only five coroutines into the async with block at a time; the rest wait their turn. Pick the number from your rate limitsRate limit: A cap on how many requests or tokens you can use in a period, such as per minute., not from a guess.

Common mistakes

  • Forgetting await. You get a coroutine object instead of a reply, plus a “coroutine was never awaited” warning.
  • Calling blocking code inside a coroutine. time.sleep(2) or a synchronous client freezes every coroutine. Use await asyncio.sleep(2) and the async client.
  • No error handling in gather. By default, the first exception propagates and you lose sight of the others. Pass return_exceptions=True to collect errors alongside results, then decide what to retry.
  • No concurrency cap. See above. Unbounded gather is the most common cause of sudden rate limiting in batch jobs.

Key points

  • Model calls spend almost all their time waiting on the network. async code lets your program start other calls during that wait.
  • await pauses one coroutine and hands control back to the event loop. Nothing runs in parallel on the CPU; the waiting overlaps.
  • asyncio.gather runs many coroutines together and returns results in the order you passed them, not the order they finished.
  • Always cap concurrency with a semaphore, or a burst of calls will hit the provider's rate limits.
Hands-on labRuns in the Playground

Run three calls together with gather

See concurrency in action: three waiting calls overlap with gather, and a semaphore caps how many overlap.

You will have: A script that reports the peak number of calls in flight for sequential await, gather and gather with a semaphore.

Steps

  1. Run the starter: both runners report 1 call in flight.
  2. Rewrite together() with asyncio.gather so all three calls start at once.
  3. Add an asyncio.Semaphore(2) and a capped() runner that wraps each call in async with.
  4. Check that results come back in input order in every case.

Done when

  • sequential reports 1 in flight, gather 3 and semaphore(2) 2.
  • Every runner prints results in order: True.
  • You can explain why gather finishes in about one call's time, not three.

Open in the Playground No API key needed.

Starter code (Python)
import asyncio

in_flight = 0
peak = 0

async def fake_call(prompt):
    """Stands in for a model call: it spends its time waiting, like a network request."""
    global in_flight, peak
    in_flight += 1
    peak = max(peak, in_flight)
    await asyncio.sleep(0.2)
    in_flight -= 1
    return f"summary of {prompt}"

docs = ["doc A", "doc B", "doc C"]

async def sequential():
    return [await fake_call(d) for d in docs]

async def together():
    # TODO: run all three calls at once with asyncio.gather
    return await sequential()

# TODO: create asyncio.Semaphore(2) and a capped() runner that uses "async with" around fake_call

async def main():
    global peak
    for name, runner in [("sequential", sequential), ("gather", together)]:
        peak = 0
        results = await runner()
        print(f"{name} max in flight: {peak} | results in order: {results == [f'summary of {d}' for d in docs]}")
    # TODO: add ("semaphore(2)", capped) to the list above

asyncio.run(main())
Show a solution
import asyncio

in_flight = 0
peak = 0

async def fake_call(prompt):
    """Stands in for a model call: it spends its time waiting, like a network request."""
    global in_flight, peak
    in_flight += 1
    peak = max(peak, in_flight)
    await asyncio.sleep(0.2)
    in_flight -= 1
    return f"summary of {prompt}"

docs = ["doc A", "doc B", "doc C"]

async def sequential():
    return [await fake_call(d) for d in docs]

async def together():
    return await asyncio.gather(*(fake_call(d) for d in docs))

limit = asyncio.Semaphore(2)

async def capped_call(d):
    async with limit:
        return await fake_call(d)

async def capped():
    return await asyncio.gather(*(capped_call(d) for d in docs))

async def main():
    global peak
    for name, runner in [("sequential", sequential), ("gather", together), ("semaphore(2)", capped)]:
        peak = 0
        results = await runner()
        print(f"{name} max in flight: {peak} | results in order: {results == [f'summary of {d}' for d in docs]}")

asyncio.run(main())
Quick checkThree independent model calls each take about 2 seconds. You run them with asyncio.gather. About how long does the batch take?
How sure are you?
Pick an answer and how sure you are