Preparing your design workspace

Loading the problem and your saved attempt…

Design and Implement a Multi-Window Sliding Rate Limiter

Limit each user, endpoint, and IP combination to per-second, per-minute, and per-hour request counts at the same time with an exact sliding window, then implement the check.

Design and implement a rate limiter that sits in front of an API server. Every incoming request carries a user ID, the endpoint it calls, and the client IP address.

These three values together form the rate-limit key, so the same user calling the same endpoint from two different IP addresses is counted as two separate keys.

Three limits apply at the same time: a maximum number of requests per second, per minute, and per hour. A request is allowed only if it stays within all three. Use a sliding window rather than fixed clock periods: a limit of 100 per minute means at most 100 requests in any 60 seconds in a row, not per calendar minute.

Start by naming the common rate-limiting algorithms and how they differ.

For this exercise, assume the following.

- Limits are configuration. Each endpoint may set its own three numbers, and an endpoint without its own limits uses a default set, such as 5 per second, 100 per minute, and 1,000 per hour. - Time is measured in milliseconds by a clock the limiter is given.

A request made at time t counts against a window of length W until time t + W. At exactly t + W it no longer counts. - Counts are exact: the limiter never lets more requests through than a limit allows in any window. - Only allowed requests count.

An allowed request counts against all three windows; a rejected request counts against none. - Each request gets an answer: allowed or rejected.

A rejected answer also says which limit or limits were hit and how many milliseconds the caller must wait before the same request could be allowed, if no other request for that key is allowed in the meantime. - One server process runs the limiter, and requests for the same key can arrive on many threads at once.

Sharing limits across several servers, keeping counts across restarts, and changing limits while the server runs are out of scope.

Design the objects, their interfaces, and the request flow, then implement the core check.