Trung BìnhBảo Mật iconBảo Mật

Rate limiting strategies: Fixed window vs Sliding window vs Token bucket?

Token bucket cho phép bursts; sliding window không có burst issue của fixed window; dùng Redis-based implementation (Upstash) cho distributed deployment — in-memory rate limiter chỉ work trên single instance.

  • Rate limiting ngăn abuse, brute-force, DoS. Fixed window: đếm requests trong window cố định (ví dụ 0:00-0:59, 1:00-1:59).
  • Dễ implement, dễ bypass: gửi 100 req cuối window cũ + 100 req đầu window mới = 200 req trong 2 giây. Sliding window: track timestamps của requests trong rolling time window — không có burst issue của fixed window; cần store per-user timestamps trong Redis (sorted set). ZADD key timestamp timestamp; ZREMRANGEBYSCORE key 0 (now-window); ZCARD key để đếm requests. Token bucket: user có bucket tokens, mỗi request tiêu 1 token, tokens được refill theo rate (1 token/giây).
  • Cho phép short bursts (bucket full = burst capacity) nhưng sustainable rate bị limit. Leaky bucket: requests vào queue, xử lý ở fixed rate — smooth output không có bursts; tốt cho APIs cần predictable throughput.
  • Implementation: @upstash/ratelimit (Redis-based, serverless-friendly); express-rate-limit (in-memory mặc định, rate-limit-redis cho distributed); ioredis + custom script.
  • Differentiated limits: /api/auth/login (5 req/15min per IP), /api/* (100 req/min per user), public endpoints (1000 req/min).

Pitfall: in-memory rate limiter không work trong multi-instance deployment — mỗi instance có counter riêng, limit thực tế là n×limit.

Xem toàn bộ Bảo Mật cùng filter theo level & chủ đề con.

Mở danh sách Bảo Mật