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 seconds
time.sleep(5)
return {"message": "Email sent"}

Problem:

  • User waits 5 seconds
  • API becomes slow

With Background Tasks

from fastapi import BackgroundTasks, FastAPI

app = FastAPI()

def send_email_task(email: str):
import time
time.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

  1. Request comes in.
  2. FastAPI returns response immediately.
  3. 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 emails
    2.Logging activity
    3.Notifications
    4.Small async jobs

Limitations

BackgroundTasks is not suitable for:

    1.Heavy processing (ML, video processing)
    2.Long-running jobs
    3.Distributed systems

For these, use:

  • Celery
  • Redis
  • RabbitMQ

Best Practices

    1.Keep tasks lightweight
    2.Avoid blocking operations
    3.Use proper logging
    4.Move heavy jobs to task queues

Common Mistakes

    1.Running heavy logic in background tasks
    2.Assuming tasks run in parallel (they don’t scale like Celery)
    3.Not handling failures

Key Takeaways

  • Background tasks improve API performance
  • They run after sending response
  • Ideal for non-critical operations
  • Not suitable for heavy workloads

Comments

Popular posts from this blog

Database Integration in FastAPI (SQLAlchemy CRUD)

Middleware & CORS in FastAPI

Python Data Handling