KatInterview

Rate Limiter with Bucket Drain Simulation

Data Structure DesignAuto-graded · 22 test cases
MediumAuto-gradedData Structure Designrate-limitingsimulationstate-machine

Last 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 add amount units to the bucket. The request is admitted (return True) if and only if the resulting level would not exceed capacity. If admitted, the bucket level increases by amount. If rejected, the bucket level does not change.
  • "advance" with a non-negative seconds: Time moves forward, draining drain_rate * seconds units from the bucket. The level never goes below zero. Return None.

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^6
  • 0 <= drain_rate <= 10^6
  • 1 <= len(operations) <= 10^4
  • All amount and seconds values 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.