Factory.ai

Open-Source Wikis

/

FastAPI

/

Features

/

Background tasks

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:

  1. Endpoint returns; serialize_response produces a Response.
  2. The response's background attribute is set to the merged BackgroundTasks instance.
  3. The response is sent to the client.
  4. Starlette runs background() — calling each task in registration order.
  5. 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 StarletteBackgroundTasks is 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 routingserialize_response returns a Starlette Response whose background attribute is the merged tasks.

Entry points for modification

  • Per-route default tasks: not supported directly; subclass BackgroundTasks and inject your own via a dependency.
  • Changing dispatch: this is Starlette territory. The add_task override in fastapi/background.py only adds an Annotated[..., 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.

Background tasks – FastAPI wiki | Factory