Rate Limiter
Mediumconcurrencystrategytimealgorithms
Design a per-client rate limiter that an API gateway calls on every request from many threads.
Requirements
- API.
tryAcquire(clientId)returnstrueand records the request if the client is under its limit. Otherwise it returnsfalse. Every client has its own independent limit. - Three algorithms, chosen by
LimiterConfig.algorithm. Each one usescapacityandwindow.TOKEN_BUCKET- A new client starts with
capacitytokens, and each allowed request uses one. - Tokens refill continuously at
capacityperwindow. With capacity 10 per second, 150 ms adds 1.5 tokens. - Fractions accumulate, and a client never holds more than
capacitytokens.
- A new client starts with
FIXED_WINDOW- At most
capacityallowed 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.
- At most
SLIDING_WINDOW_LOG- A request is allowed if fewer than
capacityallowed requests happened in the lastwindow. A request at timetstill counts whilenow - t < window. - Rejected requests are never counted.
- A request is allowed if fewer than
- Time. Read time only from the
Clockpassed toSolution.create. The tests freeze it and move it. - Validation.
- A blank client id throws
IllegalArgumentException. Solution.createthrowsIllegalArgumentExceptionfor a null algorithm, a capacity outside1..100_000, or a window outside1 ms .. 1 day.
- A blank client id throws
Non-functional requirements
- Never allow more than the limit, even when 100 threads call
tryAcquirefor the same client at the same instant. - Clients must not block each other: no single global lock.
- Memory per client stays bounded (a sliding log keeps at most
capacitytimestamps). - Adding a fourth algorithm, such as a sliding-window counter, should mean adding a class, not editing a
switchin the service.
What you get
api/holds the contract the hidden tests use. It's read-only.Solution.create(config, clock)is where you build your limiter.Mainis your demo. The judge runs it.
The judge scores correctness (hidden tests, including multi-threaded ones) and design quality. Each counts for 50%.