Design a Sliding-Window Rate Limiter for an AI Hub with Per-Model Quotas
Role: Software Engineer
Category: Software Engineering Fundamentals
Difficulty: medium
Interview Round: Other
Design a rate limiter for an AI hub that routes user requests to many different AI models. Each model has its own request quota: a maximum number of allowed requests within a rolling time window, measured in seconds.
On every incoming request, the limiter decides whether the call for a `(userId, modelId)` pair is allowed, using a sliding window. A request at time `t` is allowed only if the number of previously allowed requests for that same `(userId, modelId)` pair within `(t - windowSeconds, t]` is strictly less than the model's quota. Timestamps arrive in non-decreasing order, and rejected requests do not consume quota.
The limiter must also report per-user and per-model usage counts (counting only allowed requests) so that operators can monitor traffic.
Implement the following methods:
- `registerModel(modelId: str, maxRequests: int, windowSeconds: int)`: register a model with its rate limit, at most `maxRequests` allowed requests within any rolling window of `windowSeconds` seconds. Re-registering an existing model overwrites its limits.
- `allowRequest(userId: str, modelId: str, timestamp: int) -> bool`: return `True` if the request from `userId` to `modelId` at `timestamp` is allowed under the sliding-window quota, otherwise `False`. Only allowed requests count toward future quota and usage stats. If the model is not registered, return `False`.
- `getUserUsage(userId: str) -> int`: return the total number of allowed requests made by `userId` across all models since the limiter was created.
- `getModelUsage(modelId: str) -> int`: return the total number of allowed requests served by `modelId` across all users since the limiter was created.
```hint Structure per pair
Timestamps never go backwards, so the allowed requests for one (userId, modelId) pair form a sorted sequence. Pick a structure that lets you drop the oldest entries cheaply.
```
```hint Window edge
The window is open on the left. Check what should happen to a request that was allowed exactly windowSeconds seconds before the current one.
```
### Examples
Example 1:
```text
registerModel("chat", 2, 10)
allowRequest("alice", "chat", 1) -> True
allowRequest("alice", "chat", 5) -> True
allowRequest("alice", "chat", 8) -> False
allowRequest("bob", "chat", 8) -> True
allowRequest("alice", "chat", 11) -> True
getUserUsage("alice") -> 3
getModelUsage("chat") -> 4
```
At time 8, alice's window `(-2, 8]` already holds two allowed requests (at 1 and 5), so the call is rejected and not recorded. Bob has his own window for the same model. At time 11 the window is `(1, 11]`, which excludes the request at 1 and leaves one, so the call is allowed. Alice has 3 allowed requests in total and the model has served 4.
Example 2:
```text
registerModel("embed", 1, 5)
allowRequest("carol", "vision", 0) -> False
allowRequest("carol", "embed", 0) -> True
allowRequest("carol", "embed", 3) -> False
allowRequest("carol", "embed", 5) -> True
registerModel("embed", 3, 5)
allowRequest("carol", "embed", 6) -> True
getUserUsage("carol") -> 3
getModelUsage("vision") -> 0
getModelUsage("embed") -> 3
```
The model "vision" was never registered, so its request is rejected and counts nowhere. At time 5 the window `(0, 5]` no longer contains the request at 0. After re-registration the quota is 3, and the window `(1, 6]` holds one allowed request, so the call at 6 is allowed.
### Constraints & Assumptions
- `1 <= modelId.length, userId.length <= 20`
- `1 <= maxRequests <= 10^4`
- `1 <= windowSeconds <= 10^6`
- `0 <= timestamp <= 10^9`
- Timestamps across calls to `allowRequest` are non-decreasing.
- At most `10^5` total calls across all methods.
### Clarifying Questions to Ask
- When a model is re-registered with a longer window, should requests allowed under the old limits still count against the new window?
- Is the limiter called from a single thread, or must one instance be safe under concurrent `allowRequest` calls?
- Can the number of distinct (user, model) pairs grow without bound, so that idle windows need to be cleaned up?
### What a Strong Answer Covers
- The data structures for model limits, per-pair windows and usage counters, and the cost of each lookup.
- Exact handling of the window boundary and of rejected requests, which must leave no trace.
- Time and space complexity per method, including an argument for the amortized cost of expiring old requests.
- Edge cases: unregistered models, usage queries for unknown ids, and re-registration with changed limits.
### Follow-up Questions
- How would you make one limiter instance safe when many threads call `allowRequest` at once?
- How would you enforce the same quotas across several gateway servers that each receive part of the traffic?
- A window can hold up to 10,000 timestamps per pair. With millions of active pairs, what would you store instead, and what accuracy would you give up?
- How would you add a global cap per model across all users on top of the per-user quota?
Overview: Design a sliding-window rate limiter for an AI hub where each model sets its own quota per user and operators can query usage per user and per model. It tests picking the right per-pair data structure, getting the window boundary exactly right, and amortized complexity analysis.