Skip to content

Lesson 5 of 9 · 23m

Background Tasks and Jobs: Where Work Really Happens

When FastAPI BackgroundTasks is enough, when it is dangerous, and how to design reliable asynchronous work with retries, idempotency, and visibility.

Every tutorial reaches the part where sending email makes the request slow and says, 'use a background task.' Production is where that sentence becomes dangerous. FastAPI's BackgroundTasks runs work after the response in the same server process. It is useful for tiny fire-and-forget operations, not for anything whose loss would matter.

Know what in-process background tasks cannot promise

from fastapi import BackgroundTasks

@app.post("/reports")
def create_report(tasks: BackgroundTasks):
    report_id = queue_report()
    tasks.add_task(render_report, report_id)
    return {"id": report_id, "status": "queued"}

The response goes out first, then the function runs. If the process exits, deploys, crashes, or the worker is killed, the task is gone. There is no retry, no visibility, no distributed locking, no persistence. That may be fine for cache warming or analytics pings. It is not fine for invoices, password resets, or audit exports.

A real job needs a durable queue

The scalable shape is simple: the request validates input, writes the job transactionally, returns accepted status, and a worker consumes it later.

client → API → database/job queue → worker → external service
                    ↘ status endpoint ↗

Use Redis-backed systems such as RQ, Celery, Dramatiq, or a database-backed queue when operational simplicity matters more than throughput. The exact tool matters less than persistence, retries, dead-letter handling, and observability.

Design jobs to be idempotent

Workers will retry. Networks will duplicate. Your job must tolerate being executed twice. Give every job a stable idempotency key and make effects conditional:

def send_invoice_email(invoice_id: int, job_key: str):
    if already_processed(job_key):
        return
    invoice = load_invoice(invoice_id)
    send_email_once(invoice, dedupe_key=job_key)
    mark_processed(job_key)

Do not assume 'exactly once' delivery exists. In practice you build at-least-once delivery plus idempotent effects.

Timeouts are part of correctness

A job without timeouts is a stuck worker with extra steps. Set connection, read, and total execution timeouts. Make retries exponential with jitter, cap the maximum attempts, and move poisoned jobs to a dead-letter queue rather than retrying forever.

Keep the request/response contract honest

If work is asynchronous, return 202 Accepted plus a status URL. Do not pretend the operation completed. Clients should poll /jobs/{id} or receive a webhook, and the API should expose states such as queued, running, succeeded, failed, and cancelled with timestamps and safe error details.

Field notes

  • BackgroundTasks is same-process convenience, not reliability infrastructure.
  • Put enqueueing and business state changes in one transaction where possible; otherwise you can commit the job but lose the state or vice versa.
  • Payloads should carry IDs, not giant serialized objects; queues are coordination, not databases.
  • Monitor queue depth and oldest job age. A rising queue is often the first symptom of an outage.

Was this lesson helpful?

Sign in to rate