fix(api): add no-cache middleware to prevent Cloudflare from caching API responses
Some checks failed
Aegis CI / lint-and-test (push) Has been cancelled
Some checks failed
Aegis CI / lint-and-test (push) Has been cancelled
Root cause: Cloudflare CDN was caching empty/error API responses from /api/v1/metrics/* endpoints during the backend startup window (502 errors). Subsequent requests were served from Cloudflare edge cache, never reaching nginx or the backend, so the dashboard always showed empty metrics data. NoCacheAPIMiddleware adds Cache-Control: no-store + Pragma: no-cache to all /api/ responses so Cloudflare and browsers never cache them.
This commit is contained in:
@@ -107,6 +107,24 @@ app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)
|
||||
|
||||
app.add_middleware(RequestContextMiddleware)
|
||||
|
||||
|
||||
# ── No-cache middleware for all /api/ responses ───────────────────────────
|
||||
# Prevents Cloudflare and browser caches from storing API responses,
|
||||
# which would cause stale/empty data to be served after backend restarts.
|
||||
from starlette.middleware.base import BaseHTTPMiddleware
|
||||
from starlette.responses import Response as StarletteResponse
|
||||
|
||||
class NoCacheAPIMiddleware(BaseHTTPMiddleware):
|
||||
async def dispatch(self, request: Request, call_next):
|
||||
response = await call_next(request)
|
||||
if request.url.path.startswith("/api/"):
|
||||
response.headers["Cache-Control"] = "no-store, no-cache, must-revalidate"
|
||||
response.headers["Pragma"] = "no-cache"
|
||||
return response
|
||||
|
||||
app.add_middleware(NoCacheAPIMiddleware)
|
||||
|
||||
|
||||
# ── Domain exception → HTTP mapping ──────────────────────────────────────
|
||||
app.add_exception_handler(DomainError, domain_exception_handler)
|
||||
|
||||
|
||||
Reference in New Issue
Block a user