fastapi - 💡(How to fix) Fix Dependency keeps going after response returns when there exists any backgroud tasks. [1 participants]

Official PRs (…)
ON THIS PAGE

Recommended Tools

×6

Utilities matched from this issue’s tags and category — try them while you read without losing context.

GitHub issue graph ai analysis

Paste a GitHub issue URL. We fetch that issue, discover linked issues from bodies/comments/timeline, collect linked pull requests, and produce a structured English report.

The report is written in English Markdown for sharing and archival.

Helpful · Quick feedback

Loading…
GitHub stats
fastapi/fastapi#14988Fetched 2026-04-08 00:21:39
View on GitHub
Comments
0
Participants
1
Timeline
5
Reactions
0
Author
Participants
Timeline (top)
converted_to_discussion ×1locked ×1mentioned ×1subscribed ×1

Code Example

import asyncio

from fastapi import Depends, BackgroundTasks, FastAPI
from fastapi.responses import PlainTextResponse


app = FastAPI()

async def dep():
    yield
    print("dep done")

async def task():
    await asyncio.sleep(5)
    print("task done")

@app.get("/test", response_class=PlainTextResponse, tags=["test"], dependencies=[Depends(dep)])
async def test(bk: BackgroundTasks):
    bk.add_task(task)
    return "OK"
RAW_BUFFERClick to expand / collapse

Privileged issue

  • #14989

Issue Content

import asyncio

from fastapi import Depends, BackgroundTasks, FastAPI
from fastapi.responses import PlainTextResponse


app = FastAPI()

async def dep():
    yield
    print("dep done")

async def task():
    await asyncio.sleep(5)
    print("task done")

@app.get("/test", response_class=PlainTextResponse, tags=["test"], dependencies=[Depends(dep)])
async def test(bk: BackgroundTasks):
    bk.add_task(task)
    return "OK"

When access test endpoint, Both fastapi 0.128.0 and 0.133.0 have this behavior:

  1. Response returns
  2. print "dep done"
  3. print "task done".

But in fastapi 0.115.12:

  1. print "dep done"
  2. Response returns
  3. print "task done".

When the dependency is a database transaction, transaction is not committed after response returns, data changes are not accessable before backgroud tasks completion.

extent analysis

Quick Fix

**Make the dependency schedule its “after‑response” work (e.g

Vote matrix · Quick signals

Works
Did the solution work? Tap to confirm.
Easy Fix
Was it a quick fix?
Time Saver
Did it save you time?
Blocking
Was it severely blocking?
Common Issue
Are others likely hitting this too?
Flaky / Intermittent
Is it intermittent?
Verified / Reproducible
Can you reproduce it reliably?
Loading…

Still need to ship something?

×6

Another batch ranked right after the header list — different links, same matching logic.

Back to top recommendations

TRENDING