← Back to Node.js Course | Chapter 8: Working with APIs | Lesson 7 of 7

Rate limiting

Rate limiting caps how many requests a client may make in a time window to protect your API.

In this page:

  1. Rate limiting

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

javascript
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
  1. Limiting only in one process behind a load balancer
  2. Trusting spoofable headers for the client key
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.