Background tasks in FastAPI

Difficulty: Intermediate

Question

What are background tasks in FastAPI and when should you use them?

Answer

FastAPI's `BackgroundTasks` allows you to run functions after returning a response - useful for operations that don't need to block the client.

Use cases: - Sending confirmation emails - Logging to external services - Post-processing uploaded files - Sending notifications

Limitations: Background tasks run in the same process/event loop. They are not persistent - if the server restarts, queued tasks are lost. For production-grade background processing, use Celery with Redis/RabbitMQ or ARQ (async Redis Queue).

Code examples

BackgroundTasks usage

from fastapi import FastAPI, BackgroundTasks
import time

app = FastAPI()

def send_email(email: str, message: str):
    # Simulate slow email send
    time.sleep(2)
    print(f"Email sent to {email}: {message}")

async def log_action(user_id: int, action: str):
    # Async background task
    await some_logging_service.log(user_id, action)

@app.post("/signup")
async def signup(email: str, background_tasks: BackgroundTasks):
    # ... create user in DB ...
    background_tasks.add_task(send_email, email, "Welcome to the platform!")
    return {"message": "Signed up! Check your email."}  # returns immediately

Key points

Concepts covered

BackgroundTasks, async tasks, fire and forget, Celery