← Back to FastAPI
Lesson 7.1 · Async, Background Tasks & Middleware

async def or def?

FastAPI runs async def routes on one event loop and def routes in a pool of threads. We measured what that means: one blocking call inside async def made 10 requests take 10.06 s and froze /health for almost 10 s; plain def has a hidden limit of 40 threads (100 requests: 3.24 s); and CPU work is not helped by either - only other processes help.

Intermediate35 min

What you will be able to do

  • Explain what the event loop and the thread pool do in FastAPI
  • Choose between async def and def for a route
  • Spot a blocking call inside async def, and fix it
  • Use run_in_threadpool for a blocking library in an async route
  • Know the 40-thread limit, and raise it
  • Move CPU-heavy work to a process pool

The idea, in plain English

Most of the time a web API is waiting: for a database, another API, a file. async and await let one Python process do other work while it waits. FastAPI runs every async def route on ONE event loop - a single worker that switches between requests each time one of them says await.

That only works if every route really awaits. A route that calls something slow WITHOUT await keeps the event loop busy, and every other request - even a tiny health check - has to wait. For code that cannot await, FastAPI has a second way: a plain def route runs in a thread from a pool, so the loop stays free.

Lesson 5.6 measured this for databases. Here we measure the general rules with a slow report, 10 and 100 requests at once, and some CPU work - on a real uvicorn server, with httpx sending the requests. Python 3.13.17, FastAPI 0.143.0, uvicorn 0.54.0, AnyIO 4.16.0, httpx 0.28.1, on a 4-core laptop.

Worked example: One app with a slow "report" written four ways - plain def, async with await, async with a blocking call, and async with run_in_threadpool - hit by 10 and 100 requests at once, plus CPU-heavy routes.

workflowTen slow requests at oncestep 1 / 3

1 - async def with await

Each request awaits; the loop serves the others meanwhile. All ten wait at the same time.

10 requests
1.07 s
/health
12 ms

Each request needs 1 second of waiting. How the route is written decides how long all ten take. Real results.

Words you will see in this lesson

A few words about doing many things at once.

Small dictionary
BlockingA call that holds on to the program until it is finished, like time.sleep(1).
await"Wait here, and let other work run meanwhile." Only works on async functions.
Event loopThe one worker that runs all async def routes, switching at each await.
ThreadA separate line of work inside the same process. FastAPI runs def routes in threads.
Thread poolA fixed group of ready threads that requests borrow and give back.
I/O-boundSlow because of waiting - for a network, a disk, a database.
CPU-boundSlow because of calculating - the processor is busy the whole time.
GILGlobal Interpreter Lock: in normal Python only one thread runs Python code at a time.

An everyday example: a tea stall

  • One tea maker (the event loop) puts a pot on the stove and, while it boils, takes the next order. That is await: waiting without standing still.
  • If the tea maker stares at one pot until it boils, nobody else is served. That is a blocking call inside async def.
  • The owner can also hire helpers (the thread pool). Each helper stands at one pot - but there are only 40 helpers.
  • And if a customer wants a huge pile of onions chopped - real work, not waiting - extra helpers sharing one knife (the GIL) do not help. You need more knives: more processes.

Example 1 - one slow report, written four ways

slow.py has the same 1-second job behind four routes:

  • slow_report() stands for a library with no async version - it calls time.sleep(1). requests.get, a normal SQLAlchemy Session (Lesson 5.6) or reading a file behave the same.
  • /def - plain def. FastAPI runs it in a thread from the pool.
  • /async - async def with await asyncio.sleep(1): real async waiting.
  • /async-blocking - async def that calls slow_report() directly. It looks async, but nothing is awaited.
  • /async-threadpool - async def that hands slow_report to a thread with await run_in_threadpool(...).
  • /health - a tiny async route. If it is slow, the whole server is stuck.
  • The CPU routes at the bottom are used further down.
