KatInterview

Build an in-memory rate limiter using token buckets

System DesignModel answer
HardModel answerSystem Designrate-limitingscalabilityalgorithms

Last updated

Design a fast, memory-efficient rate limiter for an API that tracks per-client quotas using a token-bucket algorithm with lazy refill.

You're building an in-memory rate limiter for an HTTP API that needs to enforce per-client quotas.

Requirements

  • Each client (identified by user ID or API key) can make at most N requests in any T-second period
  • Start with a single-server implementation that keeps state in memory
  • Must support:
    • Low latency: sub-millisecond decision time per request
    • Memory efficiency: handle millions of clients without excessive RAM usage
    • Extensibility: the design should translate easily to distributed deployments later

What to cover

Walk through your design in these stages:

  1. Initial approach: Describe a straightforward sliding-window implementation. What data do you store per client? How do you decide whether to allow or reject an incoming request? What are the time and space complexities?

  2. Scalability analysis: At high scale (millions of clients, hundreds of thousands of requests per second), where does the sliding-window design struggle? Be specific about memory and performance bottlenecks.

  3. Optimized design: Redesign using a token bucket with lazy refill:

    • Explain the token bucket model: capacity, refill rate, consumption per request
    • Specify exactly what state you maintain per client
    • Detail the lazy refill strategy: how do you compute token availability on-demand when a request arrives, without background timers?
    • Show the calculation step-by-step for a request at time now, given stored state
    • Compare memory footprint and throughput characteristics to the sliding-window approach
  4. Production considerations:

    • How do you handle concurrent requests for the same client from multiple threads?
    • How do you prevent unbounded memory growth from inactive clients?
    • Sketch how you'd adapt this to run across multiple servers (briefly—focus stays on the core algorithm)

Provide data structures, algorithms, complexity analysis, and trade-offs. Be concrete about edge cases and implementation details.

Hints

Hint 1

The sliding window stores the full request history—can you replace it with a fixed-size summary?

Hint 2

Token buckets refill continuously in theory, but you can calculate the refill mathematically when each request arrives instead of running a timer.

Hint 3

Inactive clients that haven't been accessed in T seconds can be safely evicted—their buckets would be full anyway.