- Joined
- Threads
- 12
- Posts
- 13
Stop one client from hammering your API
A token bucket gives each client N requests that refill over time. It allows short bursts and blocks floods.
A token bucket gives each client N requests that refill over time. It allows short bursts and blocks floods.
JavaScript:
const buckets = new Map();
function rateLimit({ capacity = 20, refillPerSec = 1 } = {}) {
return (req, res, next) => {
const now = Date.now();
const b = buckets.get(req.ip) ?? { tokens: capacity, last: now };
b.tokens = Math.min(capacity, b.tokens + ((now - b.last) / 1000) * refillPerSec);
b.last = now;
buckets.set(req.ip, b);
if (b.tokens < 1) {
res.set('Retry-After', String(Math.ceil((1 - b.tokens) / refillPerSec)));
return res.status(429).json({ error: 'Too many requests' });
}
b.tokens -= 1;
next();
};
}
app.use('/api', rateLimit({ capacity: 30, refillPerSec: 0.5 }));
You must reply to see the hidden content. Consider upgrading your account to increase your reply limit.