Example 1 - slow.py
import asyncio import time from fastapi import FastAPI from fastapi.concurrency import run_in_threadpool app = FastAPI() def slow_report() -> dict: # a slow library with no async version time.sleep(1) # stands in for 1 second of waiting return {"report": "ready"} @app.get("/def") # plain def: FastAPI runs it in a thread def with_def(): return slow_report() @app.get("/async") # async def + await: waits without blocking async def with_await(): await asyncio.sleep(1) return {"report": "ready"} @app.get("/async-blocking") # async def + a blocking call: the trap async def async_but_blocking(): return slow_report() @app.get("/async-threadpool") # async def that hands the blocking call to a thread async def async_with_threadpool(): return await run_in_threadpool(slow_report) def count_up() -> int: # CPU work: no waiting, just counting total = 0 for i in range(5_000_000): total += i return total @app.get("/cpu-def") def cpu_def(): return {"total": count_up()} @app.get("/cpu-async") async def cpu_async(): return {"total": count_up()} @app.get("/health") # a fast route, to see if the server still answers async def health(): return {"ok": True}
load.py - n requests at once, plus one /health in the middle
import asyncio import sys import time import httpx BASE = "http://127.0.0.1:8171" async def main(path: str, n: int): async with httpx.AsyncClient(base_url=BASE, timeout=300, limits=httpx.Limits(max_connections=None)) as client: start = time.perf_counter() slow = [asyncio.create_task(client.get(path)) for _ in range(n)] # n requests at once await asyncio.sleep(0.1) t = time.perf_counter() await client.get("/health") # meanwhile: is the server still answering? health_ms = (time.perf_counter() - t) * 1000 codes = {r.status_code for r in await asyncio.gather(*slow)} total = time.perf_counter() - start print(f"{n:>3} x {path:<16} -> {total:5.2f} s total status {codes} /health took {health_ms:6.0f} ms") asyncio.run(main(sys.argv[1], int(sys.argv[2])))
Run it (two terminals)
uvicorn slow:app --port 8171 --log-level warning # terminal 1 python load.py /def 10 # terminal 2, and so on
Output - 10 requests to each route
10 x /def -> 1.08 s total status {200} /health took 5 ms 10 x /async -> 1.07 s total status {200} /health took 12 ms 10 x /async-blocking -> 10.06 s total status {200} /health took 9956 ms 10 x /async-threadpool -> 1.06 s total status {200} /health took 5 ms

Reading the output

  • /def - 1.08 s for all ten: ten threads waited side by side. /health answered in 5 ms.
  • /async - 1.07 s: ten awaits on one loop. /health 12 ms.
  • /async-blocking - 10.06 s: the requests ran one after another, 1 s each. And /health took 9956 ms - the server could not answer anything else for almost 10 seconds.
  • /async-threadpool - 1.06 s and /health 5 ms: the same blocking function, moved off the loop.
  • So async def is not "faster". It is a promise: "I will await when I wait". Break the promise and every user pays.

The trap: a blocking call inside async def

/async-blocking is the most common async mistake. Nothing fails, no error, no warning - with one test request it looks fine. It only shows up when requests come at the same time:

  • Before: 10 requests took 10.06 s, and /health waited 9956 ms.
  • Fix 1 - if the route does not await anything, write plain def. FastAPI moves it to a thread for you (1.08 s).
  • Fix 2 - if the route also awaits other things, keep async def and wrap only the blocking call: await run_in_threadpool(slow_report) (1.06 s).
  • Fix 3 - best, when it exists: an async version of the library (httpx instead of requests in Lesson 7.2, AsyncSession in Lesson 5.6).
  • What blocks: time.sleep, requests, a normal database session, open().read() on big files, most SDKs without "async" in their name.
The trap and the fix, side by side
@app.get("/async-blocking") # 10 requests: 10.06 s async def async_but_blocking(): return slow_report() @app.get("/async-threadpool") # 10 requests: 1.06 s async def async_with_threadpool(): return await run_in_threadpool(slow_report)

The hidden limit: 40 threads

Ten requests were fine. What about 100?

  • 100 x /async - 1.39 s. One loop can wait for many things at once; awaiting costs almost nothing.
  • 100 x /def - 3.24 s. The thread pool has 40 threads (AnyIO’s default). Requests 41 to 100 waited for a free thread: three rounds of about 1 s.
  • The limit is shared: def routes AND def dependencies borrow from the same 40.
  • You can raise it at startup with a lifespan (Lesson 7.5 covers lifespan in full). With 100 threads, 100 x /def took 1.41 s.
  • More threads are not free: each one uses memory, and a database usually allows only so many connections. Raise it when you measure a need, not just in case.
