Skip to content
BytePatterns

Rate-Limit Tiers for an API Gateway

MediumSystem Design Cases#rate-limiting#sliding-window-log~25m

Problem

An API gateway limits each key according to its plan. A tier is a list of (window, limit) rules in seconds, for example free allows 2 requests per second and 5 per minute. A request at time t is allowed only if, for every rule of its key's tier, fewer than limit allowed requests from that key fall in the window (t - window, t]. Rejected requests do not count against later ones. Given the tiers, a map from key to tier, and the requests as (time, key) sorted by time, return a dict from each key to [allowed, rejected]. There are up to 1,000,000 requests.

Examples

Input:  tiers = {"free": [(1, 2), (60, 5)], "pro": [(1, 5), (60, 100)]},
        3 free and 3 pro requests at 0, 2 free at 1, 2 free at 2, 1 free at 61
Output: {'k-free': [6, 2], 'k-pro': [3, 0]}
Why:    free loses 1 request to the per-second rule at 0 and 1 to the per-minute rule at 2
Input:  tiers = {"free": [(10, 1)]}, requests from "a" at 0, 9, 10, 19, 20
Output: {'a': [3, 2]}
Why:    the window is half-open, so a request at 10 no longer sees the one at 0
Input:  a "pro" key that sends no requests
Output: {'idle': [0, 0]}
Why:    edge case, every key appears in the result even when it is silent

Hints

0 / 3

Stuck on the idea rather than the code? Design a Rate Limiter covers it.