Background Tasks
Running tasks asynchronously after the HTTP response has been sent.
🧑🏫 Sabse pehle — simple mein samjho#
Maan lo ek naya user signup karta hai, aur tumhara server usko welcome email bhejta hai. Email bhejne mein 3 seconds lagte hain. Agar tum normal code likhoge, to user ko frontend pe 3 seconds tak ghoomta hua lattu (spinner) dikhega. Ye UX ke liye bahot bura hai! FastAPI mein BackgroundTasks aata hai. Tum server ko bolte ho, "Bhai tu HTTP response fauran bhej de taaki user khush ho jaye, aur email bhejne ka kaam piche background mein aaram se karta reh".
The BackgroundTasks Class#
FastAPI provides a built-in BackgroundTasks class. You inject it into your route function just like any other parameter.
When you add a function to BackgroundTasks, FastAPI will:
- Immediately send the HTTP response to the client.
- Execute the added function independently in the background.
Example: Sending an Email#
from fastapi import FastAPI, BackgroundTasks
import time
app = FastAPI()
# 1. A slow function that we don't want the user to wait for
def send_email_notification(email: str, message: str):
# Simulating a slow network request
time.sleep(3)
print(f"Email successfully sent to {email} with message: {message}")
@app.post("/signup")
async def signup(email: str, background_tasks: BackgroundTasks):
# Save the user to the database (fast operation)
# db.create_user(email)
# 2. Add the slow task to the background queue.
# Notice we pass the function reference, NOT the function call `()`
background_tasks.add_task(send_email_notification, email, "Welcome to our app!")
# 3. This response is sent instantly! The email sends 3 seconds later in the background.
return {"message": "User registered successfully! Check your email."}
When to use Celery instead?#
BackgroundTasks is perfect for lightweight operations that take a few seconds (like sending a single email or updating a counter in a database).
However, it runs in the exact same memory space as your FastAPI server. If you have heavy operations (like processing a massive 2GB CSV file, transcoding a video, or scraping 500 webpages), it will eat up your server's RAM and slow down API responses for everyone else.
For heavy, long-running tasks, you should integrate a dedicated task queue system like Celery (with Redis/RabbitMQ as the broker). Celery runs completely separately from your FastAPI server on a different worker process.