โ† All posts
RELEASE September 23, 2026 ยท 5 min read

FastAPI, measured from the outside of the app

SR
Sentrinel Team
Product & engineering

Sentrinel now has a FastAPI SDK. One middleware, and every request, error, log line and trace your service produces arrives correlated โ€” a log line opens the request that wrote it, an error opens the user it happened to.

import os

from fastapi import FastAPI
from sentrinel_fastapi import SentrinelMiddleware

app = FastAPI()
app.add_middleware(
    SentrinelMiddleware,
    server_url="https://api.sentrinel.dev",
    app_name="orders",
    module="api",
    env="prod",
    api_key=os.environ["SENTRINEL_API_KEY"],
)

It works the same on plain Starlette and on anything built on either, and it installs nothing: no runtime dependencies at all. The rest of this post is about the decisions that shaped it, and the bug that only appeared once a whole service ran end to end.

Not BaseHTTPMiddleware

The obvious way to write FastAPI middleware is Starlette's BaseHTTPMiddleware: you get a request, you await call_next(request), you get a response. It is also the way to break things for the people you are meant to be helping. It runs the app in a separate task, so request bodies read in the middleware are gone for the endpoint, streaming responses are buffered, and context variables set inside the endpoint never make it back out.

So the middleware is plain ASGI. It wraps receive and send, watches the messages go past, and forwards every one untouched. A streaming response streams. An upload still reaches your endpoint. The status and the bytes are read off the http.response.start and body messages as they leave, which is also the honest place to stop the clock: the duration is what the caller waited, ending with the last byte, not when your handler returned.

That last point has a consequence people are sometimes surprised by: background tasks are not in the request's time. Starlette runs them after the response inside the same call. The user was not waiting for them, so the number does not include them.

Routes as FastAPI names them

An endpoint list is only useful if /orders/1042 and /orders/1043 are one row. FastAPI already knows they are โ€” it matched both to /orders/{order_id} โ€” so the SDK asks it rather than guessing. The matched route lands on the ASGI scope, and its path_format is reported as /orders/:order_id, the way every other Sentrinel SDK writes it.

Routers and mounts are where a naive version goes wrong. include_router(prefix="/v2") is already in the path format, but app.mount("/admin", sub_app) is not: the mounted app's route only knows its own half. The SDK reconstructs the prefix from the difference in root_path between the scope it was entered with and the one the route matched in, so /admin/users/{id} does not merge with a top-level /users/{id}. On plain Starlette, where there is no path_format, it finds the endpoint in the router instead.

A request that matched nothing โ€” a scanner walking /wp-admin/โ€ฆ โ€” has its ids collapsed, so 404 noise registers one endpoint rather than one per URL.

Every 4xx and 5xx is an error

FastAPI turns most failures into responses before a middleware sees anything. An HTTPException(404, detail="no product 1010") never raises through the stack; neither does a request that fails validation. If the SDK only recorded exceptions, the Errors page would show server crashes and nothing a client ever hit.

So every response at 400 or above is recorded, with a message taken from the body when it is JSON: an HTTPException's detail, or โ€” for a validation failure โ€” one line per field, body.product_id: Input should be a valid integer. That is the same rule the Node plugin and the Django SDK follow, so an error means the same thing whichever service reported it.

Exceptions your own handlers turn into responses keep their stack if you say so:

@app.exception_handler(PaymentError)
async def payment_failed(request, exc):
    capture_exception(exc, request=request)
    return JSONResponse({"detail": "payment failed"}, status_code=402)

The error is recorded with the status the caller actually received โ€” a 402 here โ€” and the response is not counted a second time.

Sync and async alike

FastAPI runs plain def endpoints in a thread pool. Anything request-scoped has to survive that hop, or a log line written in a sync endpoint belongs to no request. The request's context lives in a contextvar, which FastAPI copies into the worker thread, so logger.info(...) inside a sync endpoint carries the request id, the user and the trace like any other.

@traced works on async def and times the awaited work rather than the creation of the coroutine, and wrapping an httpx client's transport makes every outgoing call a span that carries traceparent onward:

rates = httpx.AsyncClient(transport=async_httpx_transport())

A tap in the phone app, the Node gateway it hit and the FastAPI service behind that are one trace.

One core, two SDKs

Most of this is not FastAPI-specific. Batching, retries, masking, sampling, custom metrics, the trace model and the error rows were already written for Django. Rather than fork them, both SDKs share one core: it lives in the Django package, and a small script copies it into the FastAPI one. A test fails if the copies drift. Only the middleware, route resolution and the tunnel are framework code.

That is also why both are tested on the oldest and newest versions they claim โ€” FastAPI 0.100 through 0.141, Django 3.1 through 6.1, Python 3.9 through 3.14 โ€” on every change to either.

The bug the example service found

The tests passed. Then we ran the example service end to end: it wrote a log line at startup, and sent nothing for the rest of its life.

Starlette builds its middleware stack lazily, on the first request. The log handler was attached at import time, and its first record asked for the shared collector โ€” which did not exist yet, so it was created from the environment, which in that app was empty. When the middleware was finally built with the real settings, the collector already existed, unconfigured, and the first one wins.

The fix is small and specific: an unconfigured collector adopts the first configured settings it is offered. The lesson was the usual one. A test that builds the app and sends a request in the same breath will never find an ordering bug that needs a log line in between.

Try it

pip install "git+https://github.com/Zaga-ltd/sentinel_packages.git#subdirectory=sentrinel_fastapi"

The full reference is at docs.sentrinel.dev/reference/fastapi, and a complete example service โ€” products, quotes, a flaky endpoint and an outgoing call โ€” is in the repository under examples/fastapi-app.