Skip to content
Index Ai Academy
Phase 8 · Security & reliability

Async HTTP clients

Many requests at once with asyncio and httpx: limits, timeouts and retries.

About 45 minutes · Model names checked November 2026 · A free account opens the whole lesson.
Already have an account? Sign in to open this lesson

What it covers8

First principles

How can a client overlap waiting while staying within an upstream service's limits?

An event loop can run other tasks while a request waits for the network. A concurrency limit bounds how many requests use the service at once.

  1. Starting point

    Six independent requests are ready

  2. What changes

    A semaphore allows two requests in flight

  3. Result

    Completed requests free slots for the remaining four

Compare all three steps
  1. Starting point

    Six independent requests are ready

  2. What changes

    A semaphore allows two requests in flight

  3. Result

    Completed requests free slots for the remaining four

Complete and reverse the trace

Given Six independent requests are ready and Completed requests free slots for the remaining four, write down the missing step that connects them.

Compare with the worked step

A semaphore allows two requests in flight

Now take A semaphore allows two requests in flight and the result above. Write an input and an implementation that could produce this trace.

Check one starting point

Six independent requests are ready. Check that your implementation produces the result shown above.

Try it on a new case

What happens if each request takes one second and they all start under a limit of two?

Show worked reasoning

It takes roughly three seconds plus overhead. Two requests finish in each of three waves.

Run, change, and build

Check this when debugging. Expecting async to speed up CPU-heavy work.

Trace the cause · HTTP request, job, and result
  1. Identify the request, response, and any durable state. Predict the status or stored result before following the trace.
  2. Change one request property and keep the client contract visible. Compare the response and job state to explain the observed behavior.
  3. Try the same reasoning on this case. What happens if each request takes one second and they all start under a limit of two?

Why it matters

A program that checks prices for 200 products, or pulls pages from a dozen services, spends almost all its time waiting for answers. Asking one at a time means waiting 200 times in a row. Asking concurrently means waiting roughly once. That speed comes with duties: don't flood the service, don't hang forever on one slow reply, and retry sensibly when something fails. This lesson builds a client that does all four, using asyncio from the concurrency lesson and httpx, the async-capable cousin of requests.

What you'll be able to do

  • Send many HTTP requests concurrently with asyncio and one shared httpx.AsyncClient
  • Cap how many requests run at once with a semaphore
  • Set timeouts and keep one failure from sinking a whole batch
  • Retry only the failures worth retrying, with exponential backoff
Quick check
A script checks prices for 200 products, one request at a time, and each takes 0.5 seconds. With 20 requests in flight at once, about how long does it take?
  1. About 0.5 seconds
  2. About 20 seconds
  3. About 100 seconds
  4. About 5 seconds
Show the answer

About 5 seconds

One at a time is 200 × 0.5 = 100 seconds. With 20 in flight, it's about 200 / 20 = 10 rounds of 0.5 seconds: about 5 seconds. Waiting together is the whole trick.

The idea: waiting is free, so overlap it

This rests on Concurrency and async, where one event loop ran many waiting tasks, and on Rate limits, retries and idempotency, where a token bucket limited a client. A call to an API spends almost all of its time waiting for the reply, and a waiting program uses no resources. If you send 200 requests one after another, you wait 200 times; if you start many at once, the waits overlap and you wait about once. The overlap needs a cap: starting a thousand requests together is rude to the server, which answers 429 Too Many Requests or slows down for everyone. A semaphore holds a number of permits, and a task needs one to run its request. With a cap of 3, twelve one-second requests run in four rounds. The picture runs it.

Try it now

All twelve tasks start at once, but only three hold a permit; the rest wait for one.

Quick check
gather returns results in the order the calls were given, whatever order they finish in. What does this print: the results, and the order of finishing?
import asyncio

finished = []

async def fetch(name, delay):
    await asyncio.sleep(delay)
    finished.append(name)
    return name

async def main():
    results = await asyncio.gather(fetch("a", 0.03), fetch("b", 0.01), fetch("c", 0.02))
    print(results, finished)

