📡 You're offline — showing cached content
New version available!
Quick Access
Tutorials FastAPI Background Tasks

Background Tasks

5 min read Quiz at the end
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
Topic Quiz · 2 questions

Test your understanding before moving on

1. What are FastAPI BackgroundTasks used for?
💡 BackgroundTasks run after the response for emails, logging, non-critical work.
2. When should you use Celery instead of BackgroundTasks?
💡 Celery provides queues, retries, monitoring for heavy or critical background work.