Output - 100 requests at once
100 x /def -> 3.24 s total status {200} /health took 73 ms 100 x /async -> 1.39 s total status {200} /health took 58 ms
more_threads.py - slow.py with 100 threads (only the new part)
from contextlib import asynccontextmanager import anyio.to_thread from fastapi import FastAPI @asynccontextmanager async def lifespan(app: FastAPI): limiter = anyio.to_thread.current_default_thread_limiter() print("threads before:", limiter.total_tokens) limiter.total_tokens = 100 # room for 100 def routes at once print("threads after: ", limiter.total_tokens) yield app = FastAPI(lifespan=lifespan)
Output - the server log, then 100 requests
threads before: 40 threads after: 100 100 x /def -> 1.41 s total status {200} /health took 104 ms

CPU work: neither async nor threads help

Waiting and calculating are different. count_up() adds numbers in a loop - no waiting at all. Alone it took 345 ms. Then 8 requests at once:

  • /cpu-def - 3.06 s, about 8 x 345 ms. Eight threads, but the GIL lets only one run Python code at a time, so they took turns. /health still answered (57 ms) because threads take turns with the loop too.
  • /cpu-async - 2.79 s, and /health took 2691 ms. CPU work in async def blocks the loop exactly like time.sleep.
  • /cpu-process - 1.76 s and /health 7 ms. A ProcessPoolExecutor runs count_up in 4 other processes, each with its own GIL, on 4 cores.
  • Not 4 times faster: starting the work in another process and sending the result back costs time. Measure before you add a pool.
  • For work that takes seconds or minutes, do not make the user wait at all - Lesson 7.3 (background tasks). Several uvicorn workers (Lesson 10.1) also use more cores, for the whole app.
cpu_pool.py
import asyncio from concurrent.futures import ProcessPoolExecutor from contextlib import asynccontextmanager from fastapi import FastAPI from slow import count_up # the same CPU work as before pool: ProcessPoolExecutor | None = None @asynccontextmanager async def lifespan(app: FastAPI): global pool pool = ProcessPoolExecutor(max_workers=4) # 4 processes = 4 CPU cores on this laptop yield pool.shutdown() app = FastAPI(lifespan=lifespan) @app.get("/cpu-process") async def cpu_in_process(): loop = asyncio.get_running_loop() total = await loop.run_in_executor(pool, count_up) # another process, so no fight for the GIL return {"total": total} @app.get("/health") async def health(): return {"ok": True}
Output - count_up alone, then 8 requests at once
count_up() alone: 345 ms 8 x /cpu-def -> 3.06 s total status {200} /health took 57 ms 8 x /cpu-async -> 2.79 s total status {200} /health took 2691 ms 8 x /cpu-process -> 1.76 s total status {200} /health took 7 ms

Tip: A process pool can only run functions it can import: define them at the top level of a module (like count_up in slow.py), not inside a route or as a lambda.

So: async def or def?

Ask what the route spends its time on:

Choosing
Awaits async librarieshttpx, AsyncSession, asyncio.sleep, aiofiles
Calls blocking libraries onlyrequests, a normal Session, most SDKs
BothAwaits some things, one blocking call
Quick, no waiting at allReturns a dict, checks a value
Heavy CPU workImages, big calculations, parsing large files

Watch out: When unsure, plain def is the safer default. A blocking call in def costs one thread; the same call in async def stops the whole server.

async and threads at a glance

Async route

Runs on the event loop. Must await its waits.

async def route(): await something()
Sync route

Runs in a thread from the pool.

def route(): blocking()
Blocking call in async

Move it to a thread.

from fastapi.concurrency import run_in_threadpool
await run_in_threadpool(fn, arg)
Thread limit

Default 40, shared by def routes and def dependencies.

anyio.to_thread.current_default_thread_limiter().total_tokens = 100
CPU work

Other processes, each with its own GIL.

await loop.run_in_executor(process_pool, fn)
Async sleep

Never time.sleep in async def.

await asyncio.sleep(1)

Try it yourself

The code does not change. Swap the content string and the program does something else entirely.

Feel it

“Run uvicorn slow:app --port 8171, then python load.py /async-blocking 5. While it runs, open http://127.0.0.1:8171/health in the browser. How long does it spin?”

Find the round

“Run python load.py /def 41, then /def 40. Why does one more request add a whole second?”

Forget an await

“In /async, remove the word await before asyncio.sleep(1). What does the route return now, and what does uvicorn print?”

Your cores

“Change max_workers in cpu_pool.py to your number of cores (os.cpu_count()) and run python load.py /cpu-process 8 again.”