asyncio.run(main())
  1. ['a', 'b', 'c'] ['b', 'c', 'a']
  2. ['b', 'c', 'a'] ['b', 'c', 'a']
  3. ['a', 'b', 'c'] ['a', 'b', 'c']
  4. ['b', 'c', 'a'] ['a', 'b', 'c']
Show the answer

['a', 'b', 'c'] ['b', 'c', 'a']

All three waits start together, so the shortest one finishes first: b, then c, then a. gather still hands the results back in the order you listed the calls. That makes it safe to pair each result with the request that asked for it.

Quick check
What does this print?
import asyncio
async def answer(value, delay):
    await asyncio.sleep(delay)
    return value
async def main():
    print(await asyncio.gather(answer("slow", 0.03), answer("fast", 0.01)))
asyncio.run(main())
  1. It depends on timing
  2. ['slow', 'fast']
  3. ['fast', 'slow']
  4. fast slow
Show the answer

['slow', 'fast']

gather returns results in the order the awaitables were passed, not the order they finished, so it prints ['slow', 'fast'].

Quick check
From the lesson on rate limits: a token bucket lets a burst through up to its capacity, and refuses the rest with a 429. Eight requests arrive in the same instant at a bucket of 5. What does this print: the requests served, and the ones refused?
tokens = 5
served = 0
for request in range(8):
    if tokens >= 1:
        tokens -= 1
        served += 1
print(served, 8 - served)
  1. 8 0
  2. 1 7
  3. 5 3
  4. 5 8
Show the answer

5 3

The first five requests each take a token. The bucket is then empty, and nothing has had time to refill it, so the last three are refused. A good client doesn't send everything at once. The limits section of this lesson shows how to keep a fixed number of requests in flight.

In your own words
Why do 200 requests take 5 seconds with 20 in flight and not 100, and why cap the number in flight?

Write a sentence or two, then compare it with a good answer in the lesson.

In Python: gather, one shared client and a cap

In an async def function, await marks the places where the program waits. While one request waits for its reply, the event loop runs others. asyncio.gather starts several awaitables together and returns their results in the order you gave them, whichever finishes first.

The cells in this lesson talk to a pretend price service built with httpx.MockTransport: a function that receives each request and returns a response, here after a 0.2-second pause, like a real network call. The same tool makes async code easy to test, because the "server" is just Python.

import asyncio, time
import httpx

async def price_service(request):
    await asyncio.sleep(0.2)  # the network and the server's work
    sku = request.url.path.rsplit("/", 1)[-1]
    return httpx.Response(200, json={"sku": sku, "price": int(sku[-3:]) / 4})

SKUS = [f"TE-{n}" for n in range(100, 110)]

async def one_by_one(client):
    return [(await client.get(f"/prices/{s}")).json()["price"] for s in SKUS]

async def all_at_once(client):
    replies = await asyncio.gather(*(client.get(f"/prices/{s}") for s in SKUS))
    return [r.json()["price"] for r in replies]

async def main():
    transport = httpx.MockTransport(price_service)
    async with httpx.AsyncClient(
        transport=transport, base_url="https://prices.example"
    ) as client:
        for fetch in (one_by_one, all_at_once):
            start = time.perf_counter()
            prices = await fetch(client)
            print(f"{fetch.__name__}: {time.perf_counter() - start:.2f}s", prices[:4])

asyncio.run(main())

Ten requests one after another take ten waits; together they take about one. With 200 products the difference is 40 seconds against a fraction of one.

Note: asyncio.run needs a current browser (one with WebAssembly JSPI, like recent Chrome, Edge and Safari). If a cell here stops with an error about asyncio, run it on your own computer or update the browser.

Drill

Fetch many, keep them labeled

Write async def fetch_all(fetch, ids): start fetch(id) for every id at once with asyncio.gather, and return a dictionary from each id to its result, in the order of ids.

import asyncio


