← Back to FastAPI, page 2

fastapi-0026 · Medium mid

How do BackgroundTasks work in FastAPI, and when should you use a real task queue instead?

Add a BackgroundTasks parameter and call background_tasks.add_task(func, *args); FastAPI runs the function after the response has been sent, in the same process. It suits small, quick follow-up work like sending one email or writing an audit log. For heavy, slow or must-not-be-lost work, use a task queue (Celery, ARQ, Dramatiq, RQ) with a broker, because in-process tasks are lost if the server restarts and they compete with requests for resources.

Full answer

BackgroundTasks (from Starlette) lets an endpoint return quickly and finish small jobs afterwards:

python
@app.post("/fees/pay")
def pay(payment: Payment, background_tasks: BackgroundTasks):
    save(payment)
    background_tasks.add_task(send_receipt, payment.email, payment.amount)
    return {"status": "paid"}

How it works:

  • Tasks are collected during the request and run after the response is sent, in order.
  • def tasks run in the thread pool; async def tasks run on the event loop (so they must not block).
  • Dependencies can also accept BackgroundTasks; FastAPI merges all tasks for the request.
  • The client does not wait, but the worker process does: the connection slot and memory stay in use until tasks finish.

Limits:

  • No persistence. If the process restarts or crashes, pending tasks are lost.
  • No retries, scheduling, or visibility (no dashboard, no status).
  • Runs in the web process, so heavy work slows down request handling. CPU-heavy work in an async def task blocks the event loop.
  • Resources from yield dependencies follow their scope. With the default scope="request", current FastAPI closes them after background tasks finish; with scope="function" they are already closed. Opening a fresh session inside the task is the safe habit either way, and it keeps a slow task from holding the request's connection.

Choose a task queue when:

  • The work takes more than a few seconds (reports, video processing, bulk emails).
  • It must not be lost (payments follow-up, notifications with legal weight).
  • You need retries with backoff, rate limits, scheduling or monitoring.
  • You want to scale workers separately from the web servers.

Options: Celery (mature, many features), ARQ or SAQ (asyncio, Redis), Dramatiq, RQ, Taskiq; or a managed queue (SQS, Cloud Tasks, Pub/Sub). Pass IDs, not large objects, and make tasks idempotent because queues deliver at least once.

python
import time

from fastapi import BackgroundTasks, Depends, FastAPI
from fastapi.testclient import TestClient
from pydantic import BaseModel

app = FastAPI()
outbox = []


class Payment(BaseModel):
    roll_no: str
    email: str
    amount: int


def send_receipt(email: str, amount: int):
    time.sleep(0.2)                                  # slow email provider
    outbox.append(f"receipt for {amount} sent to {email}")


def audit(background_tasks: BackgroundTasks):
    background_tasks.add_task(outbox.append, "audit log written")


@app.post("/fees/pay", dependencies=[Depends(audit)])
def pay(payment: Payment, background_tasks: BackgroundTasks):
    background_tasks.add_task(send_receipt, payment.email, payment.amount)
    return {"status": "paid", "outbox_when_returning": list(outbox)}


c = TestClient(app)
r = c.post("/fees/pay", json={"roll_no": "BCA-17", "email": "parent@example.com", "amount": 1500})
print(r.json())
print(outbox)    # TestClient waits for background tasks before returning

Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed. The response is built before the tasks run, so outbox_when_returning is empty; TestClient waits for the tasks, so the final print shows both. Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0): {'status': 'paid', 'outbox_when_returning': []} ['audit log written', 'receipt for 1500 sent to parent@example.com']

Key points

  • add_task runs work after the response is sent, in the same process
  • Good for small, quick, losable work
  • No persistence, retries or monitoring
  • Open fresh resources inside the task instead of borrowing the request's
  • Use a task queue for heavy or critical work

Common mistakes

  • Using BackgroundTasks for long or critical jobs that must survive restarts
  • Relying on the request's database session inside a long background task
  • Running CPU-heavy work in an async def background task
  • Expecting retries or a status endpoint from BackgroundTasks

Follow-ups

  • How would you report progress of a long report generation to the client?
  • What happens to pending background tasks during a deploy?
  • Why should queued tasks receive IDs instead of full objects?

Tips

  • Explain exactly when tasks run
  • Name the limitations honestly
  • Give a clear rule for switching to a queue