14/17
Part 7 of 7 · Follow-upsLearn

Two counters instead of a bucket

Cloudflare limits with a sliding window counter: last minute's count, weighted by how much of that minute the window still covers, plus this minute's count. Their post works an example: 42 requests last minute and 18 so far this minute, 15 seconds in.

def sliding_estimate(previous: int, current: int, elapsed: float, window: float = 60) -> float:
    """Last window's count, weighted by how much of it still overlaps, plus this window's count."""
    return previous * (window - elapsed) / window + current


print(sliding_estimate(42, 18, 15))
Predict

With a limit of 50 a minute, does the next request pass?

Pick one to see what it prints.
Pick an answer above to see the rest