Rate Limiter with Bucket Drain Simulation
Data Structure DesignAuto-graded · 22 test casesLast updated
Tests ability to model a rate-limiting algorithm with time-based decay, capacity bounds, and precise edge-case handling.
You are building a rate limiter that uses a bucket model with continuous drainage. The bucket has a fixed capacity and drains at a constant drain_rate (units per second).
The bucket starts empty. You will process a sequence of operations:
- "request" with a positive
amount: Try to addamountunits to the bucket. The request is admitted (returnTrue) if and only if the resulting level would not exceed capacity. If admitted, the bucket level increases byamount. If rejected, the bucket level does not change. - "advance" with a non-negative
seconds: Time moves forward, drainingdrain_rate * secondsunits from the bucket. The level never goes below zero. ReturnNone.
Any other operation name should raise a ValueError.
Write a function that takes the bucket parameters and a list of operations, then returns the result of each operation in order.
Constraints
0 <= capacity <= 10^60 <= drain_rate <= 10^61 <= len(operations) <= 10^4- All
amountandsecondsvalues are non-negative floats<= 10^6 - Each operation is either
"request"or"advance", except in test cases checking error handling - The bucket level is represented as a float
- Admission uses exact comparison:
level + amount <= capacity(no epsilon tolerance)
Examples
Example 1
Input: rate_limiter_bucket(3, 1, ['request', 'request', 'request', 'request', 'advance', 'request'], [[1], [1], [1], [1], [1], [1]])
Output: [True, True, True, False, None, True]
Example 2
Input: rate_limiter_bucket(2, 2, ['request', 'advance', 'request', 'advance', 'request'], [[2], [0.5], [1], [0.5], [1]])
Output: [True, None, True, None, True]
Example 3
Input: rate_limiter_bucket(5, 1.5, ['request', 'request', 'advance', 'request', 'advance', 'request'], [[3], [2], [1], [1], [1], [1]])
Output: [True, True, None, True, None, True]
Hints
Hint 1
Track the current bucket level as a single float variable that increases with admitted requests and decreases with time advancement.
Hint 2
The bucket level is clamped at zero when draining—idle time cannot create negative capacity or future credit.
Hint 3
A rejected request does not modify the bucket level, so a subsequent smaller request may still succeed.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Model the bucket as a single level variable that starts at zero. Process each operation in sequence:
- Advance: Reduce the level by
drain_rate * seconds, but never let it drop below zero. The clamp at zero ensures that long idle periods empty the bucket completely but don't create negative capacity that would allow unbounded bursts later. - Request: Check whether adding
amountto the current level would exceedcapacity. If the check passes (using inclusive comparison), admit the request by increasing the level and returnTrue. Otherwise, reject it without modifying the level and returnFalse.
The key insight is that rejected work never enters the bucket, so the level only increases on successful admissions. This preserves the invariant that 0 <= level <= capacity after every operation.
Correctness
The algorithm enforces two bounds:
- Upper bound: A request is admitted only when
level + amount <= capacity, so the level never exceeds capacity. - Lower bound: Drainage clamps at zero, preventing negative levels.
The drain computation is linear in time: draining for t seconds is equivalent to subtracting drain_rate * t. The only non-linearity is the zero clamp, which only makes the bucket emptier and never allows extra capacity.
Edge Cases
- A request larger than
capacityis always rejected, even when the bucket is empty. advance(0)leaves the level unchanged and returnsNone.- Long idle periods drain the bucket to exactly zero, not below.
- Rejected requests do not consume capacity—a subsequent smaller request can still succeed immediately.
- Unknown operation names raise
ValueError.
Complexity
- Time: O(n) where n is the number of operations. Each operation performs constant-time arithmetic.
- Space: O(n) for the output list. The algorithm uses O(1) state (just the
levelvariable).
Solution
from typing import List, Optional
def rate_limiter_bucket(capacity: float, drain_rate: float, operations: List[str], arguments: List[List[float]]) -> List[Optional[bool]]:
level = 0.0
result = []
for operation, args in zip(operations, arguments):
if operation == "advance":
seconds = args[0]
level = max(0.0, level - drain_rate * seconds)
result.append(None)
elif operation == "request":
amount = args[0]
if level + amount <= capacity:
level += amount
result.append(True)
else:
result.append(False)
else:
raise ValueError("unknown operation")
return result