async def fetch_all(fetch, ids):
    results = {}
    for i in ids:
        results[i] = await fetch(i)
    return results


async def fake_price(sku):
    await asyncio.sleep(0.02)
    return len(sku) * 10


print(asyncio.run(fetch_all(fake_price, ["TENT-2P", "MAT", "STOVE"])))
In the lesson, your code is checked as you write it.

One client for the whole batch

Create one httpx.AsyncClient and share it, inside async with so its connections close at the end. A client keeps connections open between requests (a connection pool), so the second request to the same server skips the slow setup of a new connection and TLS handshake. Creating a client for every request throws that away, and with hundreds of requests it can run the machine out of open connections.

Give the client a base_url and default settings once:

client = httpx.AsyncClient(
    base_url="https://api.example.com/v1",
    headers={"Authorization": f"Bearer {token}"},
    timeout=httpx.Timeout(10.0, connect=3.0),
    limits=httpx.Limits(max_connections=10),
)

timeout matters more than it looks. httpx gives up after 5 seconds by default (requests waits forever unless told otherwise), and a program without a timeout can hang for hours on one stuck connection. max_connections caps the pool, which is one way to stop a batch from flooding a server.

Limits: be a good client

Starting a thousand requests at once is rude to the server and usually counterproductive: it answers 429 Too Many Requests, or slows down for everyone. Most APIs document a limit, like "at most 5 requests at a time". An asyncio.Semaphore enforces one in your own code: it holds a number of permits, and async with sem: waits until a permit is free.

import asyncio, time

in_flight = 0
busiest = 0

async def fetch(i, sem):
    global in_flight, busiest
    async with sem:
        in_flight += 1
        busiest = max(busiest, in_flight)
        await asyncio.sleep(0.1)  # the request
        in_flight -= 1
        return i * i

async def main():
    sem = asyncio.Semaphore(3)
    start = time.perf_counter()
    results = await asyncio.gather(*(fetch(i, sem) for i in range(12)))
    print(results)
    print(f"at most {busiest} at once, {time.perf_counter() - start:.2f}s")

asyncio.run(main())

Twelve requests of 0.1 seconds, three at a time, take about 0.4 seconds: four rounds. All twelve tasks start at once, but only three hold a permit; the rest wait at async with sem without using any resources. Create the semaphore inside the async code (here in main), so it belongs to the running event loop.

Quick check
A semaphore of 2 guards the requests, and six are started together. What does this print: the most that were ever in flight at once?
import asyncio

async def main():
    limit = asyncio.Semaphore(2)
    in_flight = peak = 0

    async def fetch(i):
        nonlocal in_flight, peak
        async with limit:
            in_flight += 1
            peak = max(peak, in_flight)
            await asyncio.sleep(0.01)
            in_flight -= 1

    await asyncio.gather(*(fetch(i) for i in range(6)))
    print(peak)

asyncio.run(main())
  1. 2
  2. 1
  3. 6
  4. 3
Show the answer

2

All six tasks start, and only two can be inside the async with block at a time. The other four wait at the door. As each one leaves, the next comes in. The batch still finishes far sooner than one at a time, and the server never sees more than 2 requests from you at once.

The same semaphore as a picture of time. Each bar is one request, from the moment it holds a permit to the moment it lets go. Change 3 to 6 and run it again: the bars pack into fewer rounds.

import asyncio, time
import matplotlib.pyplot as plt

spans = []

async def fetch(i, sem, t0):
    async with sem:
        start = time.perf_counter() - t0
        await asyncio.sleep(0.1)
        spans.append((i, start, time.perf_counter() - t0))

async def main():
    sem = asyncio.Semaphore(3)
    t0 = time.perf_counter()
    await asyncio.gather(*(fetch(i, sem, t0) for i in range(12)))

asyncio.run(main())
fig, ax = plt.subplots(figsize=(6, 3))
for i, start, end in sorted(spans):
    ax.barh(i, end - start, left=start)
ax.set_xlabel("seconds since the first request")
ax.set_ylabel("request number")
print(len(spans), "requests")
In your own words
Why one shared client for the whole batch, and what does a semaphore do?

