How to Use Background Tasks in FastAPI for Async Work
In FastAPI, you can use
BackgroundTasks to run functions after returning a response, allowing non-blocking background work. Simply add a BackgroundTasks parameter to your path operation and use its add_task method to schedule a function to run in the background.Syntax
The BackgroundTasks class is imported from fastapi. You add it as a parameter to your endpoint function. Use background_tasks.add_task(your_function, arg1, arg2) to schedule a function to run after the response is sent.
This lets your API respond quickly while the background task runs separately.
python
from fastapi import FastAPI, BackgroundTasks app = FastAPI() def write_log(message: str): with open("log.txt", "a") as log_file: log_file.write(message + "\n") @app.post("/send-message/") async def send_message(message: str, background_tasks: BackgroundTasks): background_tasks.add_task(write_log, message) return {"message": "Message received"}
Example
This example shows a FastAPI app that accepts a message and writes it to a file in the background. The API immediately returns a confirmation response without waiting for the file write to finish.
python
from fastapi import FastAPI, BackgroundTasks app = FastAPI() def write_log(message: str): with open("log.txt", "a") as log_file: log_file.write(message + "\n") @app.post("/send-message/") async def send_message(message: str, background_tasks: BackgroundTasks): background_tasks.add_task(write_log, message) return {"message": "Message received"}
Output
{"message": "Message received"}
Common Pitfalls
- Not adding
BackgroundTasksas a parameter: Without it, you cannot schedule background tasks. - Calling the background function directly: This blocks the response until the task finishes, defeating the purpose.
- Using async functions incorrectly: Background tasks should be regular functions, not async, because FastAPI runs them in a thread pool.
python
from fastapi import FastAPI app = FastAPI() def write_log(message: str): with open("log.txt", "a") as log_file: log_file.write(message + "\n") @app.post("/wrong-way/") async def wrong_way(message: str): write_log(message) # This blocks the response return {"message": "Message received"} # Correct way: from fastapi import BackgroundTasks @app.post("/right-way/") async def right_way(message: str, background_tasks: BackgroundTasks): background_tasks.add_task(write_log, message) return {"message": "Message received"}
Quick Reference
Use this quick guide to remember how to use background tasks in FastAPI:
| Step | Description | Code Example |
|---|---|---|
| 1 | Import BackgroundTasks | from fastapi import BackgroundTasks |
| 2 | Add BackgroundTasks parameter | async def endpoint(background_tasks: BackgroundTasks): |
| 3 | Define background function | def task_func(args): ... |
| 4 | Schedule task | background_tasks.add_task(task_func, args) |
| 5 | Return response immediately | return {"status": "ok"} |
Key Takeaways
Add BackgroundTasks as a parameter to your endpoint to enable background work.
Use background_tasks.add_task() to schedule functions that run after response is sent.
Background task functions should be regular (non-async) functions.
Avoid calling background functions directly inside endpoints to prevent blocking.
Background tasks help keep your API responsive by offloading slow work.