How would you use BackgroundTasks to run work after returning a 201?
What it tests: FastAPI deferred execution and failure modes. A strong answer injects BackgroundTasks, adds the task, returns 201, and notes same-process post-response execution with no persistence. Red flag: Treating it as a distributed queue like Celery.
WHAT THIS TESTS: This question probes whether you understand the boundary between synchronous request handling and deferred background work in FastAPI. Interviewers want to see that you know BackgroundTasks is a convenience mechanism built on Starlette, not a distributed job system, and that you can articulate when it is appropriate versus when a real message broker is required.
A GOOD ANSWER COVERS: First, dependency injection: you receive the BackgroundTasks object via the path operation function parameter or a dependency. Second, task registration: you call tasks.add_task(send_welcome_email, email_address, username) before returning the response, passing the function and its arguments without invoking it directly. Third, lifecycle: FastAPI returns the 201 response to the client immediately, and Starlette executes the registered tasks on the event loop after the response is sent but while the connection context still exists. Fourth, limitations: tasks run in the same process and thread as the server worker, so if the process crashes or is restarted the task is lost; there is no retry logic, no persistence, and CPU-bound tasks will block the worker and reduce throughput.
COMMON WRONG ANSWERS: A major red flag is describing BackgroundTasks as a queue like Celery or RQ. Another is suggesting you can safely perform heavy computation or long-running jobs without impacting request handling. Some candidates also mistakenly think the task runs in a separate thread or process by default, or that returning the response waits for the background task to finish. Failing to mention that tasks are lost on server restart is another weakness.
LIKELY FOLLOW-UPS: Expect the interviewer to ask what happens if the background task raises an exception, how you would handle retries, or how this interacts with yield dependencies that perform cleanup. They may also ask how to monitor background tasks or when you would migrate to a proper task queue.
ONE CONCRETE EXAMPLE: Imagine a signup endpoint that creates a user record in the database. You inject BackgroundTasks, call tasks.add_task(send_welcome_email, user_email), then return a 201 Created. The client sees success instantly. The email function then connects to an SMTP server and sends the message. If the container restarts immediately after the 201 due to a deployment, the email is never sent because the task existed only in that process memory.
Read the original → fastapi.tiangolo.com
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.