BackgroundTasks schedules a function after sending the response. It suits small actions in the same process, such as a simple notification, when the client does not need to wait.
from fastapi import BackgroundTasks, FastAPI, status
app = FastAPI()
def enviar_confirmacao(pedido_id: int) -> None:
print(f"confirmar pedido {pedido_id}")
@app.post("/pedidos/{pedido_id}", status_code=status.HTTP_202_ACCEPTED)
async def criar_pedido(
pedido_id: int,
tarefas: BackgroundTasks,
) -> dict[str, int]:
tarefas.add_task(enviar_confirmacao, pedido_id)
return {"pedido_id": pedido_id}
The function may be synchronous or asynchronous and receives arguments through add_task(). HTTP 202 means accepted, not completed. Return an identifier and expose status when the later result is part of the contract.
Practical guidance
Do not treat BackgroundTasks as a durable queue. Restarts can lose work and replicas do not share in-memory state. Choose Celery or another persistent system for retries, schedules, heavy loads, or distributed execution. Make tasks idempotent and log failures without sensitive data.
See Python Celery for persistent queues and FastAPI dependency injection for service boundaries.
The official FastAPI BackgroundTasks documentation, accessed July 22, 2026, documents the API and its constraints.