0
0
FastAPIframework~8 mins

Protected routes in FastAPI - Performance & Optimization

Choose your learning style9 modes available
Performance: Protected routes
MEDIUM IMPACT
This affects the server response time and user experience by adding authentication checks before serving protected content.
Securing API endpoints with user authentication
FastAPI
from fastapi import FastAPI, Depends
from fastapi.security import OAuth2PasswordBearer
import asyncio

app = FastAPI()
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")

async def verify_token_async(token: str):
    await asyncio.sleep(0)  # simulate async I/O
    return "user123"

@app.get("/protected")
async def protected_route(token: str = Depends(oauth2_scheme)):
    user = await verify_token_async(token)
    return {"message": f"Hello {user}"}
Using asynchronous token verification avoids blocking the event loop, improving responsiveness.
📈 Performance GainNon-blocking token verification reduces response delay and improves INP.
Securing API endpoints with user authentication
FastAPI
from fastapi import FastAPI, Depends
from fastapi.security import OAuth2PasswordBearer

app = FastAPI()
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")

@app.get("/protected")
async def protected_route(token: str = Depends(oauth2_scheme)):
    user = verify_token(token)  # synchronous blocking call
    return {"message": f"Hello {user}"}
Using synchronous blocking token verification delays response and blocks event loop, reducing throughput.
📉 Performance CostBlocks event loop during token verification, increasing response time and INP.
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
Synchronous token verificationN/A (server-side)N/AN/A[X] Bad
Asynchronous token verificationN/A (server-side)N/AN/A[✓] Good
Rendering Pipeline
Protected routes add an authentication step before generating the response, affecting server processing time and delaying content delivery.
Server Processing
Response Generation
⚠️ BottleneckAuthentication verification step
Core Web Vital Affected
INP
This affects the server response time and user experience by adding authentication checks before serving protected content.
Optimization Tips
1Avoid synchronous blocking calls in authentication to keep server responsive.
2Use asynchronous token verification to improve interaction speed.
3Cache authentication results when possible to reduce repeated verification cost.
Performance Quiz - 3 Questions
Test your performance knowledge
What is the main performance impact of synchronous token verification in protected routes?
AIt reduces CSS paint time.
BIt blocks the event loop, increasing response time.
CIt improves Largest Contentful Paint (LCP).
DIt decreases bundle size.
DevTools: Network
How to check: Open DevTools, go to Network tab, filter requests to protected routes, and check response times.
What to look for: Look for longer server response times indicating blocking authentication steps.