Docs học tập
Backend nền tảng

I6 · Thiết kế LLD: Rate Limiter

interface RateLimiter { boolean isAllowed(userId) }.

I6 · Middle

Mỗi user được phát một xô token riêng; lấy token để đi, xô tự nạp lại theo thời gian.

Cốt lõi

  • interface RateLimiter { boolean isAllowed(userId) }.
  • TokenBucket implements RateLimiter: tokens, capacity, refillRate, lastRefill, consume().
  • Map<userId, TokenBucket>: UserRequest → RateLimiter → TokenBucket.

Đánh đổi

Cần thread-safe (synchronized/atomic). Phân tán thì chuyển state sang Redis.

Trong thực tế

Token Bucket tại API Gateway 100 req/phút.

Bug thường gặp

Cập nhật token không đồng bộ giữa các thread → hai request cùng lấy được token cuối cùng.

Tự hỏi lại

Có thể tính refill "lười" dựa trên lastRefill thay vì chạy timer nền không?

On this page