tezvyn:

BackgroundTasks dependency vs response.background

AI-drafted, machine-checkedSource: interviewintermediate
WHAT IT TESTS

Two ways to defer work after a response.

OUTLINE

the injected BackgroundTasks parameter lets endpoints and dependencies stack tasks and is the common path; response.background attaches a single Starlette task when you return a Response object…

WHAT THIS TESTS Whether you understand FastAPI's two surfaces for running work after the response is returned, and that both run in the same process and event loop. It checks you know their ergonomic differences and shared limitations.

A GOOD ANSWER COVERS The BackgroundTasks dependency is injected by declaring a parameter typed BackgroundTasks. Any dependency in the chain or the endpoint itself can call background_tasks.add_task(fn, args). FastAPI collects all of them and executes them after sending the response. This composes well, since multiple dependencies can each contribute tasks. response.background is the underlying Starlette mechanism: when you build and return a Response (or StreamingResponse, FileResponse) yourself, you can set response.background = BackgroundTask(fn, args). It attaches to that specific response object. Functionally both run the callable after the body is sent, in the same worker, on the same loop for async callables. The parameter form is preferred for normal endpoints; the attribute form fits cases where you already construct the Response and have no BackgroundTasks parameter.

COMMON WRONG ANSWERS Claiming response.background runs in parallel with sending the response. Thinking either runs in a separate thread or process by default. Treating them as durable, when a crash or restart loses queued tasks.

LIKELY FOLLOW-UPS When do you outgrow both and reach for Celery or ARQ? Do async and sync task callables behave differently regarding the thread pool? What happens to tasks if the worker is killed mid-execution?

ONE CONCRETE EXAMPLE For a normal JSON endpoint that should send a welcome email after signup, inject BackgroundTasks and call add_task(send_email, user.email); it is clean and composable. But if an endpoint streams a generated CSV via StreamingResponse and must delete the temp file afterward, you set response.background = BackgroundTask(os.remove, path) on that StreamingResponse, since you already hold the Response object.

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.