Rate LimiterStep 1 of 5

Fixed-Window Counter

Step 1 β€” Fixed-Window Counter

The simplest limiter: chop time into fixed windows (say, 10-second buckets) and allow at most limit requests per bucket. When the clock crosses into a new window, the count resets to zero.

As with the TTL challenge, the limiter takes an injected clock (a zero-arg callable returning seconds) so tests are deterministic:

now = [0.0]
rl = FixedWindowLimiter(limit=5, window=10, clock=lambda: now[0])

Implement:

  • allow() β€” return True if the request is permitted (and count it), False if the current window is full

The window a timestamp belongs to is int(now // window) β€” when that index changes, start a fresh count.

Hints
Starter code
import time


class FixedWindowLimiter:
    def __init__(self, limit, window, clock=time.time):
        self.limit = limit
        self.window = window
        self.clock = clock
        self._window_index = None
        self._count = 0

    def allow(self):
        """Return True and count the request if the current window has room,
        otherwise return False."""
        # TODO:
        #   now = self.clock()
        #   index = int(now // self.window)
        #   if index != self._window_index: reset (_window_index = index, _count = 0)
        #   if self._count < self.limit: count it and return True
        #   else return False
        pass
Write it on a laptop

The editor and the test runner need a wide screen. Open this page on a desktop browser and your progress will be waiting.