Background Tasks in FastAPI (Async & Non-Blocking Operations)
Introduction
In real-world applications, some tasks:
- Take time
- Don’t need immediate response
- Should run in the background
Examples:
- Sending emails
- Logging activity
- Processing files
FastAPI provides a simple way to handle this using Background Tasks.
What are Background Tasks?
Background tasks are operations that:
- Run after returning a response
- Do not block the main request
- Improve API performance
Without Background Tasks
@app.post("/send-email")def send_email():# takes 5 secondstime.sleep(5)return {"message": "Email sent"}
Problem:
- User waits 5 seconds
- API becomes slow
With Background Tasks
from fastapi import BackgroundTasks, FastAPIapp = FastAPI()def send_email_task(email: str):import timetime.sleep(5)print(f"Email sent to {email}")@app.post("/send-email/")def send_email(email: str, background_tasks: BackgroundTasks):background_tasks.add_task(send_email_task, email)return {"message": "Email is being sent"}
Response is instant .Task runs in background.
How It Works
- Request comes in.
- FastAPI returns response immediately.
- Background task runs after response
Real-World Example: User Registration
def send_welcome_email(email: str):print(f"Welcome email sent to {email}")@app.post("/register/")def register_user(email: str, background_tasks: BackgroundTasks):# Save user (DB logic here)background_tasks.add_task(send_welcome_email, email)return {"message": "User registered successfully"}Multiple Background Tasks
def task1():print("Task 1 done")def task2():print("Task 2 done")@app.get("/tasks/")def run_tasks(background_tasks: BackgroundTasks):background_tasks.add_task(task1)background_tasks.add_task(task2)return {"message": "Tasks running"}When to Use Background Tasks
1.Sending emails2.Logging activity3.Notifications4.Small async jobsLimitations
BackgroundTasks is not suitable for:
1.Heavy processing (ML, video processing)2.Long-running jobs3.Distributed systemsFor these, use:
- Celery
- Redis
- RabbitMQ
Best Practices
1.Keep tasks lightweight2.Avoid blocking operations3.Use proper logging4.Move heavy jobs to task queuesCommon Mistakes
1.Running heavy logic in background tasks2.Assuming tasks run in parallel (they don’t scale like Celery)3.Not handling failuresKey Takeaways
- Background tasks improve API performance
- They run after sending response
- Ideal for non-critical operations
- Not suitable for heavy workloads
Comments
Post a Comment