0
0
FastAPIframework~8 mins

Trusted host middleware in FastAPI - Performance & Optimization

Choose your learning style9 modes available
Performance: Trusted host middleware
MEDIUM IMPACT
This affects the server response time and security by filtering requests based on allowed host headers before processing.
Filtering requests by allowed host to prevent host header attacks
FastAPI
from fastapi.middleware.trustedhost import TrustedHostMiddleware

app = FastAPI()
app.add_middleware(TrustedHostMiddleware, allowed_hosts=['example.com', 'www.example.com'])
Built-in middleware is optimized and integrated, performing host validation efficiently before request handling.
📈 Performance GainMinimal overhead, avoids extra middleware logic, reduces risk of errors
Filtering requests by allowed host to prevent host header attacks
FastAPI
app = FastAPI()

from fastapi import Request, Response

@app.middleware("http")
async def check_host(request: Request, call_next):
    host = request.headers.get('host')
    if host not in ['example.com', 'www.example.com']:
        return Response('Invalid host', status_code=400)
    response = await call_next(request)
    return response
Custom middleware runs on every request and does string checks manually, which can be error-prone and less optimized.
📉 Performance CostAdds extra async middleware layer, triggers 1 additional header read per request
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
Custom host check middlewareN/A (server-side)N/AN/A[X] Bad
FastAPI TrustedHostMiddlewareN/A (server-side)N/AN/A[OK] Good
Rendering Pipeline
Trusted host middleware intercepts HTTP requests early in the server pipeline to validate the Host header before routing or processing.
Request Filtering
Routing
⚠️ BottleneckRequest Filtering stage due to header validation
Optimization Tips
1Use built-in TrustedHostMiddleware to efficiently validate host headers.
2Avoid custom host validation middleware to reduce errors and overhead.
3Trusted host checks add minimal server processing time but improve security.
Performance Quiz - 3 Questions
Test your performance knowledge
What is the main performance impact of using TrustedHostMiddleware in FastAPI?
AAdds large bundle size to the frontend assets
BSignificant increase in page rendering time in the browser
CSlight increase in request processing time due to host header validation
DTriggers multiple DOM reflows on the client side
DevTools: Network
How to check: Open DevTools Network panel, inspect request headers and response times for requests with valid and invalid Host headers.
What to look for: Look for quick 400 responses on invalid hosts and minimal added latency on valid requests.