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