Background Tasks
Relevant source files
The following files were used as context for generating this wiki page:
Background tasks in Starlette provide a mechanism to schedule functions to run after a response has been sent to the client. This allows the application to perform "fire-and-forget" operations, such as sending emails, processing data, or cleaning up resources, without increasing the latency of the HTTP response.
These tasks are in-process and lightweight, managed directly by the response object or application logic. They are compatible with both synchronous and asynchronous functions and are executed once the ASGI connection has finalized the response delivery.
Sources: README.md:20, starlette/responses.py:104-105
Core Components
The background task system is built around two primary classes located in starlette/background.py.
BackgroundTask
A single task object that encapsulates a callable and the arguments/keyword arguments it requires. When awaited or called, it executes the underlying function. It automatically handles both async and sync functions, ensuring that synchronous functions are run in a threadpool to avoid blocking the event loop.
BackgroundTasks
A collection class that allows multiple BackgroundTask instances to be grouped together. It provides an add_task method to append new tasks to the sequence. When the BackgroundTasks object is executed, it runs each task sequentially. If a task in the sequence fails, subsequent tasks are not executed.
Sources: starlette/background.py:1-45, tests/test_background.py:65-88
| Component | Description |
|---|---|
BackgroundTask | Represents a single function to be executed after the response. |
BackgroundTasks | A container for multiple tasks to be executed sequentially. |
Response.background | An attribute on the base Response class that holds the task(s) to be run. |
Lifecycle and Execution Flow
Background tasks are typically attached to a Response object. The execution occurs within the __call__ method of the response class, specifically after the response body has been sent to the ASGI server.
As shown in the diagram, the task execution happens only after the http.response.body message is sent. This ensures the client receives the data as quickly as possible.
Sources: starlette/responses.py:100-105, starlette/responses.py:255-257
Integration with Responses
Every response type in Starlette (including JSONResponse, StreamingResponse, and FileResponse) inherits from the base Response class and supports the background parameter.
Standard Response Integration
In a standard Response, the task is executed at the very end of the __call__ method.
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
# ... send response start and body ...
if self.background is not None:
await self.background()
Sources: starlette/responses.py:100-105
Streaming and File Responses
For StreamingResponse and FileResponse, the task is similarly triggered after the stream or file chunks have been completely transmitted. In the case of StreamingResponse, if the client disconnects, Starlette still attempts to run the background task unless the execution group is cancelled.
Sources: starlette/responses.py:195-212, starlette/responses.py:255-257
Error Handling and Disconnects
The behavior of background tasks during exceptions or client disconnects is a critical architectural consideration:
- Task Failure: If a task within a
BackgroundTasksgroup raises an exception, the execution of that group stops immediately. Subsequent tasks in that specific group will not run. - Middleware Propagation: The
BaseHTTPMiddlewareis designed to ensure that background tasks are executed even if the client disconnects before the response is fully read. - Server Errors: If an exception occurs in the main endpoint,
ServerErrorMiddlewarecan still allow background tasks to run if they were successfully attached to an error response.
Usage Examples
Multiple Tasks
The BackgroundTasks class is used when multiple operations need to be performed.
from starlette.background import BackgroundTasks
from starlette.responses import Response
async def signup(request):
tasks = BackgroundTasks()
tasks.add_task(send_welcome_email, email="user@example.com")
tasks.add_task(update_external_crm, user_id=123)
return Response("Signed up", background=tasks)
Sources: tests/test_background.py:53-63
Middleware and Context Managers
Background tasks are integrated into the middleware stack to ensure consistency. For instance, BaseHTTPMiddleware ensures background tasks attached to a response are executed even if the underlying call_next logic encounters specific disconnect scenarios.
Sources: tests/middleware/test_base.py:186-218
Summary
Background tasks provide an efficient way to handle non-blocking side effects within a Starlette application. By offloading logic to occur after the response delivery, Starlette maintains high performance and low latency for the end user. The system is robust, handling both sync and async tasks, and is tightly integrated into the standard Response lifecycle and middleware processing.