Rate limiting protects APIs from abuse, denial of service, and brute force attacks. It's essential for any public-facing API.
Rate Limiting Algorithms
Token Bucket
Tokens refill at fixed rate. Allows burst traffic.
Sliding Window
Counts requests in rolling time window. Smoother distribution.
Fixed Window
Simple counter reset at intervals. Can allow burst at window edges.
Implementation
// Express.js with express-rate-limit
const rateLimit = require('express-rate-limit');
const limiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100, // 100 requests per window
message: { error: 'Too many requests, please try again later' },
standardHeaders: true,
legacyHeaders: false,
});
app.use('/api/', limiter);
// Stricter limit for authentication
const authLimiter = rateLimit({
windowMs: 60 * 60 * 1000, // 1 hour
max: 5, // 5 login attempts
message: { error: 'Too many login attempts' }
});
app.use('/auth/login', authLimiter);
Response Headers
HTTP/1.1 429 Too Many Requests
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 0
X-RateLimit-Reset: 1640995200
Retry-After: 3600
Best Practices
- Rate limit by user ID, API key, or IP
- Apply stricter limits to sensitive endpoints
- Return proper 429 status with Retry-After
- Consider Redis for distributed rate limiting
December 2024