0PricingLogin
FastAPI Backend Development Bootcamp · Lesson

Lightweight Offloading with BackgroundTasks

Use FastAPI's built-in BackgroundTasks for fire-and-forget side effects without blocking the response.

Why Offload Work?

When a client sends a request, they wait for the response. If your endpoint also sends a welcome email, writes an audit log, or warms a cache, the user is stuck waiting for work they don't care about.

Fire-and-forget side effects are tasks that should run after the response is sent, without blocking it:

  • Sending notification emails
  • Writing analytics or audit logs
  • Invalidating or warming caches
  • Cleaning up temporary files

FastAPI ships a built-in tool for exactly this: BackgroundTasks.

Declaring BackgroundTasks

To use it, add a parameter typed as BackgroundTasks to your path operation function. FastAPI sees the type annotation and injects an instance for you, just like any other dependency.

You then register work with .add_task(func, *args, **kwargs). The function is not called immediately, it is queued to run once the response has been returned.

from fastapi import BackgroundTasks, FastAPI

app = FastAPI()


def write_log(message: str) -> None:
    with open("log.txt", mode="a") as f:
        f.write(message + "\n")


@app.post("/signup")
async def signup(email: str, tasks: BackgroundTasks):
    tasks.add_task(write_log, f"signup: {email}")
    return {"status": "accepted"}

All lessons in this course

  1. Lightweight Offloading with BackgroundTasks
  2. Wiring Celery Workers to a FastAPI App
  3. Retries, Idempotency and Dead-Letter Handling
  4. Scheduled and Periodic Jobs with Celery Beat
← Back to FastAPI Backend Development Bootcamp