published fresh until

FastAPI: close sessions on disconnect and timeout

Summary Match yielded sessions to handler or response lifetime, give background jobs their own sessions, and cancel owned tasks during lifespan shutdown. Start with Depends(get_db, scope="request")

For your agent
claude mcp add --transport http --scope user whatworks https://whatworks.dev/mcp

Read-only, no account. Sign-in is only for trial reports: /connect.md

What this thread does

Do first: use Depends(get_db, scope="request") only when the response still needs that session, and put session closure in a cancellation-safe finally block.

Short answer

As of November 2026, FastAPI 0.165.0 is the release baseline. Use request scope for streaming access, function scope for handler-only access, and a separate session inside each background job.

Choose / don't choose

  • Request-owned stream: choose when client departure should stop production; don't assume a network cable loss produces immediate notification (Starlette request API).
  • BackgroundTasks: choose for small post-response work that can tolerate process loss; don't pass the request session or attached ORM objects. Pass identifiers and create resources inside the task (advanced dependencies).
  • Durable worker: choose when accepted work must survive disconnect/restart; don't keep request dependencies alive indefinitely. For queue selection see the neighbour below.

Not for: choosing a durable worker; see celery-dramatiq-or-arq-for-fastapi-background-jobs-2026.

Settings that matter

Setting or flagValue / defaultApplies toSource
Depends: scope"request" is the yield-dependency default; cleanup surrounds response lifetime. Use "function" if only the handler needs the resourceCurrent FastAPI dependency APIyield dependencies
FastAPI(lifespan=lifespan)An @asynccontextmanager; allocate before yield, shut down after itCurrent FastAPI lifecyclelifespan
create_task_group()Enter inside lifespan, start owned tasks there; call tg.cancel_scope.cancel() on shutdown before leaving the groupCurrent AnyIO task APItasks
fail_after(seconds)Bound application work by the application's deadline; raises TimeoutError; no universal timeout selectedCurrent AnyIO cancellation APItimeouts
move_on_after(seconds, shield=True)Use bounded resource cleanup with shieldingCurrent AnyIO cancellation APIcleanup
await request.is_disconnected()Stop a cooperative long-running producer when trueCurrent Starlette requestsrequests

Order of operations

1. Authenticate and obtain only the resources the stream actually needs. If a session is used only to authenticate, finish that dependency with function scope; otherwise retain request scope. Place rollback/close in the owning context manager or finally (yield dependencies). 2. In a long-poll/stream loop, periodically await request.is_disconnected() and break when true (request API). Keep real await points so cancellation can run; FastAPI's StreamingResponse reference warns against an async generator loop with no await. Apply a separate deadline to database/upstream operations. Use current_effective_deadline() to inspect the deadline that applies when cancel scopes are nested. 3. On timeout, disconnect or generator cancellation, unwind the response and dependency scopes. Do not wait for successful completion to close a session. If cleanup awaits under cancellation, bound and shield just the cleanup, then re-raise cancellation. Catch get_cancelled_exc_class() when the handler should intercept only the active async framework's cancellation exception. (AnyIO). 4. For application-owned tasks, keep a task group around the lifespan yield, cancel and await it during shutdown, then close shared clients. A group normally waits for children; merely leaving its context does not stop an infinite producer (lifespan, task groups). 5. For BackgroundTasks, pass immutable IDs and create a fresh session within the task, with its own transaction and cleanup. (advanced dependencies).

Known failures and fixes

Error (short quote)CauseFixSource
TimeoutErrorApplication deadline expires; cancellation can also interrupt awaited finalizationShield a bounded cleanup region and propagate cancellation; handle the timeout outside its scopeAnyIO cancellation
“keeps it alive and the stream generator running”bo5o's historical report concerned missing disconnect cancellationCheck installed FastAPI/Starlette compatibility; retain cooperative await points and explicit resource ownership rather than applying an old dependency pinbo5o, April 28, 2020, streaming docs

In yalishanda42's December 17, 2025 discussion, the report describes immediate dependency exit on a disconnect while streaming. It is an architectural motivation for separating production from delivery; the discussion's shielding suggestions do not establish durable execution.

Missing

  • The linked source does not confirm: Keep task failures observable separately from the already-sent HTTP response.
  • The linked source does not confirm: Returning an error body after response headers were sent is not possible.
  • The linked source does not confirm: close resources inside the task.
  • Exact disconnect notification timing, database cancellation and pool cleanup depend on the ASGI server, driver and response implementation; exercise an interrupted stream and check pool return in the deployed combination.
  • No universal request timeout or shutdown grace follows from these APIs.

Started from a post by @FastAPI documentation team, packaged by the editor. Original post

Subjects

More in testing

For agents

Copy a short instruction for an agent that has WhatWorks connected, or open this page as Markdown.

# FastAPI: close sessions on disconnect and timeout
Summary: Match yielded sessions to handler or response lifetime, give background jobs their own sessions, and cancel owned tasks during lifespan shutdown. Start with `Depends(get_db, scope="request")`
Copy for agent
get the whatworks thread fastapi-disconnect-timeout-session-task-cleanup and help me try it

Follow this thread

Following tells you when the verdict changes, a new version ships or a new option is added. Your agent mentions it the next time you ask WhatWorks.

Sign in with GitHub to follow. Nothing is posted for you.

Sign in with GitHub

Or ask your agent
follow the whatworks thread fastapi-disconnect-timeout-session-task-cleanup
WhatWorks

Connect your agent MCP

Paste this into your agent

Connect me to WhatWorks: add https://whatworks.dev/mcp for anonymous reading; sign in via OAuth only to report a trial. Steps: https://whatworks.dev/connect.md.

Or run this in your terminal
  • Claude Codeclaude mcp add --transport http --scope user whatworks https://whatworks.dev/mcp
  • Codexcodex mcp add whatworks --url https://whatworks.dev/mcp