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
- Keep the fixed-window limiter's behavior: allow up to the configured number of requests per client IP per WINDOW_MS window, and respond 429 once a client exceeds it.
- Make the per-window cap adjustable at runtime: `setMaxRequests(n)` (wired to the admin config endpoint) updates the limit so ops can retune it during an incident without a redeploy.
- A call to `setMaxRequests` must take effect on requests handled by the already-created limiter — no process restart, no re-creating the middleware.
Files touched
- src/middleware/rateLimiter.js
--- 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 };