KatInterview

Rate Limiter with Continuous Drainage Pattern

Data Structure DesignModel answer
MediumModel answerData Structure Designrate-limitingconcurrencytime-based-state

Last updated

Build a request throttler that drains at a fixed rate, accepting requests only when space exists, first single-threaded then thread-safe.

Design a rate limiter that uses a continuous drainage model to control request acceptance.

Your limiter maintains an internal buffer with two key properties:

  • capacity: the maximum number of pending requests the buffer can hold
  • drain_rate_per_second: how many requests exit the buffer every second

Implement a class matching this interface:

class ContinuousDrainRateLimiter:
    def __init__(self, capacity: int, drain_rate_per_second: float):
        pass

    def allow_request(self) -> bool:
        pass

The allow_request() method should return:

  • True when the request can be added to the buffer
  • False when the buffer is already full (after accounting for drained requests)

Your implementation should:

  1. Start with a single-threaded version that correctly models continuous drainage
  2. Include comprehensive tests covering normal operation, edge cases, and time-dependent behavior
  3. Extend your design to handle concurrent calls from multiple threads safely
  4. Maximize code reuse when adding thread-safety—avoid duplicating the core logic

Consider how to handle time progression, partial drainage, idle periods, and boundary conditions like zero capacity or zero drain rate.

Hints

Hint 1

Model the buffer as a continuous water level rather than discrete request objects—drainage happens continuously, not in discrete steps

Hint 2

Avoid background threads by computing drainage lazily whenever a request arrives, based on elapsed time since the last check

Hint 3

Use a monotonic clock source and make it injectable so tests can control time without sleep calls