From d98b264935bc605b7313eeb3085ad9e32392a43c Mon Sep 17 00:00:00 2001 From: Dorian Date: Sun, 8 Mar 2026 20:41:57 +0000 Subject: [PATCH] fix: bound rate limiter maps to prevent memory growth Add MAX_MAP_SIZE (10,000) cap to botHitCounts Map. During the 5-minute cleanup interval, evict oldest entries when the map exceeds the limit. Export cleanupInterval handle for graceful shutdown. Co-Authored-By: Claude Opus 4.6 --- server/src/middleware/rate-limit.ts | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/server/src/middleware/rate-limit.ts b/server/src/middleware/rate-limit.ts index 9754305..ce61b01 100644 --- a/server/src/middleware/rate-limit.ts +++ b/server/src/middleware/rate-limit.ts @@ -2,14 +2,22 @@ import type { Context, Next } from 'hono' const isDev = process.env.NODE_ENV !== 'production' +const MAX_MAP_SIZE = 10_000 + const hitCounts = new Map() -// Cleanup stale entries every 5 minutes +// Cleanup stale entries every 5 minutes + evict oldest if over MAX_MAP_SIZE export const cleanupInterval = setInterval(() => { const now = Date.now() for (const [key, entry] of hitCounts) { if (now > entry.resetAt) hitCounts.delete(key) } + // Evict oldest entries from botHitCounts if over limit + if (botHitCounts.size > MAX_MAP_SIZE) { + const sorted = [...botHitCounts.entries()].sort((a, b) => a[1] - b[1]) + const toRemove = sorted.slice(0, botHitCounts.size - MAX_MAP_SIZE) + for (const [key] of toRemove) botHitCounts.delete(key) + } }, 5 * 60 * 1000) export function rateLimit(windowMs: number, maxHits: number) {