Write a sentence or two, then compare it with a good answer in the lesson.

Timeouts and failures

In a batch of 200 requests, something will go wrong: a timeout, a 500, a refused connection. Decide what one failure should do to the rest:

  • asyncio.gather(*tasks) raises the first exception, and you lose the other results.
  • asyncio.gather(*tasks, return_exceptions=True) puts exceptions in the result list in place of values, so you can report each failure and keep every success.
  • async with asyncio.TaskGroup() as tg: (Python 3.11 and later) cancels the remaining tasks when one fails. That's right when the results only make sense together, like the pieces of one page.

Often the clearest design is a small function that fetches one item and never raises: it catches the errors it expects and returns a value or an error message. Then a plain gather collects everything.

For a deadline on the whole batch, wrap it in async with asyncio.timeout(30):, which cancels whatever is still running after 30 seconds and raises TimeoutError.

Quick check
What does asyncio.TaskGroup do when one task fails?
  1. Cancels the remaining tasks
  2. Waits 30 seconds, then stops
  3. Retries the task that failed
  4. Carries on and collects the errors
Show the answer

Cancels the remaining tasks

That is right when the results only make sense together, like the pieces of one page.

Retries

Rate limits, retries and idempotency built the rules: retry timeouts, connection errors, 429 and 502 to 504; never other 4xx; wait with backoff and jitter, or for Retry-After when the server sends it; cap the attempts; and give a POST an idempotency key. In async code the retry loop lives inside the task that holds the permit, so a task that is waiting to retry still counts against the cap and the batch cannot grow past it.

Quick check
With return_exceptions=True, gather hands back each failure in its place and keeps the other results. What does this print?
import asyncio

async def fetch(i):
    if i == 2:
        raise TimeoutError("request 2 timed out")
    return i * 10

async def main():
    results = await asyncio.gather(
        *(fetch(i) for i in range(4)), return_exceptions=True
    )
    print([r if isinstance(r, int) else "failed" for r in results])

asyncio.run(main())
  1. [0, 10, 30]
  2. [0, 10]
  3. [0, 10, 'failed', 30]
  4. ['failed', 'failed', 'failed', 'failed']
Show the answer

[0, 10, 'failed', 30]

Request 2 raised, and its exception sits in position 2 of the results, where its answer would have been. The other three results are intact. Without the flag, gather would raise the first exception and you would lose the three good answers along with the bad one.

Drill

Give up on a slow call

Write async def with_default(coro, seconds, default): wait for coro at most seconds with asyncio.wait_for, and return default instead if it takes longer (asyncio.TimeoutError).

import asyncio


async def with_default(coro, seconds, default):
    return await coro


async def slow():
    await asyncio.sleep(0.2)
    return "late"


print(asyncio.run(with_default(slow(), 0.05, "fallback")))
In the lesson, your code is checked as you write it.
Worked example

Worked example: errors as values

A status checker for five services. One is slow, one is down, one doesn't exist. Each check returns a line of text, so a single failure never hides the other results.

import asyncio
import httpx

async def services(request):
    name = request.url.host.split(".")[0]
    if name == "slow":
        await asyncio.sleep(1)
    if name == "down":
        return httpx.Response(503)
    if name == "gone":
        raise httpx.ConnectError("name not resolved", request=request)
    return httpx.Response(200, json={"status": "ok"})

async def check(client, name):
    try:
        async with asyncio.timeout(0.3):
            reply = await client.get(f"https://{name}.example/health")
        reply.raise_for_status()
        return f"{name}: up"
    except (TimeoutError, httpx.TimeoutException):
        return f"{name}: too slow (no answer in 0.3s)"
    except httpx.HTTPStatusError as e:
        return f"{name}: answered {e.response.status_code}"
    except httpx.RequestError as e:
        return f"{name}: unreachable ({e})"

