Make the rate limit adjustable at runtime

Node · Node · intermediate · modification

Makes the rate limit adjustable at runtime. Replaces the hardcoded `MAX_REQUESTS` constant with a module-level `maxRequests` plus a `setMaxRequests()` setter wired to the admin config endpoint, so ops can retune the cap during an incident without a redeploy. The fixed-window counting logic is unchanged.

createRateLimiter() is called once at boot and the returned middleware stays mounted for the whole process lifetime; setMaxRequests() is invoked later, at runtime, from the admin config endpoint.

Requirements

Files touched

--- src/middleware/rateLimiter.js
 const WINDOW_MS = 60_000;
-const MAX_REQUESTS = 100;
+
+// Requests allowed per IP per window. Adjustable at runtime by ops via
+// setMaxRequests() (wired to the admin config endpoint) so the cap can be
+// tuned during an incident without a redeploy.
+let maxRequests = 100;
+
+function setMaxRequests(next) {
+  maxRequests = next;
+}
 
 // Fixed-window limiter: counts hits per client IP within the current window.
 function createRateLimiter() {
+  const limit = maxRequests;
   const hits = new Map();
   let lastSweep = Date.now();
     }
 
-    if (entry.count >= MAX_REQUESTS) {
+    if (entry.count >= limit) {
       res.status(429).json({ error: 'Too many requests' });
       return;
 }
 
-module.exports = { createRateLimiter };
+module.exports = { createRateLimiter, setMaxRequests };
 

Review this PR

Node practice