Background Tasks & Lifespan in Python

From the FastAPI cheat sheet ยท Advanced Features ยท verified Jul 2026

Background Tasks & Lifespan

Run tasks after returning a response and manage app startup/shutdown.

python
from fastapi import BackgroundTasks

@app.post("/notify/")
async def send_notification(
    email: str, background_tasks: BackgroundTasks,
):
    background_tasks.add_task(send_email, email)
    return {"message": "Notification queued"}
๐Ÿ’ก Background tasks run after the response โ€” the client doesn't wait for them
โšก Use lifespan for startup tasks: loading ML models, connecting to DBs, etc.
๐Ÿ“Œ For heavy background work, use Celery or ARQ instead of BackgroundTasks
๐ŸŸข Store shared resources on app.state inside the lifespan context
backgroundlifespanstartupshutdown

More Python tasks

Back to the full FastAPI cheat sheet