📝 Fastapi

Background Tasks in FastAPI

P
Author
Pyland
📅
Published
30.06.2026
⏱️
Reading time
1 min
👁️
Views
90
🌳
Level
Advanced

BackgroundTasks — execute tasks after the response has been sent to the client.

Basic Usage

from fastapi import FastAPI, BackgroundTasks

app = FastAPI()

def send_email(email: str, message: str):
    # Runs after the response is sent
    print(f"Sending email to {email}: {message}")

@app.post("/tasks/")
def create_task(task: TaskCreate, background_tasks: BackgroundTasks):
    # Create the task
    db_task = save_task(task)

    # Add a background task
    background_tasks.add_task(send_email, "user@example.com", f"Task created: {task.title}")

    # Response is sent immediately, email is sent afterwards
    return db_task

Multiple Tasks

@app.post("/users/register")
def register(user: UserCreate, background_tasks: BackgroundTasks):
    db_user = create_user(user)

    background_tasks.add_task(send_welcome_email, db_user.email)
    background_tasks.add_task(notify_admin, db_user.id)
    background_tasks.add_task(update_stats)

    return {"message": "Registered"}

Via Depends

def get_background_tasks(background_tasks: BackgroundTasks):
    return background_tasks

@app.post("/tasks/")
def create_task(
    task: TaskCreate,
    bg: BackgroundTasks = Depends(),
):
    db_task = save_task(task)
    bg.add_task(process_task, db_task.id)
    return db_task

Limitations

  • Runs in the same process — will block if the task takes too long
  • No retry on errors
  • No monitoring

When to Use

  • Sending email/SMS after an action
  • Updating a cache
  • Logging to a third-party service
  • Short-lived tasks (< 30 sec)

For Heavy Tasks — Celery or ARQ

pip install celery redis
@celery.task
def heavy_processing(task_id: int):
    ...  # long processing in a separate worker

@app.post("/tasks/")
def create_task(task: TaskCreate):
    db_task = save_task(task)
    heavy_processing.delay(db_task.id)  # non-blocking
    return db_task

Your reaction to the article

💬 Comments (0)

🔐 Sign in to leave a comment
🚪 Login
💭

No comments yet

Be the first to share your opinion about this article!

🔗 Similar

Similar articles

Continue learning with these materials

📝

Middleware and CORS in FastAPI

Allows browser clients to make requests to an API from a different domain.

📅 30.06.2026 👁️ 88
📝

HTTPException in FastAPI

Охватываемые темы: Basic Usage, Status Codes, Error Details, Custom Headers.

📅 30.06.2026 👁️ 91
📝

Dependency Injection in FastAPI

Depends — FastAPI's dependency injection system for reusing code across endpoints.

📅 30.06.2026 👁️ 85

Did you like the article?

Subscribe to our updates and receive new articles first. Grow with PyLand!