← Back to FastAPI, page 5

fastapi-0090 · Hard senior

How do you handle timeouts, cancellation and client disconnects in async FastAPI endpoints without leaking work or connections?

Set explicit timeouts on every outbound call and wrap multi-step work in asyncio.timeout so slow dependencies produce a clean 504 instead of hanging workers. When a client disconnects, the ASGI server cancels the handler task (for streaming responses) and the code receives CancelledError: use try/finally to release resources and never swallow the cancellation. Poll request.is_disconnected() in long non-streaming loops. Shield only short critical cleanup, such as commits.

Full answer

Why this matters: without limits, one slow database or API call holds a task, a connection and memory for as long as the dependency stalls. Hung requests pile up until the pool is exhausted.

Timeouts at every layer:

  • Client side: httpx.Timeout(connect=2, read=5, write=5, pool=1) (never rely on defaults of libraries without a timeout; some wait forever). Database: statement timeout (SET statement_timeout), pool timeout.
  • Endpoint level: async with asyncio.timeout(3): (Python 3.11+) around the whole operation; catch TimeoutError and return 504 Gateway Timeout (or 503). The inner awaits are cancelled, which triggers their finally blocks.
  • Server level: Uvicorn --timeout-keep-alive, --timeout-graceful-shutdown; Gunicorn worker timeout (for UvicornWorker it is a heartbeat, not a request limit); proxy timeouts (nginx proxy_read_timeout) should be larger than the app's own limit so the app answers first.

Cancellation semantics:

  • asyncio.CancelledError is raised at an await. Do cleanup in finally or except asyncio.CancelledError: ...; raise. Swallowing it breaks timeout(), task groups and shutdown.
  • When a client drops the connection, Starlette's StreamingResponse (and server-sent events) detects http.disconnect and cancels the task, so generators receive cancellation and can close upstream streams.
  • For normal endpoints that already received the full body, the framework does not interrupt your handler on disconnect; the work finishes and the response is discarded. For expensive operations, poll await request.is_disconnected() between steps and stop early, or run the work as a background job independent of the connection.
  • asyncio.shield() protects a short operation (final commit, releasing a lock) from being cancelled mid-way. Do not shield long work.
  • Sync (def) endpoints run in worker threads that cannot be cancelled; set timeouts inside their calls.

Idempotency matters because after a timeout the client may retry while the original work is still running or already committed.

python
import asyncio

from fastapi import FastAPI, HTTPException
from fastapi.responses import StreamingResponse

app = FastAPI()
events = []


async def slow_dependency():
    try:
        await asyncio.sleep(10)
    finally:
        events.append("slow dependency cancelled and cleaned up")


@app.get("/report")
async def report():
    try:
        async with asyncio.timeout(0.05):
            await slow_dependency()
    except TimeoutError:
        raise HTTPException(status_code=504, detail="Upstream too slow")


@app.get("/stream")
async def stream():
    async def numbers():
        try:
            yield b"first chunk\n"
            await asyncio.Event().wait()               # waits forever, like a slow upstream
        except asyncio.CancelledError:
            events.append("stream cancelled by client disconnect")
            raise
        finally:
            events.append("upstream connection closed")

    return StreamingResponse(numbers())


def scope(path):
    return {"type": "http", "asgi": {"version": "3.0", "spec_version": "2.3"}, "http_version": "1.1", "method": "GET",
            "scheme": "http", "path": path, "raw_path": path.encode(), "query_string": b"", "headers": [],
            "server": ("t", 80), "client": ("127.0.0.1", 1), "root_path": ""}


async def get(path, disconnect_after_first_chunk=False):
    first_chunk_sent = asyncio.Event()
    status = []

    async def receive():
        if disconnect_after_first_chunk:
            await first_chunk_sent.wait()
            return {"type": "http.disconnect"}
        return {"type": "http.request", "body": b"", "more_body": False}

    async def send(message):
        if message["type"] == "http.response.start":
            status.append(message["status"])
        elif message["type"] == "http.response.body" and message.get("body"):
            first_chunk_sent.set()

    await app(scope(path), receive, send)
    return status[0]


async def main():
    print("timeout ->", await get("/report"), events)
    events.clear()
    await get("/stream", disconnect_after_first_chunk=True)
    print(events)


asyncio.run(main())

Standalone script. Run it with `python file.py`; it drives the ASGI app directly so the disconnect can be simulated. Requires Python 3.11 or later for asyncio.timeout. 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): timeout -> 504 ['slow dependency cancelled and cleaned up'] ['stream cancelled by client disconnect', 'upstream connection closed']

Key points

  • Set explicit timeouts on every outbound call and with asyncio.timeout
  • CancelledError must be allowed to propagate; use finally for cleanup
  • Streaming responses are cancelled on disconnect; plain handlers are not
  • Proxy timeouts should exceed app timeouts
  • Make operations idempotent because retries follow timeouts

Common mistakes

  • Calling external services without timeouts
  • Catching CancelledError and not re-raising it
  • Assuming plain endpoints stop when the client disconnects
  • Setting proxy timeouts lower than the application's
  • Shielding long operations, which defeats timeouts

Follow-ups

  • How do task groups change cancellation handling?
  • What happens to sync endpoints on timeout?
  • How do you design retries after a gateway timeout?

Tips

  • Mention asyncio.timeout
  • Say re-raise CancelledError
  • Contrast streaming and plain endpoints