Skip to the page

FastAPI · mid

Testing FastAPI, streaming answers and why BackgroundTasks lose work

Tests override dependencies and use a real database. Streaming uses an async generator with proper disconnect handling. BackgroundTasks run in the same process with no retry, so must-run work belongs in a durable queue.

The notes

What you must know

  • TestClient(app) (built on HTTPX), used as a context manager so lifespan runs. For an async test use httpx.AsyncClient(transport=ASGITransport(app=app)), which does not run lifespan.
  • Auth: app.dependency_overrides, cleared in teardown. Database: a real PostgreSQL (Testcontainers or a CI service) with a transaction per test. SQLite hides PostgreSQL behaviour. Outgoing HTTP: override the client dependency or use respx or httpx.MockTransport.
  • Test failures on purpose: a bad body (422), no token (401), another user's data (403 or 404), a gateway timeout (502 or 503 and no charge recorded). Flaky tests come from uncleared overrides, global state and time.
  • Streaming: an async generator calling the vendor's streaming client, returned as StreamingResponse with media_type text/event-stream (SSE: "data: ..." plus a blank line). SSE fits one-way text and reconnects by itself; WebSockets fit two-way messages.
  • Disconnects: check request.is_disconnected() or handle CancelledError to stop the upstream call, and re-raise. Timeouts on the vendor call; retry only before the first chunk.
  • Proxies buffer: turn off proxy_buffering in Nginx (or send X-Accel-Buffering: no) and raise proxy_read_timeout. Add per-user rate limits and token budgets, and save the full answer at the end.
  • BackgroundTasks run in the same process after the response is sent. Nothing stores or retries them, so on a deploy (SIGTERM) pending tasks are lost with no error.
  • Must-happen work (emails, invoices, webhooks) goes to a durable queue (Celery, RQ, Dramatiq) or an outbox table. Record invoice_emailed_at or a unique log row so a retry sends once, and alert on "created but not emailed after 15 minutes".

The red pen

Common traps: mistake → fix

  • Mistake: BackgroundTasks are a small Celery

    Fix: they have no queue, no retry and no record.

  • Mistake: SQLite is fine for tests

    Fix: it hides PostgreSQL behaviour.

  • Mistake: AsyncClient runs lifespan like TestClient

    Fix: it does not.

  • Mistake: Streaming works through any proxy

    Fix: proxies buffer unless told not to.

Easy to hard

Questions interviewers ask, easy to hard

  1. How do you test a FastAPI endpoint that needs a user, writes to a database and calls a payment gateway?
  2. How do you stream an AI answer to the browser?
  3. How do you stop paying for tokens when the user closes the tab?
  4. Why do invoices get lost after every deploy?
  5. What would you use instead of BackgroundTasks?

Explain it out loud

Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.

Practise by voice

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview