Rate Limiting and Abuse Protection
Rate limiting stops brute force, credential stuffing, scraping, spam and cost-based DoS (expensive endpoints, SMS/email sending).
Packages
| Package | Use |
|---|---|
express-rate-limit | Simple per-IP limits |
rate-limit-redis | Shared store, so limits work across multiple servers |
rate-limiter-flexible | Advanced: per user + IP, login lockout, progressive delays |
express-slow-down | Slows responses instead of blocking |
✅ Global + strict login limit
const rateLimit = require('express-rate-limit');
app.set('trust proxy', 1); // behind a load balancer, or every user shares one IP
app.use(rateLimit({ windowMs: 15 * 60 * 1000, limit: 300, standardHeaders: 'draft-7', legacyHeaders: false }));
const loginLimiter = rateLimit({ windowMs: 15 * 60 * 1000, limit: 5, skipSuccessfulRequests: true });
app.post('/login', loginLimiter, login);✅ Lockout per username (stops attacks spread over many IPs)
const { RateLimiterRedis } = require('rate-limiter-flexible');
const byUser = new RateLimiterRedis({ storeClient: redis, keyPrefix: 'login_fail', points: 10, duration: 3600 });
// on failed login
await byUser.consume(email).catch(() => { throw new Error('Too many attempts, try later'); });
// on success
await byUser.delete(email);Other abuse controls
- CAPTCHA (hCaptcha, Cloudflare Turnstile) after N failures
- Timeouts:
server.requestTimeout, DB query timeouts - Pagination limits:
?limit=1000000must be capped - GraphQL: limit query depth and complexity (
graphql-depth-limit) - ReDoS: avoid catastrophic regexes on user input; check them with
safe-regex
Checklist
- Global limit + strict limits on login, signup, password reset, OTP and SMS endpoints
- Redis store when there is more than one instance
-
trust proxyset correctly - Return
429 Too Many Requestswith aRetry-Afterheader - Cap page size and request body size