Rate Limiter · 9004
A medium low-level design interview question on strategy, factory, dependency injection. 8 scenario tests.
SYNOPSIS
interviewer: Design a rate limiter.
An in-process limiter in front of an API. Each request asks: is this client allowed right now? About 30 minutes.
QUESTIONS TO ASK
Interviews start vague on purpose. Strong candidates ask before they draw; in the studio the interviewer answers these and the answers become your requirements.
- Is the limit per client or global?
- Which algorithm should we use?
- What are the limits?
- How do we get the time?
- How many clients?
- Does it run across many servers?
- Do we return retry-after?
DESCRIPTION
The full statement, as the studio shows it at the implement step.
Design an in-process rate limiter for an API: each client may make a limited number of requests, and the limiting algorithm must be swappable.
requirements
- Two algorithms, both with tryAcquire(now) → boolean (now in ms):
TokenBucket({ capacity, refillPerSec })
Starts full. Each allowed request takes one token. Tokens refill continuously at refillPerSec (fractions count) and never exceed capacity. A request is allowed when at least one whole token is there.
SlidingWindowLog({ limit, windowMs })
Allows a request when fewer than `limit` allowed requests happened in the window (now - windowMs, now], i.e. a request made at time T stops counting at T + windowMs exactly. Denied requests are not counted.
- RateLimiter(createStrategy) keeps one strategy instance per client, created on first use with createStrategy(), and answers allow(clientId, now) → boolean.
rules
- TokenBucket: capacity and refillPerSec must be positive, otherwise throw an Error containing "capacity" or "refill" respectively.
- SlidingWindowLog: limit and windowMs must be positive, otherwise throw an Error containing "limit" or "window".
- Time never goes backwards in the tests.
think about
- The log stores timestamps: how much memory per client at limit 10,000? Which algorithm would you run for 10 million clients?
GRADING
The studio runs the interview in seven steps (clarify, entities, class diagram, patterns, sequence, implement, review) and a coach grades each one live: the core objects you found, the relations between them (ownership vs. use, the right end of the diamond), responsibilities, whether your patterns really have the shape of the pattern, and a sequence diagram of the main use case. Then you implement it in JavaScript and run its 8 scenario tests in your browser. The review gives a score out of 100, a hire signal and a reference design to compare.
FOLLOW-UPS
What the interviewer asks when you finish early:
- Run it across 20 API servers: where does the state live, and what does a request cost you now? (Redis, Lua scripts, approximate counters.)
- Return "retry after N ms" for denied requests.