When to Use Background Tasks
Use background tasks for operations like:- Sending email notifications
- Processing data that doesn’t affect the response
- Writing to log files
- Triggering webhooks
- Cleaning up resources
- Updating caches
For heavy background processing, consider using a dedicated task queue like Celery or RQ instead.
Basic Usage
AddBackgroundTasks as a parameter to your path operation function:
How It Works
1
Request Processing
Your path operation function receives the request and processes it normally.
2
Add Background Task
Use
background_tasks.add_task() to queue functions to run after the response.3
Response Sent
FastAPI sends the response to the client immediately.
4
Task Execution
After the response is sent, the background tasks run in order.
Adding Tasks
Use theadd_task() method to add a function and its arguments:
- First argument: the function to call
- Following arguments: positional arguments for the function
- Keyword arguments: keyword arguments for the function
Sync and Async Functions
Both regulardef and async def functions work:
Regular
def functions are executed in a thread pool, so they won’t block the async event loop. Use async def for I/O-bound operations that support async.Multiple Background Tasks
You can add multiple tasks - they run sequentially in the order they were added:Background Tasks in Dependencies
You can also add background tasks from dependencies:Background tasks from dependencies and path operations are combined. All tasks will run after the response is sent.
Technical Details
TheBackgroundTasks class comes from Starlette and is directly integrated into FastAPI.
Task Execution Context
- Tasks run after the response is sent to the client
- They execute within the same request context
- Dependencies with
yieldcomplete before background tasks start - Tasks run sequentially in the order they were added
Error Handling
Implement proper error handling within your background task functions:Use Cases
1
Email Notifications
2
Data Processing
3
Logging and Analytics
Limitations
When to Use a Task Queue
Consider using a dedicated task queue instead ofBackgroundTasks when you need:
- Task persistence and reliability
- Retry mechanisms with exponential backoff
- Task scheduling and delayed execution
- Distributed task processing across multiple workers
- Task monitoring and management UI
- Long-running or CPU-intensive tasks
- Task priorities and routing