Rate Limiting and API Protection in Node.js
Without rate limits, one buggy client, scraper, or attacker can overwhelm your API — or, with AI endpoints, run up a huge bill.
Algorithms
- Fixed window — 100 requests per minute; simple, but bursts at window edges
- Sliding window — smoother counting over a rolling period
- Token bucket — allows short bursts while enforcing an average rate
Quick Start With Express
import rateLimit from 'express-rate-limit';
app.use('/api/', rateLimit({
windowMs: 60 * 1000,
limit: 100,
standardHeaders: 'draft-7',
legacyHeaders: false,
}));
app.use('/api/login', rateLimit({ windowMs: 15 * 60 * 1000, limit: 10 }));
Distributed Limits
With multiple instances, in-memory counters don't work. Use a Redis store so all instances share counts.
Limit by the Right Key
- Per IP for anonymous endpoints
- Per user or API key for authenticated endpoints
- Per tenant for multi-tenant SaaS
- Stricter limits for expensive endpoints (search, AI generation, exports)
Respond Properly
Return 429 Too Many Requests with a Retry-After header so clients can back off.
Beyond Rate Limiting
- Request body size limits
- Timeouts
- Input validation
- Bot protection and WAF at the edge
- Budget caps on AI usage per user
Rate limits are a kindness to your servers, your database, and your well-behaved users.