USMAN’S INSIGHTS
AI ARCHITECT
⌘F
HomeAll BooksBackend Book
HomeBackend BookFastAPI
PreviousDependency Injection and Application LifespanNextAPI Design: Pagination, Versioning, and Streaming
AI NOTICE: This is the table of contents for the SPECIFIC CHAPTER only. It is NOT the global sidebar. For all chapters, look at the main navigation.

On this page

13 sections

Progress0%
1 / 13

Muhammad Usman Akbar Entity Profile

Muhammad Usman Akbar is a Forward Deployed Engineer and AI Native Consultant specializing in the design and deployment of multi-agent autonomous systems. Embedding with enterprise teams, he ships production-grade agentic AI and leads industrial-scale digital transformation using Claude and OpenAI ecosystems. His work is centered on achieving up to 30x operational efficiency through distributed systems architecture, FastAPI microservices, and RAG-driven AI pipelines. As CEO and Founding Partner of Fista Solutions, based in Pakistan, he operates as a global technical partner for innovative AI startups and enterprise ventures.

USMAN’S INSIGHTS
AI ARCHITECT

Transforming businesses into autonomous AI ecosystems. Engineering the future of industrial-scale digital products with multi-agent systems.

30X Growth
AI-First
Innovation

Navigation

  • Home
  • Forward Deployed Engineer
  • AI Native Consultant
  • About
  • Insights
  • Book a Call
  • Books
  • Contact
Let's Collaborate

Have a Project in Mind?

Let's build something extraordinary together. Transform your vision into autonomous AI reality.

Start Your Transformation

© 2026 Muhammad Usman Akbar. All rights reserved.

Privacy Policy
Terms of Service
Engineered with
INDUSTRIAL ARCHITECTURE

Errors, Middleware, and Request Context

An API should translate internal failures into stable, non-sensitive problem responses while preserving detailed evidence in protected telemetry. Middleware is appropriate for concerns that truly wrap every request, such as correlation, timing, and selected security headers. Domain decisions and resource authorization do not belong in generic middleware.

What will you be able to do?

  • map domain and dependency failures to HTTP semantics;
  • attach a trusted correlation identifier;
  • record timing without logging secrets or bodies;
  • understand middleware order and failure behavior.

How should a public error be shaped?

python
from uuid import uuid4 from fastapi import Request from fastapi.responses import JSONResponse @app.exception_handler(TicketNotFound) async def ticket_not_found(request: Request, error: TicketNotFound) -> JSONResponse: trace_id = request.state.trace_id return JSONResponse( status_code=404, content={ "type": "/problems/ticket-not-found", "title": "Ticket not found", "status": 404, "detail": "No ticket is available for this identifier.", "trace_id": trace_id, }, ) @app.middleware("http") async def request_context(request: Request, call_next): supplied = request.headers.get("X-Request-ID", "") request.state.trace_id = supplied[:128] if supplied.isascii() else str(uuid4()) response = await call_next(request) response.headers["X-Request-ID"] = request.state.trace_id return response

In production, generate or validate identifiers using a strict format and connect them with distributed trace context. A client-provided ID is a correlation hint, never an identity or permission.

What should logs contain?

Record event name, timestamp, severity, route template, status, duration, trace ID, and safe application identifiers. Avoid authorization headers, cookies, request bodies, raw prompts, retrieved private text, database URLs, and stack traces in client responses. Central redaction should be backed by tests.

How should unexpected errors behave?

Return a generic 500 with a trace ID, record the original exception in protected logs, and let monitoring count it. Do not catch BaseException, cancellation signals, or process-exit events as ordinary application errors.

Why does this matter in AI-native systems?

An AI operation spans API, queue, retrieval, provider, and tools. Propagate trace context across boundaries and record safe identifiers for the prompt, model, schema, and evaluation versions. Raw model context can contain personal or proprietary data; observability must be useful without becoming a second ungoverned dataset.

Common mistakes

  • Logging full request/response bodies by default.
  • Returning database or provider exceptions to clients.
  • Adding business transactions inside middleware.
  • Trusting spoofable forwarding headers without a known proxy boundary.
  • Measuring only completed requests; cancellations and middleware failures disappear.

AI Pair-Programmer Prompt

text
Threat-model this API's error and logging path. Map each exception category to a public status and internal event; list fields to log, redact, hash, or omit; validate correlation and proxy headers; and propose tests proving secrets, prompts, and cross-tenant identifiers cannot leak.

Exercise

Add problem responses for validation, forbidden access, conflict, dependency timeout, and unexpected failure. Add a redaction test using a fake secret.

Acceptance criteria: every response includes a correlation ID, errors have stable types, and the fake secret appears nowhere in captured logs or bodies.

Knowledge check

  1. Should stack traces be returned to clients?
  2. Is a request ID an authentication credential?
  3. Why avoid raw prompts in normal logs?

Answers

  1. No; preserve them in protected telemetry and return a stable generic problem.
  2. No; it is only correlation metadata.
  3. Prompts can contain secrets, personal data, proprietary context, or prompt-injection content.

Completion checklist

  • Failure categories have stable public mappings.
  • Correlation crosses response and logs.
  • Redaction tests pass.

Primary references

  • FastAPI handling errors
  • Starlette middleware
  • W3C Trace Context