Lesson 29 • Advanced
Rate Limiting & Throttling 🚦
Protect your API from abuse with token bucket rate limiting, sliding windows, IP controls, and Redis-backed distributed throttling.
What You'll Learn in This Lesson
- • Why rate limiting is essential for API security
- • Token bucket algorithm implementation
- • Per-user, per-endpoint, and per-IP limiting
- • Sliding window vs fixed window trade-offs
- • Redis-backed distributed rate limiting
Token Bucket Rate Limiter
The token bucket algorithm is the most popular rate limiting approach. Each client has a bucket of tokens that refills at a constant rate. Each request consumes one token. When the bucket is empty, requests are denied until tokens refill — allowing short bursts while enforcing long-term limits.
Try It: Token Bucket
Build a rate limiter with capacity, refill rate, and response headers
// Building a Rate Limiter
console.log("=== Why Rate Limit? ===");
console.log();
console.log("Without limits, a single client can:");
console.log(" • Crash your server with thousands of requests");
console.log(" • Brute-force passwords by trying millions of combinations");
console.log(" • Scrape your entire database through the API");
console.log(" • Rack up massive server costs");
console.log();
console.log("=== Token Bucket Algorithm ===");
console.log();
console.log("Imagine a bucket th
...Advanced Strategies
Production APIs need different limits for different endpoints — login attempts are stricter than search queries. Use sliding windows for smoother rate enforcement, IP blocklists for known bad actors, and Redis for rate limiting across multiple servers.
Try It: Advanced Rate Limiting
Per-endpoint limits, sliding windows, IP controls, and Redis implementation
// Advanced Rate Limiting Strategies
console.log("=== Per-User vs Per-IP Limiting ===");
console.log();
class RateLimiterStore {
constructor() { this.windows = new Map(); }
check(key, limit, windowSec) {
let now = Date.now();
let windowKey = key + ":" + Math.floor(now / (windowSec * 1000));
let count = this.windows.get(windowKey) || 0;
count++;
this.windows.set(windowKey, count);
return {
allowed: count <= limit,
count: count,
limit: limit,
...⚠️ Common Mistakes
Retry-After so clients know when to try again instead of hammering your server.📋 Quick Reference — Rate Limiting
| Algorithm | Best For |
|---|---|
| Token Bucket | Allows bursts, smooth long-term rate |
| Fixed Window | Simple, resets at interval boundaries |
| Sliding Window | Smooth, no burst at boundary |
| Leaky Bucket | Constant output rate, queues bursts |
🎉 Lesson Complete!
Your APIs are now protected! Next, learn to offload heavy work with background queues and message brokers.
Sign up for free to track which lessons you've completed and get learning reminders.