Step 6: Rate limiting
Without limits one client could create millions of links or hammer your server. A fixed-window rate limiter counts requests per client in a time window and refuses extras with 429 Too Many Requests. The function takes the clock as a parameter, so it can be tested with a fake clock instead of waiting real seconds. This is a very useful testing trick.
// A fixed-window rate limiter: at most 3 requests per client per window.
function makeLimiter(limit, windowMs, now = () => Date.now()) {
const hits = new Map(); // client -> { count, windowStart }
return function allow(client) {
const t = now();
const entry = hits.get(client);
if (!entry || t - entry.windowStart >= windowMs) {
hits.set(client, { count: 1, windowStart: t });
return true;
}
if (entry.count >= limit) return false;
entry.count++;
return true;
};
}
// a fake clock lets us test time-based code instantly and deterministically
let time = 0;
const allow = makeLimiter(3, 1000, () => time);
const results = [];
for (let i = 1; i <= 5; i++) results.push(allow("1.2.3.4"));
console.log("burst of 5:", results);
console.log("other client:", allow("5.6.7.8"));
time = 1500;
console.log("after the window:", allow("1.2.3.4"));
// In the server you would use it like this and answer 429 Too Many Requests:
// if (!allow(req.socket.remoteAddress)) return json(res, 429, { error: "slow down" }, { "Retry-After": "1" });burst of 5: [ true, true, true, false, false ] other client: true after the window: true
Fixed windows have a known weakness (a burst at the end of one window and the start of the next can double the limit), so production systems often use a sliding window or token bucket. The idea of counting per client is the same.
Why pass the clock into makeLimiter as a parameter?
Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.
Tip: use the left and right arrow keys to move between lessons.