784. Rate limit API requests with compound and payload-aware rules
A model API often enforces several limits at once: requests per user per minute, requests per IP, and tokens per user, where a big prompt costs more than a small one.
Write run_limiter(rules, requests). Each rule is a dict with 'field' (the request field the limit is keyed by, such as 'user' or 'ip'), 'limit', 'window' (seconds) and an optional 'cost' naming a numeric request field to use as the cost. Without 'cost', each request costs 1.
Each request is a dict with an int time 't' (non-decreasing) and string or number fields. For each rule, the usage of a key is the total cost of allowed requests with that key whose time is greater than t - window. A request is allowed only if, for every rule, usage plus its own cost is at most limit. An allowed request is recorded in every rule. A rejected request is recorded nowhere.
Return a list of booleans, one per request.
def run_limiter(rules, requests)Example 1
Input: rules = [{'field': 'user', 'limit': 2, 'window': 10}], requests at t = 0, 1, 2, 10, 11 for the same user
Output: [True, True, False, True, True]
Explanation: At t = 10 the request at t = 0 has left the window.
Example 2
Input: with rules [{'field': 'user', 'limit': 100, 'window': 60, 'cost': 'tokens'}], requests of 60, 50 and 40 tokens at t = 0, 1, 2
Output: [True, False, True]
Constraints
- Up to 50,000 requests and 5 rules.
- Times are non-decreasing ints.
Hint 1
Solve one count-based rule first.
Hint 2
Generalise cost to 1 or a request field.
Hint 3
Separate the check pass from the record pass.
Common mistakes
- Recording usage for a request that a later rule rejects.
- Off by one at the window edge: an entry at exactly t - window has expired.
- Sharing one counter across rules that key on different fields.
Understand the idea
Sliding window rate limiting with several keyed rules that must all pass before any of them charge the request.