Designing an In-Memory Rate Limiter

Difficulty: Medium Patterns: Strategy, Factory, Singleton Asked at: Google, Amazon, Uber, Stripe, Razorpay

💡 Design pattern = a named, reusable solution to a problem that keeps recurring in object-oriented code; each name above links to a primer. The machine coding round guide explains why interviewers grade on this vocabulary.


Functional Requirements

  1. Support multiple rate limiting algorithms — Token Bucket, Sliding Window Log, and Fixed Window Counter
  2. Allow per-client/key rate limiting — each client identified by a unique key gets independent limits
  3. Provide a simple allowRequest(key) API that returns whether a request is allowed or denied
  4. Support configurable limits — max requests and time window size are configurable per limiter instance
  5. Allow runtime algorithm swapping — change the rate limiting strategy without restarting or rebuilding
  6. Expose current usage stats — remaining tokens/quota for a given client key

Non-Functional Requirements

  1. Thread-safety — concurrent requests for the same or different keys must not corrupt internal state
    💡 Thread-safety = the code still behaves correctly when several threads run it at the same instant. Two requests for the same key arriving together must not both see “one token left” and both be allowed.
  2. O(1) decision time — Token Bucket and Fixed Window must decide in constant time; Sliding Window in O(n) worst case bounded by window size
    💡 O(1) = constant time, independent of how much data is held; O(n) = cost grows in step with n, here the number of timestamps still inside the window.
  3. Memory efficiency — automatic cleanup of stale client entries to prevent unbounded memory growth
    💡 Stale entry = per-key state belonging to a client that has stopped calling. Without a cleanup pass the map keeps one entry for every key ever seen, which is a slow memory leak.

Core Entities

Entity Description
RateLimiter Facade that holds a strategy and delegates allow/deny decisions per key
RateLimitStrategy Interface defining the allowRequest and getRemainingQuota contract
TokenBucketStrategy Refills tokens at a steady rate, each request consumes one token
SlidingWindowLogStrategy Tracks exact timestamps of requests, counts those within the window
FixedWindowCounterStrategy Divides time into fixed windows, counts requests per window
ClientState Per-key state (tokens, timestamps, counters) managed internally by each strategy
RateLimiterConfig Holds maxRequests, windowSizeMs, and refill rate parameters
RateLimiterFactory Creates a RateLimiter with the desired algorithm by name

💡 Facade = a single simple entry point placed in front of a more complicated set of objects, so callers just use allowRequest(key) and never touch strategies or per-client state themselves.

💡 Interface = a list of method signatures with no bodies. RateLimitStrategy is one, which is what lets the same allowRequest(key) call run token-bucket, sliding-window or fixed-window maths behind the scenes.


Class Diagram

classDiagram
    class RateLimitAlgorithm {
        <<enumeration>>
        TOKEN_BUCKET
        SLIDING_WINDOW_LOG
        FIXED_WINDOW_COUNTER
    }

    class RateLimiterConfig {
        -int maxRequests
        -long windowSizeMs
        +getMaxRequests() int
        +getWindowSizeMs() long
    }

    class RateLimitStrategy {
        <<interface>>
        +allowRequest(String key) boolean
        +getRemainingQuota(String key) int
    }

    class TokenBucketStrategy {
        -int maxTokens
        -long refillIntervalMs
        -ConcurrentHashMap clientBuckets
        +allowRequest(String key) boolean
        +getRemainingQuota(String key) int
    }

    class SlidingWindowLogStrategy {
        -int maxRequests
        -long windowSizeMs
        -ConcurrentHashMap clientLogs
        +allowRequest(String key) boolean
        +getRemainingQuota(String key) int
    }

    class FixedWindowCounterStrategy {
        -int maxRequests
        -long windowSizeMs
        -ConcurrentHashMap clientCounters
        +allowRequest(String key) boolean
        +getRemainingQuota(String key) int
    }

    class RateLimiter {
        -RateLimitStrategy strategy
        -ReentrantLock lock
        +allowRequest(String key) boolean
        +getRemainingQuota(String key) int
        +setStrategy(RateLimitStrategy)
    }

    class RateLimiterFactory {
        +create(RateLimitAlgorithm, RateLimiterConfig) RateLimiter
    }

    RateLimiter --> RateLimitStrategy
    RateLimiter --> RateLimiterConfig
    RateLimitStrategy <|.. TokenBucketStrategy
    RateLimitStrategy <|.. SlidingWindowLogStrategy
    RateLimitStrategy <|.. FixedWindowCounterStrategy
    RateLimiterFactory --> RateLimiter
    RateLimiterFactory --> RateLimitAlgorithm

💡 In a UML class diagram the solid arrow --> means “holds a reference to”, the dashed arrow <|.. means “implements this interface”, - marks a private field and + a public method.

Key classes:

  • RateLimiterConfig - the knobs (max requests, window size), fixed at construction so every strategy can read them without locking.
  • RateLimitStrategy - the two-method contract every algorithm implements. The decision logic and the per-client state live behind it, which is why swapping strategies swaps both.
  • TokenBucketStrategy / SlidingWindowLogStrategy / FixedWindowCounterStrategy - the three algorithms. Each owns its own ConcurrentHashMap of per-client state in the shape that algorithm needs: a bucket, a deque of timestamps, or a counter.
  • RateLimiter - the single door clients knock on. It owns the active strategy reference and the lock that stops a strategy swap landing mid-request.
  • RateLimiterFactory - the one place that maps an algorithm name to a concrete strategy, so calling code never names a strategy class.

Design Patterns

Pattern Where Why
Strategy RateLimitStrategy interface with three implementations Swap algorithms at runtime. Adding a new algorithm = one new class, zero changes to RateLimiter.
Factory RateLimiterFactory.create(algorithm, config) Decouple client code from concrete strategy instantiation.
Singleton RateLimiter can be used as a singleton per service One shared limiter instance ensures global enforcement across threads.

💡 Strategy pattern = put each algorithm behind a shared interface so the surrounding code can swap it at runtime. Adding a leaky-bucket algorithm is one new class and zero edits to RateLimiter.

💡 Factory pattern = one place that builds objects for you, so callers ask for TOKEN_BUCKET by name instead of knowing which class implements it and how to wire it.

💡 Singleton pattern = exactly one instance of a class exists for the whole process. That matters here because two limiter instances would each count to the limit separately and let through twice the traffic.


Data Structures

Component Structure Why
Token Bucket state ConcurrentHashMap<String, TokenBucket> where bucket has tokens + lastRefillTimestamp O(1) lookup per key, lazy refill on access
Sliding Window Log ConcurrentHashMap<String, Deque<Long>> storing request timestamps Deque allows O(1) append and O(k) eviction of expired entries from front
Fixed Window Counter ConcurrentHashMap<String, WindowCounter> with count + windowStart O(1) increment and reset when window rolls over
Strategy reference Single RateLimitStrategy field in RateLimiter Hot-swappable via setter under lock

💡 ConcurrentHashMap = a hash map built for simultaneous access. It guards small slices of the table instead of the whole map, so requests for different client keys never queue behind each other.