Sequence NODE_233
MediumImplement In-Memory Rate Limiter
Node.js
Technical Specification
Implement a basic in-memory rate limiter that allows only N requests per IP in a time window.
Input/Output Samples
Input:5 requests within 1 minute
Output:Allowed, then blocked
Optimal Logic Path
const buckets = new Map();
function isAllowed(ip, limit = 5, windowMs = 60000) {
const now = Date.now();
const list = (buckets.get(ip) || []).filter(
(ts) => now - ts < windowMs
);
if (list.length >= limit) {
buckets.set(ip, list);
return false;
}
list.push(now);
buckets.set(ip, list);
return true;
}
module.exports = { isAllowed };Architectural Deep-Dive
We track timestamps per IP and enforce a maximum count within a given timeframe.