Run post-response work (email, logging) with BackgroundTasks — and when to use Celery instead.
Background Tasks
from fastapi import BackgroundTasks
def send_welcome_email(email: str, name: str):
# This runs AFTER response is sent
import time; time.sleep(5) # simulate slow email
print("Sending welcome email to " + email)
def log_activity(user_id: int, action: str):
ActivityLog.objects.create(user_id=user_id, action=action)
@app.post("/register", status_code=201)
def register(
user_data: UserCreate,
background_tasks: BackgroundTasks,
db: Session = Depends(get_db),
):
user = create_user(db, user_data)
# These run after response is returned
background_tasks.add_task(send_welcome_email, user.email, user.name)
background_tasks.add_task(log_activity, user.id, "registered")
return user
# For heavy tasks, use Celery instead of BackgroundTasks
# BackgroundTasks are good for quick non-critical operations