What usually goes wrong

A blocking call inside async def

10 requests took 10.06 s and /health waited 9956 ms. Use def, run_in_threadpool, or an async library.

✗ async def report():
    return slow_report()
✓ def report():
    return slow_report()
time.sleep in async code

It blocks the loop. Use the async version.

✗ time.sleep(1)
✓ await asyncio.sleep(1)
Making every route async def "because it is faster"

async def is only faster when the route awaits. With blocking calls it is far slower.

Forgetting the 40-thread limit

100 def requests took 3.24 s in three rounds. Use async for very many waits, or raise the limit after measuring.

Using threads for CPU work

8 threads took 3.06 s - the same as one after another, because of the GIL. Use processes.

Best practices

  • Use async def only when the route awaits async libraries.
  • Default to def for routes that call blocking libraries.
  • Wrap a single blocking call in an async route with run_in_threadpool.
  • Test with many requests at once, and watch a fast route like /health while you do.
  • Send CPU-heavy work to other processes or to a background job.
  • Raise the thread limit only when you have measured a need.

Practice

Write these yourself before opening anything. Getting them wrong first is most of how this sticks.

1.

Add GET /two-reports that needs slow_report() twice. Write it three ways: def calling it twice, async def with two run_in_threadpool calls one after the other, and async def that runs both at once with asyncio.gather. Measure each with python load.py <path> 10.

Show hint

await asyncio.gather(run_in_threadpool(slow_report), run_in_threadpool(slow_report)) - the two threads wait side by side, so about 1 s instead of 2 s.

2.

Find the blocking calls: in your own project (or the to-do API from Lesson 6.4), list every async def route and dependency, and mark each call that does not have await in front of it. Which ones wait on something?

Coding challenge

A blocking detector

Blocking calls in async routes are silent. Build a small checker that warns when the event loop is stuck.

It should
  • In a lifespan, start an asyncio task that sleeps 0.1 s in a loop and measures how late it wakes up.
  • If it wakes more than 0.2 s late, print a warning with the delay.
  • Run python load.py /async-blocking 3 and show the warnings; run /async 3 and show there are none.
  • Also try asyncio’s debug mode (PYTHONASYNCIODEBUG=1) and compare what it reports.

Key points

  • async def routes share one event loop; def routes run in a thread pool.
  • A blocking call in async def stops every request - 10.06 s for 10, /health 9956 ms.
  • def is safe for blocking code, but the pool has 40 threads by default.
  • await lets one loop handle 100 waiting requests in 1.39 s.
  • run_in_threadpool moves one blocking call off the loop.
  • CPU work needs processes: threads took 3.06 s, a process pool 1.76 s.

Quick check before you move on

How long did 10 requests to /async-blocking take, and /health meanwhile?
10.06 s, and /health took 9956 ms.
Why did 100 requests to /def take 3.24 s?
Only 40 threads: requests waited for a free thread, in about three rounds of 1 s.
What did 100 x /def take with 100 threads?
1.41 s.
Which CPU route kept /health fast, and how long did it take for 8 requests?
/cpu-process - 1.76 s, /health 7 ms.

Interview questions

How does FastAPI handle def versus async def endpoints?

async def endpoints run directly on the event loop, so they must not block; def endpoints (and sync dependencies) run in a worker thread from AnyIO’s thread pool, 40 tokens by default, so blocking libraries are safe but concurrency is capped by the pool size.

A FastAPI service gets slow under load but each request is fast alone. What do you check?

Blocking calls inside async def (sync HTTP clients, sync DB sessions, time.sleep, CPU work) that stall the loop - visible as a fast endpoint like /health getting slow under load; thread-pool exhaustion for sync endpoints; then connection pool limits and CPU saturation. Fix with def or run_in_threadpool, async libraries, a larger limiter, process pools or more workers.

How do you run CPU-bound work in a FastAPI app?

Not on the event loop and not just in threads (GIL). Use a ProcessPoolExecutor via run_in_executor for short jobs, multiple worker processes to use all cores, and a task queue for long jobs so the request returns quickly.

Quiz

  1. 1.

    Why is a blocking call worse in async def than in def?

  2. 2.

    Why did 8 threads not speed up count_up?

  3. 3.

    When is async def clearly the better choice?

Comments

Sign in to leave a comment. Your name and photo come from Google; nothing else is shared.

Loading comments...