async def main():
    async with httpx.AsyncClient(transport=httpx.MockTransport(services)) as client:
        names = ["shop", "slow", "down", "gone", "search"]
        async with asyncio.timeout(5):
            for line in await asyncio.gather(*(check(client, n) for n in names)):
                print(line)

asyncio.run(main())
In the lesson you can change this and run it.

check gives each service 0.3 seconds with asyncio.timeout, which works whatever the transport. On a real network, httpx's own timeout setting raises httpx.TimeoutException instead, so the except catches both. raise_for_status() turns the 503 into an HTTPStatusError, which carries the response. ConnectError is one kind of RequestError, so the general except httpx.RequestError comes last. Because every check returns a string, gather always gets five results, in the order of names, and the whole batch has a five-second deadline as a safety net.

In your own words
In a batch of 200 requests, what should one failure do to the rest?

Write a sentence or two, then compare it with a good answer in the lesson.

In AI and ML systems: forty model calls under a limit

A batch of model calls is the job this lesson was made for. Each call takes seconds of waiting, so overlapping them is a large win, and each is limited twice: by requests a minute and by tokens a minute. So the cap on calls in flight comes from the provider's limits, not from what your machine could do. One shared client keeps the connections open, and each task holds a permit while it waits. The cell runs forty "calls" to a pretend model service and records how many were in flight at once.

Worked example

Forty model calls, six at a time

A pretend model service answers each call after a pause and counts how many calls it holds at once. The semaphore keeps that number at the cap.

import asyncio
import httpx

state = {"now": 0, "most": 0}

async def pretend_model(request):
    state["now"] += 1
    state["most"] = max(state["most"], state["now"])
    await asyncio.sleep(0.02)
    state["now"] -= 1
    return httpx.Response(200, json={"stop_reason": "end_turn"})

async def ask(client, sem, n):
    async with sem:
        reply = await client.post("/v1/messages", json={"n": n})
        return reply.status_code

async def main():
    sem = asyncio.Semaphore(6)
    transport = httpx.MockTransport(pretend_model)
    async with httpx.AsyncClient(transport=transport, base_url="https://m.test") as c:
        codes = await asyncio.gather(*(ask(c, sem, n) for n in range(40)))
    print(len(codes), set(codes), "most in flight:", state["most"])

asyncio.run(main())
In the lesson you can change this and run it.

All forty tasks started together, but never more than six calls were in flight, so the provider's limit would have been respected. Real code also reads the rate-limit headers from each reply and slows the rate when the budget runs low.

Async code outside the academy, and where this shows up

The cells here end with asyncio.run(main()): one call that starts the event loop, runs main and closes the loop. A program should call it once, at the top. Inside a Jupyter notebook a loop is already running, so there you write await main() directly in a cell. In a FastAPI app the loop belongs to the server, so an async def endpoint awaits an async client that the app creates once at startup, in its lifespan function (APIs with FastAPI). When a library has only blocking functions, await asyncio.to_thread(func, ...) runs it in a thread so the loop keeps going.

On the job, two mistakes recur. A client made inside the loop of tasks, so every call pays for a new connection. No cap, so a nightly batch of thousands of calls trips the provider's limit and the whole batch is retried. Goes deeper in: Async JavaScript: promises, await and fetch does the same in JavaScript, One request through a serving stack: latency and cost shows the provider's side of the queue, and Caches, queues and background jobs moves a big batch to a queue and workers.

In your own words
Where does the cap on calls in flight come from when you call a model API?

Write a sentence or two, then compare it with a good answer in the lesson.

Choose how to practice

Start with a short baseline or choose guided, independent, or AI-assisted practice.

Practice what you just read

  • 6 code examples you can edit and run
  • a practice exercise that checks your code
  • a 5-question quiz
  • 9 review cards for spaced repetition

Try a quiz question

Why share one httpx.AsyncClient across all the requests in a batch?

  1. It reuses open connections, skips setup for each request, and keeps settings in one place
  2. httpx allows only one client per program, so a second one would fail to start
  3. Each AsyncClient can send only one request before it has to be recreated
  4. It makes the requests run one at a time, which keeps them in a fixed order

