Choosing FastAPI Background Work: BackgroundTasks vs create_task vs Queues
Decide when to use FastAPI BackgroundTasks, asyncio.create_task, or an external task queue for post-response work.
17 Jun 2026, 13:48 UTC

Decision: run work after the response without blocking the client
Your API route needs to send an email, write an audit log, or call a slow external service, but the client should not wait for that work. FastAPI offers three common approaches: BackgroundTasks, asyncio.create_task, and an external queue such as Celery, RQ, or Huey. This guide helps you pick one and implement it safely.
Useful takeaway: use BackgroundTasks for short, request-scoped work that can run after the response is sent and does not need retries. Use an external queue for durable, retried, or multi-worker jobs. Avoid unmanaged asyncio.create_task for user-facing side effects.
Constraints and supported options
BackgroundTasks is a Starlette dependency injected into a route parameter. FastAPI runs the registered callbacks after the response is sent, in the same process and event loop. If the worker process crashes before a callback finishes, the work is lost. There are no built-in retries.
asyncio.create_task schedules a coroutine immediately. It is fire-and-forget by default. Unless you keep a reference to the task object and handle cancellation, the task can be dropped when the request ends or raise exceptions after the request context tears down.
External queues run workers outside the FastAPI process. They require a message broker such as Redis or RabbitMQ and separate worker processes. Jobs survive process restarts and can be retried, but they add operational complexity and serialization requirements.
Option comparison
| Option | Durable? | Retries? | Runs after response? | Ops complexity | Best for |
|---|---|---|---|---|---|
BackgroundTasks | No | No | Yes | None | Email, logs, lightweight notifications tied to one request |
asyncio.create_task | No | No | Not guaranteed | None | Internal fire-and-forget work you can track and cancel manually |
| External queue (Celery, RQ, Huey) | Yes, with broker | Yes | Independent of response | High | Long-running jobs, retries, multi-worker distribution |
Trade-offs
BackgroundTasks adds almost no latency to the request path because only the task registration happens before the response. Errors inside a callback do not change the HTTP status code; the client receives a success response even if the background work fails. You must log errors inside the callback itself.
Because callbacks run in the same process, a long-running synchronous callback can consume a threadpool worker, and a long-running async callback can block the event loop. Do not use BackgroundTasks for work that takes minutes or that must survive a deploy.
An external queue decouples request throughput from job execution, but every argument must be serializable, and you must operate workers, monitor broker health, and handle poison messages.
Implementation: register a callback with BackgroundTasks
This pattern is stable in current FastAPI and Starlette releases. Check Starlette release notes when upgrading, because response handling behavior can change between versions.
Create app/main.py:
from fastapi import FastAPI, BackgroundTasks
import logging
import time
logger = logging.getLogger("app")
app = FastAPI()
def write_audit_log(user_id: int, action: str) -> None:
"""Runs after the response is sent. Keep this fast and idempotent."""
logger.info("audit user_id=%s action=%s at=%s", user_id, action, time.isoformat(time.time()))
@app.post("/items/{item_id}")
async def create_item(item_id: int, background_tasks: BackgroundTasks):
background_tasks.add_task(write_audit_log, user_id=item_id, action="create_item")
return {"item_id": item_id, "status": "accepted"}
Run the server from the project directory:
uvicorn app.main:app --reload
No special permissions are required. Replace app.main:app with your actual module path. The placeholder write_audit_log represents your side effect; do not use it for durable financial transactions without a retry layer.
Why the callback runs after the response
Starlette's BackgroundTasks object is attached to the response. The server sends the response to the client, then iterates through the callbacks. The route handler returns immediately after add_task is called; the client does not wait for write_audit_log.
Validation: confirm order of execution
You cannot observe background success through the HTTP status code because the response is sent first. Validate locally with timestamps instead.
- Write a timestamp to the application log immediately after the route returns.
- Write a timestamp inside the callback after a short sleep.
- Call the endpoint and inspect server logs. The callback timestamp should be later than the post-return timestamp.
Unit test the callback function directly. Use TestClient to assert the response status and body, then assert the side effect occurred after the request completed. Do not assert timing in a flaky way; assert that the side effect happened, not exactly when.
Limitations and how to check the result
- If the process is killed immediately after the response, in-flight callbacks may abort. Check by stopping the server right after a request and confirming whether the log appeared.
- Background task arguments are passed in-process. They do not survive worker restarts. Check durability by restarting the worker mid-task and observing whether the job completes.
- Exceptions in callbacks do not fail the HTTP response. Check application logs for errors; do not rely on the client seeing a 500.
- Do not return the
BackgroundTasksobject or await task results inside the route. Clients cannot observe task success or failure through HTTP.
When to move to an external queue
If you need retries, job persistence across deploys, or distribution across multiple worker machines, prototype with Redis and RQ or Celery. Compare restart behavior and task persistence against BackgroundTasks before committing to the operational overhead.
Decision summary
- Short, request-tied work after response:
BackgroundTasks. - Trackable fire-and-forget within one process:
asyncio.create_taskwith a stored task reference and disconnect handling. - Durable, retried, multi-worker: external queue.