Rate Limiter

Mediumconcurrencystrategytimealgorithms

Design a per-client rate limiter that an API gateway calls on every request from many threads.

Requirements

  1. API. tryAcquire(clientId) returns true and records the request if the client is under its limit. Otherwise it returns false. Every client has its own independent limit.
  2. Three algorithms, chosen by LimiterConfig.algorithm. Each one uses capacity and window.
    • TOKEN_BUCKET
      • A new client starts with capacity tokens, and each allowed request uses one.
      • Tokens refill continuously at capacity per window. With capacity 10 per second, 150 ms adds 1.5 tokens.
      • Fractions accumulate, and a client never holds more than capacity tokens.
    • FIXED_WINDOW
      • At most capacity allowed requests per window. Windows are aligned to the Unix epoch: with a 1-minute window, they start at every whole minute.
      • The count resets when a new window starts.
    • SLIDING_WINDOW_LOG
      • A request is allowed if fewer than capacity allowed requests happened in the last window. A request at time t still counts while now - t < window.
      • Rejected requests are never counted.
  3. Time. Read time only from the Clock passed to Solution.create. The tests freeze it and move it.
  4. Validation.
    • A blank client id throws IllegalArgumentException.
    • Solution.create throws IllegalArgumentException for a null algorithm, a capacity outside 1..100_000, or a window outside 1 ms .. 1 day.

Non-functional requirements

What you get

The judge scores correctness (hidden tests, including multi-threaded ones) and design quality. Each counts for 50%.

com/lld/ratelimiter/Solution.java
com.lld.ratelimiter
Main.java
Solution.java
com.lld.ratelimiter.api
๐Ÿ”’ Algorithm.java
๐Ÿ”’ LimiterConfig.java
๐Ÿ”’ RateLimiter.java
Loading...