Skip to content
masterclassBuddyTech Buzz5 fresh blogs · 5:00 AM IST

FastAPI · Class

BackgroundTasks

BackgroundTasks collects callable work and runs it after FastAPI sends the response. FastAPI injects it into path operations or dependencies, and add_task() accepts a synchronous or asynchronous function with its arguments.

Since
0.10.0

How it works

BackgroundTasks is injected into a path operation or dependency and collects callable work for execution after the HTTP response has been sent. Register work with add_task(), which accepts a regular or asynchronous function plus the arguments it needs; FastAPI runs the task for you.

Syntax

BackgroundTasks(tasks=None)
add_task(func, *args, **kwargs)

Parameters

NameTypeDescription
taskslist[starlette.background.BackgroundTask] | NoneOptional initial collection of background tasks.

Returns

BackgroundTasks is a task collection; add_task() returns None.

Key points

  • Annotate a path operation or dependency parameter with BackgroundTasks to receive the task collector.
  • The instance stores work that executes after the response reaches the client.
  • Use add_task() to register one callable for later execution.
  • Registered work can be synchronous or asynchronous.
  • Positional arguments are forwarded to the task in the order supplied.
  • Keyword arguments can be forwarded by name when registering the task.

Common mistakes

  • Tasks may be synchronous or asynchronous; choose the form appropriate to the work.
  • FastAPI's class is backed by Starlette, so use FastAPI's plural class for automatic injection rather than confusing it with the singular Starlette class.

Example: Schedule a notification

from fastapi import BackgroundTasks, FastAPI

app = FastAPI()

def write_notification(email: str, message: str = ""):
    with open("log.txt", "a") as file:
        file.write(f"{email}: {message}\n")

@app.post("/send/{email}")
async def send_notification(email: str, background_tasks: BackgroundTasks):
    background_tasks.add_task(write_notification, email, message="queued")
    return {"message": "Notification sent"}

The endpoint registers a regular function with positional and keyword arguments; FastAPI runs it after sending the response.

When to use it

Deferred side effects

Record an event or write a notification after returning a response.

Post-response work

Send an email or perform another request-independent operation without delaying the client response.

Dependency-based task collection

Register tasks from shared dependency logic.

Interview questions

QHow do you schedule a background task?

Declare a parameter annotated as BackgroundTasks in a path operation or dependency. FastAPI creates and injects the object, and add_task() registers work that runs after the response is sent.

Follow-up: Can dependencies use it too? Yes: the type can be declared at multiple dependency levels, including sub-dependencies, and FastAPI coordinates the collected tasks.

QWhat arguments does add_task accept?

Call add_task(func, *args, **kwargs). The first argument is the callable, followed by positional and keyword arguments that FastAPI passes when it runs the task.

Follow-up: How would you pass a named option? Supply it as a keyword, such as add_task(write_notification, email, message="queued").

QWhen does the task execute, and what callable types are supported?

The task runs after the response is sent, so the client does not wait for that work before receiving the response. The callable can be either a normal def or an async def function.

Follow-up: When might this be insufficient? For heavier or distributed processing, use a separate task queue rather than relying on in-process background execution.

  • BackgroundTask
  • add_task
  • FastAPI dependency injection
  • path operation function

Source: Background Tasks - BackgroundTasks - FastAPI. Checked 2026-10-15.