11"""Redis-backed rate limiting middleware with global limits."""
22
3+ import logging
34import math
45import time
56import uuid
1415
1516from lightspeed_agent .config import get_settings
1617
18+ logger = logging .getLogger (__name__ )
19+
1720
1821class RedisRateLimiter :
1922 """Distributed Redis rate limiter using atomic Lua + ZSET sliding windows."""
@@ -140,6 +143,7 @@ async def is_allowed(
140143 unique_member ,
141144 )
142145 except RedisError as exc :
146+ logger .error ("Redis rate limiter check failed: %s" , exc )
143147 raise RuntimeError ("Redis rate limiter check failed" ) from exc
144148
145149 allowed = bool (int (result [0 ]))
@@ -231,6 +235,10 @@ async def dispatch(
231235 try :
232236 allowed , status = await self ._limiter .is_allowed (principal_keys = principals )
233237 except RuntimeError :
238+ logger .error (
239+ "Rate limiter backend unavailable, returning 503 (principals=%s)" ,
240+ principals ,
241+ )
234242 return JSONResponse (
235243 status_code = 503 ,
236244 content = {
@@ -240,6 +248,15 @@ async def dispatch(
240248 )
241249
242250 if not allowed :
251+ logger .warning (
252+ "Rate limit exceeded: principal=%s, limit=%s, "
253+ "requests_minute=%s, requests_hour=%s, retry_after=%s" ,
254+ status .get ("limited_principal" ),
255+ status .get ("exceeded" ),
256+ status .get ("requests_this_minute" ),
257+ status .get ("requests_this_hour" ),
258+ status .get ("retry_after" ),
259+ )
243260 return self ._rate_limit_response (status )
244261
245262 # Process request
0 commit comments