Rate limiting
Rate limiting caps how many requests a client may make in a time window to protect your API.
In this page:
Rate limiting
A simple limiter counts requests per client key (such as IP) in a window and answers 429 Too Many Requests when the count is exceeded. In production use express-rate-limit or a shared store like Redis when running several servers.
Send Retry-After to tell clients when to try again.
Note:
In-memory limiters reset when the process restarts and do not share state across servers.
Example: Rate limiting
const hits = new Map();
function allow(key, limit, now) {
const recent = (hits.get(key) || []).filter((t) => now - t < 1000);
recent.push(now); hits.set(key, recent);
return recent.length <= limit;
}
for (let i = 1; i <= 5; i++) console.log("request", i, allow("1.2.3.4", 3, 100 + i) ? 200 : 429);
// Output:
// request 1 200
// request 2 200
// request 3 200
// request 4 429
// request 5 429
⚠️ Run this in your own terminal or Node.js environment.
Related Topics
Common Mistakes
- Limiting only in one process behind a load balancer
- Trusting spoofable headers for the client key
- Not returning Retry-After
Chapter Summary
- Count requests per window
- Respond 429 when exceeded
- Send Retry-After
- Use shared storage in clusters
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: