Background tasks and async
Some work shouldn't make the user wait: sending emails, resizing images, generating PDFs, calling slow third-party APIs, nightly reports. And some work is mostly waiting (on networks and databases), which is where async code shines. This lesson covers both: running work after the response, concurrently, or in a separate worker process.
Why not do it in the request?
A signup that sends a welcome email synchronously takes as long as the email server does (often a second or more), and fails if the email server is down. Instead: save the user, respond immediately, and send the email in the background.
FastAPI BackgroundTasks
For small jobs, FastAPI can run a function after the response has been sent:
The tasks ran after "response ready", in order. Limits: they run in the same process, so they're lost if the server restarts, can't be retried, and long CPU-heavy tasks still slow the server down. For anything important, use a task queue.
Async: doing many waits at once
When code waits on I/O, async/await lets one thread make progress on other work meanwhile. Compare fetching three slow APIs one by one and concurrently:
In a FastAPI route, the same pattern with httpx.AsyncClient calls several services in parallel:
@app.get("/compare/{product_id}")
async def compare(product_id: int):
async with httpx.AsyncClient(timeout=2) as client:
responses = await asyncio.gather(*(client.get(f"{url}/prices/{product_id}") for url in SUPPLIERS),
return_exceptions=True)
return [r.json() for r in responses if not isinstance(r, Exception)]Django supports async views too (async def my_view(request)), plus async ORM methods (await Product.objects.aget(pk=1), async for p in Product.objects.filter(...)), when served by an ASGI server.
The golden rule
Inside async def, never call blocking code: time.sleep, requests.get, a synchronous database driver, or heavy CPU loops. They freeze the event loop and every other request with it. Use async libraries (httpx, asyncpg, aiofiles), or in FastAPI simply write a plain def route (FastAPI runs it in a thread pool), or use await asyncio.to_thread(blocking_function).
Task queues: durable background work
For reliable background processing, the web app puts a job on a queue (usually Redis or RabbitMQ), and separate worker processes take jobs off it:
web app ──enqueue("send_email", to=…)──▶ queue (Redis) ──▶ worker 1
└────▶ worker 2Jobs survive restarts, can be retried with backoff, scheduled for later, rate-limited and monitored, and workers can be scaled independently of the web servers.
Here's the core idea in plain Python: a queue, workers, and retries:
Real projects use a library rather than writing this themselves:
| Library | Notes |
|---|---|
| Celery | The most established; Redis or RabbitMQ; schedules (Celery beat), retries, chains of tasks |
| RQ (Redis Queue) | Simple, Redis-based |
| Dramatiq, Huey | Simpler alternatives to Celery |
| arq, Taskiq | Async-native, good with FastAPI |
| Django tasks | Django 6.0 added a built-in background tasks framework (@task, .enqueue()), with pluggable backends |
A Celery task looks like this:
# tasks.py
from celery import Celery
app = Celery("shop", broker="redis://localhost:6379/0")
@app.task(bind=True, max_retries=3, default_retry_delay=30)
def send_receipt(self, order_id):
try:
email_service.send_receipt(order_id)
except ConnectionError as exc:
raise self.retry(exc=exc)
# in a view: send_receipt.delay(order.id)
# run workers: celery -A tasks worker --loglevel=infoRules for background jobs
- Pass IDs, not objects: the worker loads fresh data from the database (
send_receipt.delay(order.id)). - Make jobs idempotent: a retried job must not send two emails or charge twice.
- Enqueue jobs after the database transaction commits (Django's
transaction.on_commit), or the worker may not find the new row yet. - Monitor queues (Flower for Celery) and alert when they back up.
Practice
- Add a third background task to the signup example that logs
"audit: signup". - Use
asyncio.gather(..., return_exceptions=True)with one supplier that raises an error, and print only the successful prices. - Change the worker example to use three workers and five retries, and count how many attempts were made in total.
1.When do FastAPI BackgroundTasks run?
2.Why is calling time.sleep(2) inside an async def route a problem?
3.Why should a background job receive an order ID rather than the order object?