Adds a new "Custom Middleware Examples" section to docs/en/docs/advanced/middleware.md
covering five production-ready patterns: timing middleware (X-Process-Time header),
request ID middleware (UUID tracing), rate limiting middleware (sliding window per IP),
combining multiple middlewares with ordering notes, and accessing request.state in
route handlers.
To see other available middlewares check [Starlette's Middleware docs](https://www.starlette.dev/middleware/) and the [ASGI Awesome List](https://github.com/florimondmanca/awesome-asgi).
The following examples demonstrate common middleware patterns used in production FastAPI applications. Each middleware is self-contained and can be added directly to your application.
### Timing Middleware { #timing-middleware }
Track how long each request takes to process. The elapsed time is added as an `X-Process-Time` response header, which is useful for performance monitoring and APM tools.
A simple in-memory rate limiter that restricts each IP address to a configurable number of requests per time window. For production use, replace the in-memory store with Redis.
Each `BaseHTTPMiddleware` layer adds a small overhead due to Python async context switching. For high-throughput applications (> 1000 req/s), consider using Starlette's `@app.middleware("http")` decorator or pure ASGI middleware for the most performance-critical layers.
///
### Accessing Middleware State in Route Handlers { #accessing-middleware-state }
State set on `request.state` in middleware is accessible throughout the entire request lifecycle: