Lesson 21 of 59Async and background work
Background Tasks and Async
Choose async def or def correctly, never block the event loop, and move slow work to background tasks or a job queue.
Your API now has a real database, and the last two lessons already used async def with it. This unit looks at async itself, and at work that should not happen inside a request. One time.sleep(2) in the wrong place can make an entire FastAPI server stop answering for two seconds, for every user at once. Async is FastAPI's biggest performance feature and its most common foot-gun. This lesson shows exactly how requests share the event loop, when to write async def versus def, and what to do with work that is too slow for a request at all, like sending emails or generating reports.
One loop, many requests
Recall from Async and Await in the Python course: an event loop runs many coroutines on one thread. Each one runs until it hits an await on something slow (a database reply, an HTTP call), then yields so the loop can run another. Nothing runs in parallel; they take turns, very quickly. That is cooperative multitasking: it only works if every coroutine cooperates by awaiting instead of blocking.
The toy scheduler below has a fake clock so you can see it. Each request is a generator; yield 100 means "await something that takes 100 ms". The blocking version simulates time.sleep: it advances the clock without ever yielding.
Press Run (⌘ Enter) to see what happens.In the first run all three finish at 100 ms: their waits overlapped. In the second, B and C cannot even start until A's sleep ends, so they finish at 200 ms. On a real server with hundreds of requests per second, one blocking call per request freezes everything.
@app.get("/report")
async def report():
time.sleep(1) # pretend this is a slow API call with requests.get
return {"ok": True}async def or def?
FastAPI handles the two kinds of path function differently:
- An
async defroute runs directly on the event loop. Fast and cheap, but it must never block. - A plain
defroute runs in a threadpool (a pool of worker threads, 40 by default via AnyIO). Blocking inside it only ties up that one thread, and the loop keeps serving others.
So the rule is about what the code inside does:
| Inside the route you call... | Write | Why |
|---|---|---|
await libraries: httpx.AsyncClient, asyncpg, async SQLAlchemy | async def | Waits overlap on the loop |
Blocking libraries: requests, psycopg sync, sync SQLAlchemy, file reads | def | Runs in the threadpool, loop stays free |
| Nothing slow at all | Either | async def avoids a thread hop |
| Heavy CPU work: image resizing, ML inference, big loops | Neither, ideally | Move it to a worker process or queue |
import httpx
import requests
@app.get("/weather/async")
async def weather_async(city: str):
async with httpx.AsyncClient(timeout=5) as client:
response = await client.get("https://api.example.com/weather", params={"city": city})
return response.json()
@app.get("/weather/sync")
def weather_sync(city: str): # plain def: runs in the threadpool
response = requests.get("https://api.example.com/weather", params={"city": city}, timeout=5)
return response.json()Both are fine. The bug is the mix: requests.get inside async def. If you are stuck with a blocking library in an async route, hand it to a thread with await asyncio.to_thread(blocking_fn, arg) (or Starlette's run_in_threadpool). Dependencies follow the same rule: def dependencies run in the threadpool too.
Pick the right way to write each route.
Background tasks
Some work does not need to finish before you answer: sending a welcome email, writing an audit log, pinging a webhook. The user should not wait for an SMTP server. FastAPI's BackgroundTasks runs functions after the response has been sent.
from fastapi import BackgroundTasks
def send_welcome_email(email: str) -> None:
... # talk to your email provider
@router.post("/signup", status_code=201)
def signup(body: UserCreate, background_tasks: BackgroundTasks, db: DB) -> UserRead:
user = create_user(db, body)
background_tasks.add_task(send_welcome_email, user.email)
return userHere is the mechanism, which is simpler than it sounds:
Press Run (⌘ Enter) to see what happens.With the code above, what does this print?
def note(msg):
print("task:", msg)
def ping(background_tasks):
background_tasks.add_task(note, "second")
background_tasks.add_task(note, "third")
print("route: first")
return "ok"
serve(ping)BackgroundTasks is great for small, fast, best-effort work. But the tasks run inside the same process: if the server restarts or crashes, queued tasks are gone. There are no retries, no visibility into what is pending, and a slow task still competes with your requests for CPU and threads.
BackgroundTasks?When you need a real queue
A job queue stores jobs in a durable broker (Redis, RabbitMQ, Amazon SQS) and separate worker processes pull and run them. The API only enqueues and responds in milliseconds.
The client asks for a big report. Building it takes 40 seconds, far too long for a request.
Popular choices: Celery (the long-standing standard, many features, Redis or RabbitMQ), RQ (simple, Redis only), arq (small and asyncio-native, Redis), Dramatiq, and managed queues like Amazon SQS with your own worker loop. Design jobs to be idempotent (safe to run twice), because retries mean some jobs will run more than once.
Order the life of a job that sends a monthly report.
- Tap the steps below in the right order.
WebSockets, briefly
Background work often ends with "tell the user it is done". Besides polling, you can keep a WebSocket open: a two-way connection that stays alive, which ASGI supports natively.
from fastapi import WebSocket, WebSocketDisconnect
@app.websocket("/ws/jobs/{job_id}")
async def job_updates(websocket: WebSocket, job_id: str):
await websocket.accept()
try:
while True:
status = await get_job_status(job_id) # async: must not block
await websocket.send_json({"job_id": job_id, "status": status})
if status == "done":
break
await asyncio.sleep(1)
except WebSocketDisconnect:
passEach open socket is a long-lived coroutine on the event loop, which is why blocking calls are even more harmful here. With several workers or servers, a message produced on one must reach sockets held by another, so real chat and notification systems add a pub/sub channel such as Redis.
Practice
A job queue with retries
Build the core of a worker queue like Celery or RQ, in memory. Write JobQueue(max_retries=2):
enqueue(fn, *args, **kwargs) -> int: store a job and return its id (ids start at 1). Its status is"queued".work(): process jobs in FIFO order until the queue is empty.- If
fn(*args, **kwargs)returns, store the value inresults[job_id]and mark the job"done". - If it raises, put the job back at the end of the queue to retry. A job gets at most
1 + max_retriesattempts in total; after the last failed attempt, mark it"failed"and append its id todead_letters.
- If
status(job_id)returns"queued","done"or"failed".attempts[job_id]counts how many times the job ran.
q = JobQueue(max_retries=1)
ok = q.enqueue(lambda a, b: a + b, 2, 3)
bad = q.enqueue(lambda: 1 / 0)
q.work()
q.results[ok], q.status(bad), q.attempts[bad], q.dead_letters # 5, "failed", 2, [2]- event loop
- Runs many coroutines on one thread, switching whenever one awaits. Blocking calls stall all of them.
- threadpool
- Where FastAPI runs plain
defroutes and dependencies, so blocking code does not freeze the loop. - BackgroundTasks
- Runs functions after the response is sent, in the same process. No retries, lost on crash.
- job queue
- Durable storage of jobs (Redis, RabbitMQ, SQS) consumed by separate worker processes, with retries.
- idempotent job
- A job that is safe to run more than once, essential because queues retry.
- WebSocket
- A long-lived, two-way connection, supported by ASGI, used for live updates.