Answer it at the end of the lesson to see if you're right, and why.

Before this lesson

Keep learning

Where this lesson leads.

575 lessons in thirteen phases. 176 are free without an account, and a free account opens the rest. See every lesson.

Phase 8 · about 23 hours of study

APIs

Design, build, secure and scale web APIs from first principles 27 lessons 1 free
  1. HTTP from the wire up FreeWhat really travels between client and server: bytes, headers and bodies.40 min
  2. API stylesREST, RPC, GraphQL, gRPC and streaming: what each is for.35 min
  3. Build an API server from scratchRouting, handlers and responses, with no framework.45 min
  4. A web framework, from the insideDecorators, middleware and error handling: how Flask and FastAPI work.40 min
  5. Designing a REST APIResources, methods, status codes, errors and pagination done well.45 min
  6. Validating requests with schemasCheck every request against a JSON Schema and say exactly what's wrong.45 min
  7. A database-backed APICRUD endpoints on SQLite, with safe concurrent updates.45 min
  8. Authentication and authorizationAPI keys, sessions, tokens and OAuth: who's calling, and what may they do?45 min
  9. Rate limits, retries and idempotencyKeep an API up under load and make retries safe.45 min
  10. Async HTTP clientsMany requests at once with asyncio and httpx: limits, timeouts and retries.45 min
  11. Webhooks and eventsPush events to other systems: signed, retried and deduplicated.45 min
  12. Documenting APIs with OpenAPIA machine-readable contract for docs, SDKs and AI tools.40 min
  13. Running APIs in productionVersioning, CORS, caching, request ids and health checks.45 min
  14. Project: a reviews APIAn authenticated, validated, paginated API with tests.45 min
  15. Web pages with FlaskRoutes, Jinja templates, a shared layout, links and error pages, tested with the test client.45 min
  16. Forms and redirectsGET and POST, validation messages, post/redirect/get, flash messages and CSRF tokens.45 min
  17. Accounts and loginsPassword hashing with bcrypt, sessions, pages that need a login, and safe logout.45 min
  18. Project: a trail log web appA multi-page app with a database, accounts, forms and tests.45 min
  19. JavaScript for Python programmersVariables, functions, arrays and objects mapped from Python, and the traps: truthy empty arrays, for...in and string sort.35 min
  20. Async JavaScript: promises, await and fetchThe event loop, async and await, fetch with res.ok checks, Promise.all, and timeouts with AbortController.35 min
  21. Modules, Node and reading TypeScriptimport and export, package.json, classes, and types as notes the compiler checks, read through a small tool server.30 min
  22. A chat front end in the browserThe DOM and events, model text kept out of innerHTML, a streamed reply parsed from server-sent events, and a Stop button.40 min
  23. APIs with FastAPITyped routes, pydantic models, automatic validation and docs, tested with httpx.45 min
  24. Streaming from the serverServer-sent events written by a server: an ASGI app that sends a body in pieces, FastAPI's StreamingResponse, heartbeats, and what a closed connection looks like.40 min
  25. Project: a FastAPI service with accountsA session per request, bcrypt sign-ups, signed tokens, ownership checks and tests on a fresh database.45 min
  26. Serving a model behind FastAPILoad once with lifespan, a typed predict route, a batch route, a cap on work in flight, 429 with Retry-After, a readiness route and a 202 job.45 min
  27. Capstone: a streaming chat serviceA FastAPI service with key auth, a per-user bucket, a token budget, request ids and an event-stream reply, tested on fresh state.45 min
Part of a free course 127 lessons

Free Python developer course

Go from your first line of code to working as a Python developer: projects, testing, data, databases, web apps and APIs, all in your browser.

Part of a free course 20 lessons

Build and Operate HTTP APIs

Design, test, deploy, and operate an HTTP API that another engineer can use.

Never trained an AI? Teach a small one to write, right in your browser. It takes about 20 seconds and needs no account. Teach it to write