FastAPI interview question · Most asked

What are `BackgroundTasks` and when should you use a real task queue instead?

Summary

BackgroundTasks runs small functions after the response is sent, in the same process; for heavy, slow, retryable or critical jobs, use a queue like Celery, RQ, Dramatiq, arq or a managed queue.

Longer Answer

Background tasks share the server process: if the worker crashes or restarts, tasks are lost; there are no retries, scheduling or visibility; and CPU-heavy tasks steal capacity from requests. They're fine for sending a notification email or writing an audit log.

Code Example

from fastapi import BackgroundTasks

def send_welcome_email(email: str) -> None:
    mailer.send(email, "Welcome!")

@app.post("/signup", status_code=201)
async def signup(data: SignUp, tasks: BackgroundTasks):
    user = await create_user(data)
    tasks.add_task(send_welcome_email, user.email)
    return {"id": user.id}

Key Points

  • Runs after response, same process
  • No persistence or retries
  • Good for small fire-and-forget work
  • Use Celery/arq/RQ for durable jobs

More most-asked FastAPI questions

← All FastAPI questions