I’m running into strange behavior in FastAPI where my BackgroundTasks only execute when declared inside an async dependency. No exception is raised, the route returns normally, but the background job never runs.
from fastapi import FastAPI, BackgroundTasks, Depends
app = FastAPI()
async def log_something():
print("Background task executed!")
async def dependency(bg: BackgroundTasks):
print("Dependency started")
bg.add_task(log_something)
print("Dependency added task")
return {"ok": True}
@app.get("/test")
async def test_route(data=Depends(dependency)):
print("Route executed")
return {"status": "done"}
When I call:
curl http://127.0.0.1:8000/test
I expect to see this printed in the console:
Dependency started
Dependency added task
Route executed
Background task executed!
What I get:
Dependency started
Dependency added task
Route executed
No errors are logged, and FastAPI returns {"status": "done"} correctly.
If I move the bg.add_task() call into the route itself, it works as expected.
FastAPI 0.115.2
Python 3.13
macOS (Apple Silicon)
1 Answer 1
BackgroundTasks only runs for tasks that are attached to the response object created by FastAPI during route execution. When you move the bg.add_task(), the bg instance is the same one attached to the response lifecycle, so FastAPI executes the background tasks after returning the response.
Pass BackgroundTasks from the route into your dependency.
async def dependency(bg: BackgroundTasks):
print("Dependency started")
bg.add_task(log_something)
print("Dependency added task")
return {"ok": True}
@app.get("/test")
async def test_route(bg: BackgroundTasks, data=Depends(dependency)):
print("Route executed")
return {"status": "done"}
return {"ok": True}doesn't include the BackgroundTasks. You need to attach the BackgroundTasks object to the response from your dependency. FastAPI doesn’t attach that task to the response, because the dependency runs before the route creates the response. That’s why yourlog_something()never executes, nothing is actually scheduling it after the response is returned. When you callbg.add_task()inside the route itself: FastAPI can attach it to the response being returned. Once the response is sent, FastAPI executes the background task correctly.