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

  • BackgroundTasks are added via dependency injection or directly in the route
  • Multiple tasks can be queued - they run sequentially after the response
  • For async background tasks, define them with `async def`

Common follow-up questions

  • How does Celery differ from FastAPI's BackgroundTasks?
  • What happens to background tasks if an exception occurs?

Interview tips

  • Always mention the persistence limitation - BackgroundTasks are process-scoped, not durable

Concepts covered

BackgroundTasks, async tasks, fire and forget, Celery

More FastAPI Interview questions