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

Rate Limiting क्या है

Rate limiting आपके API protect करने के लिए cap करता है कि एक client एक time window में कितनी requests कर सकता है।

In this page:

  1. Rate Limiting

Rate Limiting

एक simple limiter एक window में प्रति client key (जैसे IP) requests count करता है और जब count exceed हो 429 Too Many Requests answer देता है। Production में express-rate-limit या कई servers चलाते वक्त Redis जैसा एक shared store इस्तेमाल करें।

Clients को बताने के लिए कि फिर कब try करें Retry-After भेजें।

Note: In-memory limiters process restart होने पर reset होते हैं और servers के आर-पार state share नहीं करते।

उदाहरण: 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/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. एक load balancer के पीछे सिर्फ एक process में limit करना
  2. client key के लिए spoofable headers पर trust करना
  3. Retry-After return न करना
चैप्टर सारांश
  • प्रति window requests count करें
  • Exceed होने पर 429 respond करें
  • Retry-After भेजें
  • Clusters में shared storage इस्तेमाल करें
🔒

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.