LLD Guide · Module 2: Problem prep · Lesson 02.04

Prep: Sliding Window Rate Limiter

Shared state in Redis, one atomic decision per request, and data that cleans itself up.

By Cruscible Engineering · Published

A rate limiter makes one decision, millions of times: allow or deny. The decision is only correct if counting and recording happen as one step.

This lesson prepares you for Build a Sliding Window Rate Limiter. It doesn't solve it.

1. What the rate limiter contract asks for

A limiter that allows at most maxRequests per user in any window of windowSizeSeconds, sliding, not fixed. All state lives in Redis, so several app instances would share the same limits.

MethodReturns / does
configure(maxRequests, windowSizeSeconds)sets the limits; may be called again, and existing counts are judged by the new limits
allowRequest(userId)true if allowed (and it counts), false if over the limit
getRemainingRequests(userId)how many more are allowed now; never negative
reset(userId)clears that user's data

Targets: up to 10,000 distinct users, 10,000 operations a second, P99 under 5 ms.

Figure: A sliding window: requests older than the window stop counting as it moves

2. Lessons to read before the rate limiter

3. Rate limiter design decisions to make first

  1. What's in one user's key? What is the score, and what is the member, and how do two requests in the same millisecond stay two entries?
  2. Which steps must be one atomic unit? List the Redis commands allowRequest needs, and which of them the RedisClient has directly.
  3. What does a denied request write? Should a rejected request take a place in the window?
  4. How does data expire for users who stop sending? What TTL, set when?
  5. What does getRemainingRequests count? Only entries inside the current window, so it must drop old ones (or ignore them) too.
  6. What does configure mean for data already stored? The contract says existing counts are judged against the new limits.

4. Rate limiter pitfalls

⚠️ Trap: no in-process counters. A ConcurrentHashMap limiter might pass by hand, but it breaks the "shared across instances" requirement.

⚠️ Trap: a fixed window (one counter per minute) isn't a sliding window: it lets up to twice the limit through around a boundary.

⚠️ Trap: ZREMRANGEBYSCORE, ZCARD and ZADD as separate calls can let concurrent requests exceed the limit. The RedisClient has no ZREMRANGEBYSCORE anyway: that's a hint to use eval.

⚠️ Trap: userId may be an empty string. It's still a valid user, with its own key.

Before you submit

Further reading

After you've tried it

Submit first. The full walkthrough of one solution: Building a Sliding Window Rate Limiter with Redis.

Open the problem