openlibrary icon indicating copy to clipboard operation
openlibrary copied to clipboard

Add global exception handler and request correlation IDs to FastAPI app

Open soumojit-D48 opened this issue 3 months ago • 2 comments

Problem

The FastAPI app has no @app.exception_handler() registered. When an unhandled exception occurs, FastAPI returns its default HTML error page instead of JSON. This breaks the API contract for clients expecting JSON responses.

Additionally, there are no request correlation IDs. When Sentry captures an error or logs are searched, there's no way to trace all events from a single request. This makes production debugging very difficult.

Evidence:

  • openlibrary/asgi_app.py — no @app.exception_handler() anywhere
  • Unhandled exceptions return HTML 500, not JSON
  • No X-Request-ID header in responses
  • No request ID in log entries

Reproducing the bug

  1. Hit any FastAPI endpoint that raises an unexpected exception
  2. Response is HTML, not JSON
  3. Check response headers — no X-Request-ID present
  4. Check logs — no correlation between log entries for the same request
  • Expected behavior: All error responses are structured JSON with a request_id field. Every response includes an X-Request-ID header.
  • Actual behavior: Unhandled errors return HTML. No request tracing.

Context

  • Environment: prod, dev, local (all)

Breakdown

Implementation Details (for maintainers)

Proposed fix

  • Add correlation ID middleware that generates a UUID per request, attaches to request.state, and adds X-Request-ID response header
  • Register @app.exception_handler(StarletteHTTPException) for structured JSON
  • Register @app.exception_handler(RequestValidationError) for structured validation errors
  • Register @app.exception_handler(Exception) as catch-all for unhandled exceptions

Requirements Checklist

  • [ ] Correlation ID middleware adds X-Request-ID to every response
  • [ ] Client-provided X-Request-ID is preserved if present
  • [ ] HTTPException returns JSON with error and request_id
  • [ ] RequestValidationError returns 422 JSON with error, detail, and request_id
  • [ ] Unhandled Exception returns 500 JSON with error, message, and request_id
  • [ ] Existing tests pass
  • [ ] Pre-commit hooks pass

Related files

  • openlibrary/asgi_app.py

soumojit-D48 avatar Aug 07 '26 18:08 soumojit-D48

Thank you @soumojit-D48 for submitting this issue!

Context

  • Confirmed via grep across openlibrary/ — there is no @app.exception_handler() registration, no X-Request-ID header, and no request_id/correlation-ID handling anywhere in the codebase. The gap described is real.
  • openlibrary/asgi_app.py already registers several middlewares in two different styles that a correlation-ID middleware could follow:
    • Decorator-based: https://github.com/internetarchive/openlibrary/blob/1d23364b8c652d6107e2dc685f918551fda5d327/openlibrary/asgi_app.py#L185-L202
    • Class-based ASGI middleware: https://github.com/internetarchive/openlibrary/blob/1d23364b8c652d6107e2dc685f918551fda5d327/openlibrary/fastapi/middleware/experiments.py#L1-L35
  • A form of per-request correlation ID already exists for the legacy web.py side via Sentry (trace_id / sentry-trace header), but it is not wired into FastAPI responses:
    • https://github.com/internetarchive/openlibrary/blob/1d23364b8c652d6107e2dc685f918551fda5d327/openlibrary/utils/sentry.py#L89-L96
    • https://github.com/internetarchive/openlibrary/blob/1d23364b8c652d6107e2dc685f918551fda5d327/openlibrary/utils/sentry.py#L147-L153
  • Likely breaking change not addressed in the issue's checklist: FastAPI routers already raise fastapi.HTTPException in many places (account.py, auth.py, cdn.py, link.py, checkins.py, merge_authors.py, partials.py, models.py), and FastAPI's default behavior returns {"detail": "..."} as the JSON body. At least 7 existing test files assert on that exact shape, e.g. resp.json()["detail"] == "Unauthorized" (https://github.com/internetarchive/openlibrary/blob/1d23364b8c652d6107e2dc685f918551fda5d327/openlibrary/tests/fastapi/test_account.py#L150), with similar assertions in test_auth.py (4), test_account_loans.py (1), test_link.py (4), test_lists_json.py (3), test_list_seeds.py (3), and test_merge_authors.py (2). The proposal's target schema (error, request_id) doesn't mention detail — if the new StarletteHTTPException handler drops it, all of these break.
  • No duplicate or prior-attempt issue/PR was found for this specific request.

Issue Assessment

Open questions

  • [x] Does an exception handler or request-ID mechanism already exist anywhere in the app? (Answer: No — confirmed by grep; the only existing per-request correlation mechanism is Sentry's trace_id/sentry-trace, and it's legacy-web.py-only, not exposed on FastAPI responses.)
  • [ ] Should the new request_id/X-Request-ID be independent of, or unified with, Sentry's existing trace correlation, so ops can correlate FastAPI logs, response headers, and Sentry events with one ID? This is a design call for whoever leads FastAPI work.
  • [ ] Should the new JSON error schema preserve the existing detail field (to avoid breaking the ~24 existing test assertions and any external clients depending on it), or is an intentional breaking change to the error contract acceptable here? This affects the "Existing tests pass" requirement already in the checklist.

Stakeholders

🔔 Stakeholders

@RayBB — dev experience, documentation, and FastAPI migration lead; openlibrary/asgi_app.py is the core FastAPI app definition this issue proposes to modify.

Full triage checklist
  • [x] Triage — correct labels applied or removed
  • [x] Problem / opportunity — problem is clear, audience identified (API clients, ops/on-call debugging via logs/Sentry), reasoning for impact given
  • [x] Scope — well-scoped to a single file (openlibrary/asgi_app.py) and a bounded set of handlers/middleware
  • [x] Justification — reasoning given (broken API contract, no request tracing); no quantified incident data, but plausible on its face
  • [x] Success & testing criteria — requirements checklist is concrete and verifiable
  • [x] Proposal & breakdown — specific handlers, middleware behavior, and related file identified
  • [x] If bug: environment & repro steps — clear repro steps given, applies to prod/dev/local
  • [x] Risks, concerns, open questions — surfaced above (breaking detail field change, Sentry trace-ID overlap)
  • [x] Richy context — relevant code, tests, and prior Sentry correlation mechanism reviewed; no duplicate found
  • [ ] References — no screenshots/designs needed for this backend change; N/A

[!NOTE] This comment was automatically generated by Richy, Open Library's issue enrichment assistant, on behalf of @mekarpeles. This is NOT a sign-off. This issue needs lead review before work begins.

openlibrary-bot avatar Aug 07 '26 18:08 openlibrary-bot

@soumojit-D48 can you provide a real url for reproduction? How is this impacting your use of Open Library?

RayBB avatar Aug 07 '26 19:08 RayBB