Full answer
Comparison:
| BackgroundTasks | asyncio.create_task | Task queue | |
|---|---|---|---|
| Starts | after the response is sent | as soon as the loop is free | when a worker picks it up |
| Runs in | same process (sync functions in thread pool) | same event loop | separate worker processes or machines |
| Survives restart | no | no | yes (broker-persisted) |
| Retries | no | no | yes |
| Result tracking | no | manual | yes |
| Good for | small, fast, non-critical work | fire-and-forget I/O alongside a request | long, important, heavy or scheduled work |
Details and failure modes:
- BackgroundTasks run after the response is sent but the connection is still held by the worker; heavy tasks reduce capacity. An exception in a background task happens after the 200 was sent: the client never learns about it, and you only see it in logs (log explicitly).
- Sync background functions run in the thread pool;
async defones run on the event loop (CPU work there blocks everything). asyncio.create_task(coro())returns a Task that the event loop holds only weakly: store it in a set and remove it on completion, or it may be garbage-collected mid-run. Unhandled exceptions are logged at garbage collection time ("Task exception was never retrieved") unless you add a done-callback. Tasks are cancelled at shutdown.- On deploy or crash, in-process tasks vanish silently. Graceful shutdown may wait for them, but only if you track them.
- Queues add infrastructure, but give durability, retries with backoff, rate limiting, scheduling, priorities, visibility (dashboards) and separate scaling.
Rules of thumb: if losing the job would be a bug (sending a receipt, charging, syncing), use a queue and make the job idempotent. If losing it is acceptable (cache warm-up, analytics ping), BackgroundTasks is fine. Enqueue after the database commit (or use an outbox) so workers never see missing rows.
import asyncio
from fastapi import BackgroundTasks, FastAPI
app = FastAPI()
events = []
background_tasks_alive: set[asyncio.Task] = set()
def write_audit(roll_no):
events.append(f"audit written for {roll_no} (after response)")
def failing_job():
events.append("failing job started")
raise RuntimeError("mail server down")
async def warm_cache():
await asyncio.sleep(0)
events.append("cache warmed by create_task")
@app.post("/pay/{roll_no}")
async def pay(roll_no: str, tasks: BackgroundTasks):
tasks.add_task(write_audit, roll_no)
task = asyncio.create_task(warm_cache())
background_tasks_alive.add(task) # keep a reference until it finishes
task.add_done_callback(background_tasks_alive.discard)
events.append("endpoint returns")
return {"paid": roll_no}
@app.post("/fail")
async def fail(tasks: BackgroundTasks):
tasks.add_task(failing_job)
return {"queued": True}
async def call(path):
scope = {"type": "http", "asgi": {"version": "3.0"}, "http_version": "1.1", "method": "POST", "scheme": "http",
"path": path, "raw_path": path.encode(), "query_string": b"", "headers": [], "server": ("t", 80),
"client": ("127.0.0.1", 1), "root_path": ""}
async def receive():
return {"type": "http.request", "body": b"", "more_body": False}
async def send(message):
if message["type"] == "http.response.start":
events.append(f"response sent: {message['status']}")
try:
await app(scope, receive, send)
except RuntimeError as exc:
events.append(f"error after the response was sent: {exc}")
asyncio.run(call("/pay/BCA-1"))
print("\n".join(events))
events.clear()
asyncio.run(call("/fail"))
print("\n".join(events))
Standalone script. Run it with `python file.py`; it drives the ASGI app directly so the order of events is visible. Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0): endpoint returns response sent: 200 cache warmed by create_task audit written for BCA-1 (after response) response sent: 200 failing job started error after the response was sent: mail server down
Key points
- BackgroundTasks run after the response, in the same process
- create_task needs a held reference and error handling
- None of the in-process options survive restarts or retry
- Important or long jobs belong in a queue with idempotent tasks
- Exceptions in background tasks never reach the client
Common mistakes
- Using BackgroundTasks for work that must not be lost
- Starting create_task without keeping a reference or handling exceptions
- Running CPU-heavy work in async background functions and blocking the loop
- Queuing a job before the database commit
- Assuming the client sees background errors
Follow-ups
- How would you make a queued job idempotent?
- What happens to BackgroundTasks on graceful shutdown?
- How does the outbox pattern relate?
Tips
- Use the comparison table
- Name failure modes
- Give a decision rule