patternpythonfastapiTip
FastAPI BackgroundTasks for fire-and-forget after response
Viewed 0 times
background tasksfire and forgetpost-responseemailwebhook
Problem
Sending emails, logging analytics, or triggering webhooks as part of a request adds latency. Users shouldn't wait for non-critical work to complete.
Solution
Inject BackgroundTasks into the endpoint and call add_task() to schedule work that runs after the response is sent. For heavy workloads, use Celery or ARQ instead.
from fastapi import BackgroundTasks, FastAPI
app = FastAPI()
def send_welcome_email(email: str):
# Blocking I/O is fine here — runs in a thread
print(f'Sending email to {email}')
@app.post('/users/')
async def create_user(email: str, background_tasks: BackgroundTasks):
# ... create user in DB ...
background_tasks.add_task(send_welcome_email, email)
return {'message': 'User created'}Why
BackgroundTasks uses Starlette's background task mechanism. Tasks run in the same process after the response is sent. Sync functions are run in a thread pool; async functions are awaited in the event loop.
Gotchas
- BackgroundTasks are NOT suitable for long-running or critical tasks — process restart loses them
- Exceptions in background tasks are silently swallowed unless you add error handling inside the task
- DB sessions from the request scope are already closed when the background task runs — open a new session
- For reliability, use a proper task queue (Celery, ARQ, RQ) instead
Context
Sending notifications, logging, or triggering lightweight async work after an HTTP response
Revisions (0)
No revisions yet.