In-memory rate-limit state is never evicted, so unique client IPs grow the process without limit
Description
Happy for this one to be a public issue instead if you prefer. It needs sustained traffic and there is nothing secret in it.
Summary
_in_memory_request_count in guard_core/handlers/ratelimit_handler.py prunes expired timestamps out of a key's deque but never removes the key. Pruning only runs on keys that are touched again, so an address that sends one request and never comes back holds its entry for the life of the process. Checking a key is enough to create it, since the store is a defaultdict. This is the code path taken whenever Redis is disabled or unreachable.
_by_ip_autoban_counts in the same module is the same shape: a defaultdict(int) keyed by client IP, incremented on every rate-limit violation, never cleaned.
Details
Calling _in_memory_request_count directly on 3.13.0: 2 000 addresses sending one request each, then a single request one full window later.
3.13.0: peak 2000 keys -> 2001 keys
patched: peak 2000 keys -> 1 key736 bytes per retained key by tracemalloc, so 100 000 unique addresses is 70 MB that never comes back. Slow, but there is no ceiling: a scan sweep, a botnet, or plain CGNAT churn all feed it. IPBanManager in the same package already handles this with a TTLCache(maxsize=10000).
Impact
Memory exhaustion over time on any deployment running without Redis. Suggested CVSS AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:L (5.3).
Suggested fix
Drop keys with no request inside the current window, at most once per window, and bound the violation counter.
--- a/guard_core/handlers/ratelimit_handler.py
+++ b/guard_core/handlers/ratelimit_handler.py
@@ -84,6 +84,54 @@ async def _redis_request_count(
+_last_idle_sweep: float = 0.0
+
+
+def _sweep_idle_rate_limit_keys(
+ request_timestamps: "defaultdict[str, deque[float]]",
+ window_start: float,
+ current_time: float,
+) -> int:
+ """Drop keys with no request inside the current window.
+
+ Pruning only ever runs on keys that are touched again, so a key created by
+ an IP that never comes back keeps its (empty) deque for the life of the
+ process. Sweeping is O(keys) so it runs at most once per window.
+ """
+ global _last_idle_sweep
+
+ window = max(current_time - window_start, 1.0)
+ since_last = current_time - _last_idle_sweep
+ if 0.0 <= since_last < window:
+ return 0
+ _last_idle_sweep = current_time
+
+ idle = [
+ key
+ for key, timestamps in request_timestamps.items()
+ if not timestamps or timestamps[-1] <= window_start
+ ]
+ for key in idle:
+ del request_timestamps[key]
+ return len(idle)
+
+
+_AUTOBAN_COUNTS_MAX_KEYS = 10000
+
+
+def _prune_autoban_counts() -> None:
+ """Bound the rate-limit violation counter.
+
+ It is keyed by client IP and nothing ever removes an entry, so rotating
+ source addresses grow it without limit. Oldest-inserted entries go first;
+ dict preserves insertion order.
+ """
+ excess = len(_by_ip_autoban_counts) - _AUTOBAN_COUNTS_MAX_KEYS
+ if excess <= 0:
+ return
+ for key in list(_by_ip_autoban_counts)[:excess]:
+ del _by_ip_autoban_counts[key]
+
+
def _in_memory_request_count(
@@ -93,6 +141,8 @@ def _in_memory_request_count(
key = f"{client_ip}:{endpoint_path}" if endpoint_path else client_ip
+ _sweep_idle_rate_limit_keys(request_timestamps, window_start, current_time)
+
while request_timestamps[key] and request_timestamps[key][0] <= window_start:
@@ -131,6 +181,7 @@ async def _feed_rate_limit_autoban(ip: str, config: SecurityConfig) -> None:
ip_counts = {"rate_limit": _by_ip_autoban_counts[ip]}
+ _prune_autoban_counts()The sweep tolerates a clock that moves backwards, which also keeps it order-independent under test.
guard_core/sync/handlers/ratelimit_handler.py gets the same change by hand, inside the lock it already takes. It is in scripts/unasync.py's HAND_MAINTAINED set, and its test has to be too: the sync _in_memory_request_count takes a lock argument the translation cannot invent, so the patch adds one line there and a hand-written sync test beside it.
Four tests each side, using a simulated clock rather than sleeping. Your full suite runs 12 241 passed / 28 failed with both patches applied, against 12 225 / 28 without them - the same 28 either way, on a machine where those already fail. ruff check, ruff format --check and scripts/unasync.py --check pass.
Affected
3.13.0 confirmed; the code shape is long-standing.
Fixed in 3.14.0
Fixed in guard-core 3.14.0 (PyPI), merged in #82 (500d4ef6). In-memory rate-limit stores and the behaviour-tracker per-client stores are LRU-bounded at 10,000 keys (least recently used entry evicted on insert, per window, so multi-window endpoints keep working; the proposed global sweep timer was not taken for that reason), and every 429 response carries Retry-After.