In FastAPI 0.143, can a background task use a database session yielded by a dependency, and what decides whether it is still open?
answer
- when the code after yield runs
- the scope argument of Depends
- request vs function
- the docs still say: pass an ID
basics
~10 sYes with the default Depends(scope="request"): FastAPI 0.143 runs that teardown after the response and its background tasks. With scope="function" the session is closed before the response, so the task gets a closed one.
solid answer
~40 sIt depends on the yield dependency's `scope`. In FastAPI 0.143 a yield dependency defaults to `Depends(scope="request")`, whose code after `yield` runs once the response and the request's background tasks have finished, so a task that receives the session can still use it. Declared with `scope="function"`, the teardown runs right after the path operation returns, before the response is sent, and the task gets a closed session. This has moved across releases: 0.106 closed sessions before tasks, 0.118 restored teardown after the response, and 0.121 added `scope`. Even where it works, the FastAPI docs advise passing the record's ID and opening a fresh session inside the task, so the request's connection is not held for the task's whole duration.
code
python · 48 linesfrom typing import Annotated
from fastapi import BackgroundTasks, Depends, FastAPI
app = FastAPI()
class AuditStore:
"""Stands in for a database session or connection."""
def __init__(self) -> None:
self.closed = False
def write(self, line: str) -> None:
print(f"write {line!r}, store closed={self.closed}")
def get_store():
store = AuditStore()
try:
yield store
finally:
store.closed = True
print("store closed")
def write_audit(store: AuditStore, line: str) -> None:
store.write(line)
@app.post("/signup-request-scope")
def signup_request_scope(
email: str,
background_tasks: BackgroundTasks,
store: Annotated[AuditStore, Depends(get_store)], # scope="request" by default
):
background_tasks.add_task(write_audit, store, f"signup {email}")
return {"email": email}
@app.post("/signup-function-scope")
def signup_function_scope(
email: str,
background_tasks: BackgroundTasks,
store: Annotated[AuditStore, Depends(get_store, scope="function")],
):
background_tasks.add_task(write_audit, store, f"signup {email}")
return {"email": email}go deeper
Remember that a yield dependency has setup before yield and cleanup after it, and that the cleanup timing decides whether a background task can still use what it yielded.
Lay out the timeline: function-scope teardown, response, background tasks, request-scope teardown, and say which scope FastAPI uses by default.
Explain why borrowing the session is still a bad habit: pooled connections held for the task's duration, coupled error handling, and breakage when someone switches to scope="function".
Set the convention that background tasks receive IDs and open their own resources, so session scope can be tuned for pool pressure without breaking post-response work.
## The question behind the question A sign-up endpoint gets a database session from a **yield dependency**: the code before `yield` opens it, the code after `yield` closes it. The endpoint wants a background task to write an audit row after the response. Passing the endpoint's session to the task is the obvious move, and whether it works depends on **when the dependency's teardown runs relative to the background tasks**. ## The timeline in FastAPI 0.143 FastAPI keeps two exit stacks per request. Yield dependencies are entered on one of them according to their **`scope`**, an argument of `Depends` added in 0.121: 1. The path operation function runs. 2. Dependencies declared `Depends(..., scope="function")` are torn down: their code after `yield` runs now. 3. The response's status, headers and body are sent. 4. The request's background tasks run, one after another. 5. Dependencies with `scope="request"` are torn down. **This is the default** for a yield dependency. So with the default scope the session is still open while the tasks run, and with `scope="function"` it is already closed. | Dependency declared as | Teardown runs | Session state inside the task | |---|---|---| | `Depends(get_session)` (default `"request"`) | after the tasks finish | still open | | `Depends(get_session, scope="function")` | before the response is sent | already closed | A dependency with the default request scope also sees a background task's exception at its `yield`, because it is still open when the task fails. ## How it got here Older material disagrees with this, because the behaviour moved: - **Before 0.106**, teardown ran after the response and after the tasks; the design explicitly let tasks reuse yielded objects. - **0.106** moved teardown to before the response, to stop holding resources while the response travelled; tasks then received closed sessions, and the docs told people to open their own. - **0.118** reverted that, running teardown after the response again, mainly so a `StreamingResponse` could keep using the session. - **0.121** added `scope="function"` as the opt-in for early teardown. An answer written against 0.106 to 0.117 ("the session is always closed in a background task") is wrong for 0.143 with the default scope, and right only for `scope="function"`. ## Why the docs still say: open your own Working is not the same as advisable. FastAPI's documentation still recommends that a background task **create its own resources**: pass the ID of the record, open a new session inside the task, and load the object again. The reasons are practical: - **Connection hold time.** With the default scope, the request's session and its pooled connection stay checked out until every task finishes. A ten-second email task holds a database connection for ten seconds it does not need. - **Coupled failure.** The task's exception arrives at the dependency's `yield`, so a session dependency that rolls back or logs on error now reacts to the task's failures as if they were the request's. - **Hidden coupling to a default.** Someone later adds `scope="function"` to release connections early, for good reasons, and every task that borrowed the session breaks. - **Stale objects.** Objects loaded through the request's session belong to that session and its transaction; a fresh session in the task loads what has actually been committed. ## A safe pattern The task receives plain data and opens its own resource. Here `AuditStore` stands in for a database session: ```python from contextlib import contextmanager from typing import Annotated from fastapi import BackgroundTasks, Depends, FastAPI app = FastAPI() class AuditStore: def write(self, line: str) -> None: ... def close(self) -> None: ... def get_store(): store = AuditStore() try: yield store finally: store.close() def write_audit(user_id: int) -> None: with contextmanager(get_store)() as store: # the task's own store store.write(f"signup {user_id}") @app.post("/signup", status_code=201) def signup( email: str, background_tasks: BackgroundTasks, store: Annotated[AuditStore, Depends(get_store, scope="function")], ): user_id = 42 # ... create the user through `store` ... background_tasks.add_task(write_audit, user_id) # pass the ID, not the store return {"id": user_id, "email": email} ``` The request's dependency is declared with `scope="function"` to release its resource before the response is sent, and the task does not care.
- Why would a FastAPI app declare its session dependency with scope="function"?To return the pooled connection before the response is sent. With the default request scope, the connection stays checked out while a slow or streamed response travels and while background tasks run; `scope="function"` releases it as soon as the path operation returns.
- What should a FastAPI background task receive instead of the request's session?Plain data: the record's ID and any values it needs. The task opens its own session, loads the record again and commits its own work, so it no longer depends on the request dependency's scope or lifetime.
- In FastAPI 0.143 a yielded session is always closed before background tasks run
- scope="function" keeps the dependency open until background tasks finish
- Reusing the request's session in a task costs nothing once the response is sent
- FastAPI opens a fresh session for each background task automatically
Assumes FastAPI 0.143; 0.106 tore yield dependencies down before the response, 0.118 moved teardown back to after the response and its tasks, and 0.121 added Depends(scope="function") for early teardown.