System Design — Sliding Window Counter Rate Limiter
A fixed-window counter lets a client burst twice the limit around a window boundary; a sliding
window log is exact but stores every timestamp. The sliding window counter is the
production compromise: keep only two numbers (the previous and the current window's counts)
and weight the previous window by how much of it still overlaps the sliding window.
solve(args, ops) builds new SlidingWindowCounter(limit, windowSize) —args = [limit, windowSize] — and replays ops:
allow(timestamp)— returntrueand count the request, orfalseand count nothing.
Time is split into fixed windows: window w = floor(timestamp / windowSize), andelapsed = timestamp - w * windowSize. Timestamps never go backwards. The estimated load is
estimate = prev * (windowSize - elapsed) / windowSize + currentA request is allowed when estimate < limit (before counting it). Compare in integers —prev * (windowSize - elapsed) + current * windowSize < limit * windowSize — to avoid
floating-point surprises. When the window changes, prev becomes the old current if the new
window directly follows it, or 0 if one or more whole windows were skipped; current restarts at 0.
Example (limit = 1, windowSize = 10)
allow(0) → true allow(5) → false allow(10) → false allow(11) → trueSample tests