From 71141d9901400c6b3c1b4ea86e49ba819fd47748 Mon Sep 17 00:00:00 2001 From: kitos Date: Tue, 2 Jun 2026 10:12:13 +0200 Subject: [PATCH] fix(api): add no-cache middleware to prevent Cloudflare from caching API responses 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. --- backend/app/main.py | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/backend/app/main.py b/backend/app/main.py index 81db6e2..0e04580 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -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)