Waymo OA Interview Question: Implement a RateLimiter Class

17 Views
No Comments

Implement a class, RateLimiter, which wraps a given function, allowing it to be called no more than once every n milliseconds.

TODO: Implement this class.

class RateLimiter:
    """Rate limiter class which will only allow the wrapped function to be called with specified frequency."""

    def __init__(self, fn, millis_between_calls):
        self.fn = fn
        self.millis_between_calls = millis_between_calls

    def run_rate_limited(self):
        # TODO: Implement this.
        pass

Sample Usage:

rate_limited = RateLimiter(tracked_function, 1000)
rate_limited.run_rate_limited()

This problem asks you to implement a RateLimiter that wraps a function and ensures it is executed at most once per specified millisecond interval. The key idea is to store the timestamp of the last real execution, then compare it with the current time on each request: if enough time has passed, call the function and update the timestamp; otherwise, wait for the remaining interval before running it. It tests basic class design, time-based control flow, and function wrapping.

END
 0