← Back to FastAPI, page 5

fastapi-0085 · Hard senior

How do you design an API for long-running jobs in FastAPI using 202 Accepted, status polling and idempotency keys?

Accept the request, validate it, create a job record, hand the work to a worker, and return 202 Accepted with a Location header pointing to a job status resource. Clients poll that resource (or receive a webhook) until it reports succeeded or failed with a result link. An Idempotency-Key header lets clients retry the POST safely: the same key returns the same job instead of starting duplicate work. Production workers should be a queue such as Celery, ARQ or a database-backed worker.

Full answer

Request-response APIs should not hold HTTP connections open for minutes: proxies time out, clients retry, and workers get tied up.

Resource flow:

  1. POST /reports validates input, creates a job row (id, status=queued, created_at, owner, idempotency_key), enqueues work, and returns 202 Accepted with Location: /jobs/{id} and a body like {"id": ..., "status": "queued"}. Optionally include Retry-After.
  2. GET /jobs/{id} returns status (queued, running, succeeded, failed), progress, timestamps, error details, and on success a link to the result (/reports/{id}/download). A finished job may answer 303 See Other to the result.
  3. DELETE /jobs/{id} or POST /jobs/{id}/cancel cancels if possible.
  4. Optional push: webhook or Server-Sent Events for status changes, with polling still available.

Idempotency: clients on flaky networks retry the POST. With an Idempotency-Key header, store (owner, key) -> job_id with a unique constraint; if the key is seen, return the original job with the same status code (and reject reuse of a key with a different payload using 422 or 409). Expire keys after a day or so.

Workers: BackgroundTasks and in-process thread pools disappear on restart and cannot scale out. Use Celery, ARQ, RQ or Dramatiq with a persistent broker, make tasks idempotent, write status transitions to the database, add retries with backoff and a dead-letter strategy, and set time limits. Enqueue after commit (or via an outbox) to avoid workers seeing a missing job.

Details: authorise job reads (owner check), do not leak other users' job IDs, use unguessable IDs, rate-limit job creation, cap queue length with 429 or 503 under load, and keep results for a limited time.

python
import threading
from concurrent.futures import ThreadPoolExecutor
from typing import Annotated

from fastapi import FastAPI, Header, HTTPException, Response
from fastapi.testclient import TestClient

app = FastAPI()
pool = ThreadPoolExecutor(max_workers=2)           # stand-in for Celery or ARQ workers
jobs: dict[str, dict] = {}
by_key: dict[str, str] = {}
gate = threading.Event()                           # lets the demo keep a job "running" on purpose


def build_report(job_id: str):
    jobs[job_id]["status"] = "running"
    gate.wait(timeout=5)
    jobs[job_id].update(status="succeeded", result="/reports/" + job_id + "/download")


@app.post("/reports", status_code=202)
def start(response: Response, idempotency_key: Annotated[str | None, Header()] = None):
    if idempotency_key and idempotency_key in by_key:
        job_id = by_key[idempotency_key]                       # same key, same job
    else:
        job_id = f"job-{len(jobs) + 1}"                        # use uuid4 in real code
        jobs[job_id] = {"id": job_id, "status": "queued"}
        if idempotency_key:
            by_key[idempotency_key] = job_id
        pool.submit(build_report, job_id)
    response.headers["Location"] = f"/jobs/{job_id}"
    response.headers["Retry-After"] = "2"
    return {"id": job_id, "status": jobs[job_id]["status"]}


@app.get("/jobs/{job_id}")
def status(job_id: str):
    if job_id not in jobs:
        raise HTTPException(404, "Unknown job")
    return jobs[job_id]


c = TestClient(app)
first = c.post("/reports", headers={"Idempotency-Key": "abc-1"})
retry = c.post("/reports", headers={"Idempotency-Key": "abc-1"})
print(first.status_code, first.headers["location"], retry.headers["location"], "jobs created:", len(jobs))
import time
while jobs["job-1"]["status"] != "running":
    time.sleep(0.01)
print("while the worker runs:", c.get(first.headers["location"]).json()["status"])
gate.set()
pool.shutdown(wait=True)
print("after the worker finishes:", c.get("/jobs/job-1").json())
print(c.get("/jobs/nope").status_code)

Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed. The thread pool stands in for a real queue. Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0): 202 /jobs/job-1 /jobs/job-1 jobs created: 1 while the worker runs: running after the worker finishes: {'id': 'job-1', 'status': 'succeeded', 'result': '/reports/job-1/download'} 404

Key points

  • 202 Accepted with a Location header to a job resource
  • Status endpoint with queued, running, succeeded, failed
  • Idempotency-Key makes retried POSTs safe
  • Use a persistent queue, not in-process tasks, in production
  • Enqueue after commit; authorise job access

Common mistakes

  • Holding the HTTP request open for the whole job
  • Using in-process background tasks for important jobs
  • No idempotency, so retries create duplicate jobs
  • Letting any user read any job by ID
  • Enqueueing before the transaction commits

Follow-ups

  • How would you notify clients without polling?
  • How do you cancel a running job?
  • How do you size the queue and apply backpressure?

Tips

  • Lay out the endpoint flow
  • Explain Idempotency-Key
  • Say where the worker runs