</>
⌕
Mid #rate-limiting#token-bucket#redis#api

Rate limiting: token bucket và các thuật toán khác

⚡ Trả lời nhanh

Rate limiting giới hạn số request mỗi client theo thời gian để chống lạm dụng. Token bucket: xô chứa tối đa N token, nạp r token/giây, mỗi request lấy một token; cho phép burst. Các lựa chọn khác: leaky bucket, fixed window, sliding window log/counter.

Thuật toánƯuNhược
Fixed windowđơn giảnburst gấp đôi ở ranh giới cửa sổ
Sliding window logchính xáctốn bộ nhớ
Sliding window countercân bằngxấp xỉ
Token bucketcho phép burst, rẻcần tinh chỉnh capacity/rate
Leaky bucketđầu ra đềukhông burst
tokens = min(capacity, tokens + (now - last) * rate)
if tokens >= 1: tokens -= 1; allow
else: reject (HTTP 429 + Retry-After)
  • Phân tán: lưu bộ đếm ở Redis, dùng Lua script để thao tác atomic.
  • Khoá theo user id, API key hoặc IP; trả header X-RateLimit-Remaining, Retry-After.
🃏 Ôn bằng flashcard