Fire and Forget: Background Tasks
Fire and Forget: Background Tasks
Section titled “Fire and Forget: Background Tasks”Sometimes, an API request triggers an action that takes time to complete, such as sending a confirmation email, processing a video file, or crunching heavy data. If you make the user wait for these tasks to finish, your API will feel slow and unresponsive.
FastAPI provides a simple mechanism to solve this: Background Tasks. This allows you to return a response to the user immediately while the server continues to process the heavy logic in the background.
Using the BackgroundTasks Class
Section titled “Using the BackgroundTasks Class”To use this feature, simply declare a parameter of type BackgroundTasks in your path operation function. You do not need to install extra libraries like Celery for simple use cases; this is built right into FastAPI (via Starlette).
Scheduling Operations
Section titled “Scheduling Operations”Instead of calling your heavy function directly, you use the .add_task() method on the background_tasks object. You pass the function reference and any arguments it needs.
Example: Sending a Notification
Section titled “Example: Sending a Notification”Let’s simulate sending an email notification. We define a standard Python function for the logic, and then schedule it in our endpoint.
from fastapi import BackgroundTasks, FastAPI
app = FastAPI()
# This is our heavy taskdef write_notification(email: str, message=""): with open("log.txt", mode="w") as email_file: content = f"notification for {email}: {message}" email_file.write(content)
@app.post("/send-notification/{email}")def send_notification(email: str, background_tasks: BackgroundTasks): # Schedule the task background_tasks.add_task(write_notification, email, message="some notification")
# Return the response immediately return {"message": "Notification sent in the background"}How It Works
Section titled “How It Works”When the client calls /send-notification/user@example.com:
- The
send_notificationfunction executes. - The task is added to the queue.
- FastAPI sends the JSON response
{"message": "Notification sent in the background"}to the client. - After the response is sent, the
write_notificationfunction runs on the server.
This “Fire and Forget” pattern ensures your API remains snappy and provides a better user experience.