fastapi/fastapi
Background tasks
fastapi/background.py exposes BackgroundTasks, a thin subclass of starlette.background.BackgroundTasks. The class collects callables that run after the response has been sent to the client.
Public API
from fastapi import BackgroundTasks, FastAPI
app = FastAPI()
def write_log(message: str):
with open("log.txt", "a") as f:
f.write(message + "\n")
@app.post("/notify")
async def notify(background_tasks: BackgroundTasks):
background_tasks.add_task(write_log, "request received")
return {"ok": True}add_task(func, *args, **kwargs) queues a callable. Both regular def and async def functions are supported. The base class handles dispatch — sync functions run in a threadpool.
How it gets injected
BackgroundTasks is one of the framework's special parameters. During dependant building (fastapi/dependencies/utils.py:get_dependant) the resolver detects a BackgroundTasks annotation and stores the parameter name on Dependant.background_tasks_param_name. At request time, the resolver creates a BackgroundTasks instance and feeds it into the kwargs.
The resolver also walks sub-dependencies and collects any BackgroundTasks produced inside dependencies (for example, a logging dependency that wants to enqueue work). They are merged into the response via Starlette's Response.background = BackgroundTasks(...) mechanism.
When tasks run
Tasks run after the response is constructed but before the per-request AsyncExitStacks close (see Request lifecycle). Concretely:
- Endpoint returns;
serialize_responseproduces aResponse. - The response's
backgroundattribute is set to the mergedBackgroundTasksinstance. - The response is sent to the client.
- Starlette runs
background()— calling each task in registration order. - The framework closes the function and inner exit stacks (running
yield-style dependency cleanup).
If a background task raises, Starlette logs it; the response has already been sent, so there is nothing to surface to the client.
Beyond BackgroundTasks
BackgroundTasks is appropriate for short, in-process tasks. For anything longer, use a real task queue (Celery, RQ, Arq, Dramatiq, …). The framework deliberately does not ship one — the docs encourage existing solutions and the BackgroundTasks API exists for the trivial case.
Integration points
- Down to Starlette —
BackgroundTasksis a one-method override of Starlette's class. The dispatch logic is Starlette's. - Across to dependency resolver — the special-parameter detection is in
fastapi/dependencies/utils.py. Tasks added inside dependencies are merged with tasks added inside the endpoint. - Across to routing —
serialize_responsereturns a StarletteResponsewhosebackgroundattribute is the merged tasks.
Entry points for modification
- Per-route default tasks: not supported directly; subclass
BackgroundTasksand inject your own via a dependency. - Changing dispatch: this is Starlette territory. The
add_taskoverride infastapi/background.pyonly adds anAnnotated[..., Doc(...)]description for the API reference page — there is no extra logic.
Built by Factory AutoWiki from public repository content. It is a generated preview for codebase exploration, not source-maintained documentation.
Previous
Server-Sent Events
Next
WebSockets