Rate Limiter with Continuous Drainage Pattern
Data Structure DesignModel answerLast 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:
Truewhen the request can be added to the bufferFalsewhen the buffer is already full (after accounting for drained requests)
Your implementation should:
- Start with a single-threaded version that correctly models continuous drainage
- Include comprehensive tests covering normal operation, edge cases, and time-dependent behavior
- Extend your design to handle concurrent calls from multiple threads safely
- 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
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The key insight is to represent the buffer as a continuous fill level (a floating-point value) rather than a collection of discrete requests. Each accepted request adds 1.0 to the level, and the level drains continuously at the specified rate.
Instead of running a background thread to drain the buffer, we compute drainage lazily on each request:
- Calculate time elapsed since the last check
- Reduce the level by
elapsed × drain_rate_per_second - Clamp the level at zero (an empty buffer cannot accumulate negative credit)
- Check if adding 1.0 would exceed capacity
- If within capacity, increment the level and accept; otherwise reject
This "lazy evaluation" approach gives identical results to true continuous drainage while requiring only O(1) time and space.
Design Decisions
Injectable clock: Pass a clock function (defaulting to time.monotonic) as a parameter. This allows tests to control time deterministically without sleep() calls or real-time delays.
Monotonic time source: Never use time.time() for rate limiting. Wall-clock time can jump backward during NTP adjustments, causing negative elapsed time and incorrect behavior. Monotonic clocks guarantee forward progression.
Epsilon tolerance: Floating-point arithmetic can introduce tiny rounding errors. Add a small epsilon (1e-9) when comparing the level against capacity to avoid spurious rejections.
Correctness Invariants
The fill level always represents "total accepted requests minus total drained requests, floored at zero." The floor-at-zero rule is critical: a long idle period should not create stored credit that allows an unbounded burst. The algorithm enforces this by clamping level - drained at zero.
A request is rejected only if the buffer is genuinely full at the moment of the check (after applying drainage). This matches the specified behavior.
Thread Safety
The single-threaded version has a read-modify-write race: two threads might both read level = capacity - 1, both pass the admission check, and both increment, over-admitting by one request.
The solution is to wrap the entire check-modify sequence in a lock. For maximum code reuse, extract the core logic into the base class and create a thread-safe subclass that only adds locking around the allow_request() call.
Read the clock inside the lock to prevent timestamp ordering issues where an older timestamp might be written to last_checked after a newer one.
Edge Cases
- Zero capacity: All requests are immediately rejected
- Zero drain rate: Buffer never drains; exactly
capacityrequests are accepted total - Negative parameters: Raise
ValueErrorin the constructor - Long idle period: Level clamps at 0.0, preventing credit accumulation
- Fractional drainage: With rate 0.5/sec, one second drains 0.5 units—not enough for a full request. Floats handle this naturally
- Same timestamp: Multiple requests at identical timestamps (elapsed = 0) fill the buffer sequentially
Complexity
- Time: O(1) per request
- Space: O(1) total—only stores two floats plus a lock, independent of request volume
Solution
import threading
import time
from typing import Callable
class ContinuousDrainRateLimiter:
_EPSILON = 1e-9
def __init__(self, capacity: int, drain_rate_per_second: float,
clock: Callable[[], float] = time.monotonic):
if capacity < 0:
raise ValueError("capacity cannot be negative")
if drain_rate_per_second < 0:
raise ValueError("drain_rate_per_second cannot be negative")
self.capacity = capacity
self.drain_rate = float(drain_rate_per_second)
self._clock = clock
self._fill_level = 0.0
self._last_check = clock()
def _apply_drainage(self, current_time: float) -> None:
"""Update fill level based on elapsed time."""
elapsed = max(0.0, current_time - self._last_check)
drained = elapsed * self.drain_rate
self._fill_level = max(0.0, self._fill_level - drained)
self._last_check = current_time
def allow_request(self) -> bool:
"""Check if a request can be accepted into the buffer."""
now = self._clock()
self._apply_drainage(now)
if self._fill_level + 1.0 <= self.capacity + self._EPSILON:
self._fill_level += 1.0
return True
return False
class ThreadSafeContinuousDrainRateLimiter(ContinuousDrainRateLimiter):
"""Thread-safe version using a lock around the critical section."""
def __init__(self, capacity: int, drain_rate_per_second: float,
clock: Callable[[], float] = time.monotonic):
super().__init__(capacity, drain_rate_per_second, clock)
self._lock = threading.Lock()
def allow_request(self) -> bool:
with self._lock:
return super().allow_request()
Test Strategy
Use a fake clock class for deterministic testing:
class ControllableClock:
def __init__(self, start_time: float = 0.0):
self.current = start_time
def __call__(self) -> float:
return self.current
def tick(self, seconds: float) -> None:
self.current += seconds
Key test scenarios:
- Fill to capacity then verify rejection
- Zero capacity always rejects
- Zero drain rate never recovers
- Exact drainage timing (1 second @ 1/sec = 1 slot)
- Fractional drainage requires cumulative time
- Idle period does not create burst capacity beyond limit
- Concurrent threads never over-admit (use barriers to synchronize)
This design provides an efficient, testable rate limiter that correctly models continuous drainage without background threads or complex timing logic.