tezvyn:

FastAPI Background Tasks: Don't Make the Client Wait

AI-drafted, machine-checkedSource: fastapi.tiangolo.combeginner

FastAPI background tasks let you run slow operations, like sending an email, *after* returning a response. This keeps your API fast. The main footgun: these are fire-and-forget; a server crash means the task is lost without a real message queue.

WHY IT EXISTS: APIs need to be fast. Some operations, like sending an email or processing a video, are inherently slow. Making a user wait for these to complete before getting a response leads to a poor user experience and potential timeouts. Background tasks solve this by decoupling the slow work from the client's request-response cycle.

THE MENTAL MODEL: Think of it like ordering a custom piece of furniture. You pay at the counter and get a receipt immediately (the HTTP response). You don't stand there for weeks while they build it. The store builds it "in the background" and will notify you later. The API response is the receipt, and the background task is the workshop building your furniture.

HOW IT WORKS: FastAPI uses its dependency injection system. You declare a parameter in your path operation function of type BackgroundTasks. FastAPI provides an instance of this object. You then call the .add_task() method on this instance, passing the function you want to run and its arguments. FastAPI sends the response to the client first, and only then does it execute the tasks you added.

WHEN TO USE IT: Use background tasks for operations that the client doesn't need to see the result of immediately. Three common cases: first, sending notifications like emails or push notifications; second, performing slow data processing on an uploaded file; third, calling a webhook or another service where you only care about triggering it, not its response.

WHEN NOT TO USE IT: Do not use background tasks for critical, must-not-fail operations or very long-running jobs. They run within the same process as your web server. If your server crashes or restarts, the task is lost. For durable, reliable background jobs, you need a dedicated message queue and worker system like Celery with Redis or RabbitMQ.

ONE CANONICAL EXAMPLE: A user signs up. Your endpoint saves the user to the database and immediately returns a "201 Created" response. As a background task, you then send a welcome email. The user gets an instant confirmation from the API, and the email arrives a few seconds later. This prevents a slow email server from delaying the user's sign-up confirmation screen.

Read the original → fastapi.tiangolo.com

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.