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
- How does dependency injection with `Depends` work in FastAPI?
- Walk through what happens to a request in FastAPI, from the ASGI server to the response.
- What is FastAPI and what makes it different from Flask or Django?
- How do `yield` dependencies work and why are they used for database sessions?
- How does FastAPI distinguish path, query and body parameters?
- How does FastAPI use Pydantic for request validation?
- What does `response_model` (or a return annotation) do in FastAPI?
- When should an endpoint be `async def` versus plain `def` in FastAPI?