17/32
Part 4 of 6 · Deques and rate limitsLearn and do

Drop a request at exactly t + window, and never store a denied one

Three details decide whether the limiter is right:

  • The drop is the rule turned around. A request counts while now < t + window, so it goes when t + window <= now. Write < there, and a request still counts at exactly 10 seconds old.
  • A denied request never goes in the deque. If it did, a client that retries faster than its limit would keep its own window full and never get through.
  • The deque stays sorted with no effort, because the times come in order. The front is always the oldest, so the while stops at the first request that still counts.

Each time is appended once and popped at most once. So a call costs O(1) amortized: averaged over all the calls, even though one call can pop many times.

The editor holds OneKeyLimiter from above with one change: allow records the request before it decides. Fix allow so a denied request is never stored.