Rate limiting bảo vệ API khỏi spam, brute-force và DDoS.
- Fixed window: đếm requests trong window cố định (0:00-0:15) — dễ bypass bằng cách gửi burst ở cuối window cũ + đầu window mới.
- Sliding window: window trượt theo thời gian thực, chính xác hơn nhưng cần Redis.
express-rate-limitdùng fixed window:rateLimit({ windowMs: 15601000, max: 100, standardHeaders: true, legacyHeaders: false }). - Distributed rate limiting với Redis:
rate-limit-redisstore để share state giữa nhiều server instances — bắt buộc trong cluster/multi-server deployment, nếu dùng in-memory thì mỗi instance có counter riêng, giới hạn thực tế làmax * numInstances. - Rate limit headers trả về client:
RateLimit-Limit,RateLimit-Remaining,RateLimit-Reset(standardHeaders: true). - Limits khác nhau per endpoint: auth endpoints (5 req/15min), API endpoints (100 req/15min), public endpoints (1000 req/15min).
- Per-user limits:
keyGenerator: (req) => req.user?.id || req.ip— authenticated users có limit riêng theo userId thay vì IP.
Pitfall: behind reverse proxy thì req.ip là IP của proxy — cần app.set('trust proxy', 1) để lấy IP thật từ X-Forwarded-For.