Video in progress

Strong Middle 🧩 Microservices

How do the rate limiting algorithms (fixed window, sliding window and token bucket) differ, and when do you pick which?

Fixed window is simple, but at a window boundary it lets through twice the limit in a short time. Sliding window smooths that out. Token bucket limits the average rate while allowing a short burst, and for APIs it is often the most natural choice.

📖 Answer

The limit: 100 requests per minute.

Fixed window: a counter per minute (rl:user42:10:15). In Redis it's INCR + EXPIRE, very simple. The problem is at the boundary: 100 requests at 10:15:59 and another 100 at 10:16:00, so 200 requests went through in two seconds.

Sliding window log: store the time of every request (a Redis sorted set) and count the ones from the last 60 seconds. It is exact, but up to 100 entries per user means memory and CPU get expensive.

Sliding window counter: add the current and previous window counters with a weight: previous × (share of the previous window still remaining) + current. Nearly exact and cheap, and many large systems use it.

Token bucket: the bucket holds at most capacity tokens, they refill at rate, and each request takes one token:

// Bucket4j
Bucket bucket = Bucket.builder()
    .addLimit(limit -> limit.capacity(20).refillGreedy(100, Duration.ofMinutes(1)))
    .build();

if (!bucket.tryConsume(1)) {
    throw new TooManyRequestsException();   // 429 + Retry-After
}

A user can send up to 20 requests in one moment (several parallel requests when a page opens is normal), but over the long run never more than 100 per minute. The Redis rate limiter in Spring Cloud Gateway is a token bucket too.

Leaky bucket: a queue that releases requests at a constant rate. Handy for a smooth flow when you call an external API yourself (the provider allows 10 requests per second).

Which one:

  • user and API key limits: token bucket;
  • business quotas like "1000 SMS per day": fixed window is enough, accuracy at the boundary doesn't matter;
  • when you need exact accounting: sliding window.

Return Retry-After with the 429, so the client knows when to retry.