Skip to content

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.

17 min read0/5 questions

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.

Pythontoy_event_loop.py
import heapq clock = 0 def run(tasks): global clock clock = 0 queue = [(0, i, task) for i, task in enumerate(tasks)] heapq.heapify(queue) while queue: wake_at, i, task = heapq.heappop(queue) clock = max(clock, wake_at) try: wait_ms = next(task) # run until the next await heapq.heappush(queue, (clock + wait_ms, i, task)) except StopIteration: pass def request(name, db_ms): print(f"t={clock:>3}ms {name}: send query") yield db_ms # like `await session.execute(...)` print(f"t={clock:>3}ms {name}: respond") def blocking_request(name, ms): global clock print(f"t={clock:>3}ms {name}: time.sleep({ms / 1000})") clock += ms # the loop is stuck, nobody else runs print(f"t={clock:>3}ms {name}: respond") yield 0 print("Three cooperative requests:")run([request("A", 100), request("B", 100), request("C", 100)])print()print("One blocking request first:")run([blocking_request("A", 100), request("B", 100), request("C", 100)])
Output
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.

Quick check
This route is called by 50 users at the same moment on one Uvicorn worker. Roughly how long does the last user wait?
@app.get("/report")
async def report():
  time.sleep(1)          # pretend this is a slow API call with requests.get
  return {"ok": True}
Need a nudge? A hint rules out a wrong answer.

async def or def?

FastAPI handles the two kinds of path function differently:

  • An async def route runs directly on the event loop. Fast and cheap, but it must never block.
  • A plain def route 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...WriteWhy
await libraries: httpx.AsyncClient, asyncpg, async SQLAlchemyasync defWaits overlap on the loop
Blocking libraries: requests, psycopg sync, sync SQLAlchemy, file readsdefRuns in the threadpool, loop stays free
Nothing slow at allEitherasync def avoids a thread hop
Heavy CPU work: image resizing, ML inference, big loopsNeither, ideallyMove it to a worker process or queue
app/api/weather.py
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.

Match the pairs0/4 matched

Pick the right way to write each route.

Choose an item, then its match on the other side.

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.

app/api/users.py
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 user

Here is the mechanism, which is simpler than it sounds:

Pythonbackground_tasks.py
class BackgroundTasks: def __init__(self): self.tasks = [] def add_task(self, fn, *args, **kwargs): self.tasks.append((fn, args, kwargs)) def send_welcome_email(email): print(f"[background] emailing {email}") def signup(email, background_tasks): print(f"[route] saving {email}") background_tasks.add_task(send_welcome_email, email) return {"status": 201, "email": email} def serve(route, *args): tasks = BackgroundTasks() response = route(*args, tasks) print("[server] response sent:", response) for fn, fn_args, fn_kwargs in tasks.tasks: # only now do the tasks run fn(*fn_args, **fn_kwargs) serve(signup, "ada@example.com")
Output
Press Run (⌘ Enter) to see what happens.
Predict the outputPython

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)
Need a nudge? Hints walk you through it.

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.

Quick check
Which job should NOT use BackgroundTasks?
Need a nudge? A hint rules out a wrong answer.

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.

An API with a job queue
ClientClientFastAPI: enqueues jobsFastAPIenqueues jobsPostgreSQL: job status, resultsPostgreSQLjob status, resultsRedis broker: durable job listRedis brokerdurable job listWorkers: Celery / arq / RQWorkersCelery / arq / RQEmail providerEmail providerObject storage: generated reportsObject storagegenerated reportsPOST /reportsenqueuestatus rowpull jobsenduploadmark done

The client asks for a big report. Building it takes 40 seconds, far too long for a request.

1/5

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.

Put it in order5 steps

Order the life of a job that sends a monthly report.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

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.

app/api/ws.py
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:
        pass

Each 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

ChallengeMedium

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 in results[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_retries attempts in total; after the last failed attempt, mark it "failed" and append its id to dead_letters.
  • 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]
Python
class JobQueue: def __init__(self, max_retries: int = 2): pass def enqueue(self, fn, *args, **kwargs) -> int: pass def work(self) -> None: pass def status(self, job_id: int) -> str: pass
Key terms
event loop
Runs many coroutines on one thread, switching whenever one awaits. Blocking calls stall all of them.
threadpool
Where FastAPI runs plain def routes 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.