A FastAPI endpoint queues a welcome email with background_tasks.add_task, then returns JSONResponse(..., background=BackgroundTask(write_audit_line)); why is the email never sent?
answer
- who owns the response's background slot
- a returned Response is used as is
- attached only when background is None
- no warning, no error
basics
~10 sFastAPI attaches the injected BackgroundTasks to a returned Response only when that response's background is None. Passing your own BackgroundTask fills the slot, so the queued email is silently discarded.
solid answer
~30 sWhen a path operation returns a `Response` instance, FastAPI uses it as is and makes one adjustment: if the response's `background` attribute is `None`, it sets it to the request's injected `BackgroundTasks`. A response built with `background=BackgroundTask(write_audit_line, email)` already has a background, so FastAPI leaves it alone and the list holding the welcome email is never run. Nothing is logged and nothing fails. The fix is to keep one list: queue the audit line with `background_tasks.add_task` too and leave the response's `background` unset, or pass `background=background_tasks` so the injected list is the one the response carries.
code
python · 30 linesfrom fastapi import BackgroundTasks, FastAPI
from fastapi.responses import JSONResponse
from starlette.background import BackgroundTask
app = FastAPI()
def send_welcome_email(email: str) -> None:
print(f"welcome -> {email}")
def write_audit_line(email: str) -> None:
print(f"audit -> {email}")
@app.post("/signup-broken")
async def signup_broken(email: str, background_tasks: BackgroundTasks):
background_tasks.add_task(send_welcome_email, email) # silently dropped
return JSONResponse(
{"email": email},
status_code=201,
background=BackgroundTask(write_audit_line, email),
)
@app.post("/signup-fixed")
async def signup_fixed(email: str, background_tasks: BackgroundTasks):
background_tasks.add_task(send_welcome_email, email)
background_tasks.add_task(write_audit_line, email)
return JSONResponse({"email": email}, status_code=201) # background left as Nonego deeper
Remember that a response you build yourself can carry its own background, and that this can stop tasks queued with add_task from running.
Explain the single background slot and the rule FastAPI applies: attach the injected list only when the returned response's background is None.
Diagnose the silent loss from the symptoms, notice that dependencies' tasks vanish too, and fix it with one list rather than a second mechanism.
Set a codebase rule for post-response work, one queuing path through BackgroundTasks, and back it with tests that assert every side effect.
## The symptom A sign-up endpoint needs a custom response, say a `JSONResponse` with an extra header or a specific status code. Somebody also wants an audit line written after the response, and attaches it the way Starlette's documentation shows, through the response's `background` argument. The welcome email, queued earlier in the same endpoint with `background_tasks.add_task`, stops arriving. There is no exception, no warning and no log line: the audit line is written, the email is not. ## Two ways to attach post-response work Starlette's `Response` has a single **`background`** slot. Whatever object sits there is awaited after the body has been sent. FastAPI fills that slot from two possible sources: - **the injected `BackgroundTasks`**, a list FastAPI creates per request and passes to every parameter of that type; - **an object you attach yourself**, either a single `starlette.background.BackgroundTask` or a `BackgroundTasks` list, passed as `background=` to a response you construct. FastAPI's request handler treats the two cases differently: 1. If the endpoint returns ordinary data (a dict, a model), FastAPI builds the response itself and passes the injected `BackgroundTasks` as its background. 2. If the endpoint returns a `Response` instance, FastAPI uses that object **as is** and only checks its `background` attribute. 3. If that attribute is `None`, FastAPI sets it to the injected `BackgroundTasks`. 4. If it is anything else, FastAPI keeps it, and the injected list is dropped. There is one slot and no merging. The source reads, in effect, `if raw_response.background is None: raw_response.background = solved_result.background_tasks`. ## Reproducing it ```python from fastapi import BackgroundTasks, FastAPI from fastapi.responses import JSONResponse from starlette.background import BackgroundTask app = FastAPI() def send_welcome_email(email: str) -> None: ... def write_audit_line(email: str) -> None: ... @app.post("/signup-broken") async def signup_broken(email: str, background_tasks: BackgroundTasks): background_tasks.add_task(send_welcome_email, email) # silently dropped return JSONResponse( {"email": email}, status_code=201, background=BackgroundTask(write_audit_line, email), ) ``` A test with `fastapi.testclient.TestClient` shows only the audit line being written, because only the response's own task runs. ## Fixes | Change | Effect | |---|---| | Queue both with `background_tasks.add_task` and omit `background=` | FastAPI attaches the injected list; both run, in order | | Pass `background=background_tasks` to the response | the response carries the injected list, including anything dependencies added | | Return data instead of a `Response` | FastAPI builds the response and attaches the list itself | The second form works because FastAPI's `BackgroundTasks` is a subclass of Starlette's `BackgroundTask`, so the whole list fits in the slot. The first is the clearest convention: one way of queuing work per codebase. ## Why it is easy to miss - **Dependencies queue work too.** An audit or metrics dependency may call `add_task` on the same object; returning a response with its own `background` drops their tasks as well, far from where they were written. - **The two classes differ by one letter.** `BackgroundTasks` from `fastapi` is injected; `BackgroundTask` from `starlette.background` is not, and both are legitimate in their place. - **Nothing fails loudly.** The injected object still accepts `add_task` calls; it simply never gets awaited. - **Returning a `Response` already bypasses other FastAPI steps**, such as filtering through `response_model`, so reviewers tend to look at the body and headers, not at the background slot. ## Finding it in an existing codebase When a post-response side effect goes missing, check in this order: 1. Search the path operations for responses built with a `background=` argument. 2. For each, list every place that calls `add_task` for that route: the endpoint, its dependencies, router-level and app-level dependencies. 3. Confirm in a `TestClient` test which side effects happen; the call returns only after the tasks that did run have finished. 4. Remove the second mechanism rather than patching the one route, since the same pattern tends to be copied. ## A review rule that prevents it Ban the `background=` argument on responses in path operations, or allow it only as `background=background_tasks`. Any extra post-response work goes through the injected object, so dependencies, the endpoint and the returned response all agree on a single list. A test that asserts every expected side effect after a `TestClient` call catches a regression immediately, since `TestClient` returns only after the tasks have run.
- Does the same rule apply to a StreamingResponse returned from a FastAPI endpoint?Yes. Any `Response` instance the endpoint returns goes through the same check: FastAPI attaches the injected `BackgroundTasks` only if `background` is `None`, and the tasks run after the last chunk has been sent.
- Can you set background tasks through FastAPI's injected Response parameter instead?No. The `Response` parameter FastAPI injects is a temporary object whose headers, cookies and status code are copied onto the real response; its `background` attribute is not used. Queue the work on `BackgroundTasks` instead.
- FastAPI merges the response's own background task with the injected BackgroundTasks
- Returning a Response makes FastAPI raise an error if tasks were queued
- The injected tasks run first, then the response's own background task
- Setting status_code=202 makes FastAPI run both sets of tasks