๐Ÿ“ Fastapi

Background Tasks in FastAPI

P
Author
PyLand Team
๐Ÿ“…
Published
30.06.2026
โฑ๏ธ
Reading time
1 min
๐Ÿ‘๏ธ
Views
318
๐ŸŒณ
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

Middleware processes requests and responses around FastAPI routes, while CORS controls which browser origins may...

๐Ÿ“… 30.06.2026 ๐Ÿ‘๏ธ 330
๐Ÿ“

HTTPException in FastAPI

Covered topics: Basic Usage, Status Codes, Error Details, Custom Headers.

๐Ÿ“… 30.06.2026 ๐Ÿ‘๏ธ 298
๐Ÿ“

Dependency Injection in FastAPI

Depends โ€” FastAPI's dependency injection system for reusing code across endpoints.

๐Ÿ“… 30.06.2026 ๐Ÿ‘๏ธ 304

Did you like the article?

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