Per-Key Token Bucket Admission Decisions
Data Structure DesignAuto-graded · 22 test casesLast updated
Simulate independent token buckets per key over a request log, with exact fractional refill, capped capacity, and out-of-order timestamps, to decide which requests are admitted.
You are given a log of requests hitting a rate limiter. The limiter keeps one independent token bucket for every distinct key. Process the log in the order given and report, for each request, whether it is admitted.
Bucket rules
- Every bucket holds at most
capacitytokens. - A key's bucket is created when that key first appears in the log. It starts full (
capacitytokens) as of that first request's timestamp. - Tokens are added continuously at
refill_ratetokens per second. Refill is exact and fractional: after 500 ms at a rate of 2 tokens per second, the bucket gains exactly 1 token, and after 1 ms at a rate of 1 token per second it gains exactly 0.001 tokens. Nothing is rounded. A bucket never exceedscapacity. - Each request has a
cost. Before deciding, bring the bucket up to date to the request's timestamp (add the refill earned since the bucket's last update, capped atcapacity). Then:- If the bucket holds at least
costtokens, the request is admitted andcosttokens are removed. - Otherwise it is rejected and the bucket loses no tokens. The refill earned up to this request's timestamp is still kept.
- If the bucket holds at least
- A request whose
costexceedscapacitycan never be admitted.
Time handling
Timestamps are in milliseconds. The log is processed in the given order but timestamps are not guaranteed to be non-decreasing for a key. If a request's timestamp is earlier than the latest timestamp already seen for its key, it earns no refill and the bucket's "last updated" time does not move backward. It is still judged against the current token balance.
Task
Implement token_bucket_decisions(capacity, refill_rate, requests).
capacity: maximum tokens in each bucket.refill_rate: tokens added per second.requests: list of[key, timestamp_ms, cost]entries in processing order.
Return a list of booleans, one per request in the same order, where True means admitted.
Constraints
capacityandrefill_rateare non-negative integers.costandtimestamp_msare integers;cost >= 0andtimestamp_ms >= 0.keyis a hashable identifier (for example an integer); different keys never affect each other.- Up to about 10^5 requests.
- The output must contain exactly one boolean per request.
Examples
Example 1
Input: token_bucket_decisions(5, 2, [[1, 0, 1], [1, 0, 4], [1, 0, 1], [1, 500, 1], [1, 1000, 1], [2, 1000, 5]])
Output: [True, True, False, True, True, True]
Example 2
Input: token_bucket_decisions(2, 1, [[1, 0, 2], [1, 999, 1], [1, 1000, 1]])
Output: [True, False, True]
Hints
Hint 1
Keep a dictionary from key to its current balance and the timestamp of its last update. Create the entry lazily on the key's first request, with a full bucket.
Hint 2
Avoid floating point. Since 1 token per second equals 1 thousandth of a token per millisecond, store balances in thousandths of a token and add `elapsed_ms * refill_rate` on each update.
Hint 3
On every request, refill first (cap at capacity), then compare to the cost. Rejected requests must still persist the refilled balance. For out-of-order timestamps, clamp elapsed time at 0 and never move the stored time backward.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Each key needs only two pieces of state: its current token balance and the timestamp at which that balance was last brought up to date. Both live in a dictionary created lazily the first time a key appears, with a full bucket.
To avoid floating-point error, balances are stored in thousandths of a token. A rate of refill_rate tokens per second equals exactly refill_rate thousandths per millisecond, so refilling is the integer expression elapsed_ms * refill_rate. A cost of c tokens is c * 1000 thousandths, and the capacity is capacity * 1000.
For every request, in order:
- If the key is new, set balance to full capacity and last-update time to this timestamp.
- Otherwise compute
elapsed = max(0, timestamp - last), addelapsed * refill_rateto the balance, cap it at the capacity, and setlast = max(last, timestamp). - If the balance covers the cost, subtract it and record
True; otherwise recordFalseand leave the balance alone. - Store the updated
(balance, last)for the key, including after rejections, so the refill that has already been credited is not lost or counted twice.
Why it is correct
- Lazy refill is equivalent to continuous refill, because the balance only matters at decision times, and the cap is applied after each addition. Capping at each update is valid since a full bucket stays full until it is spent.
- Integer thousandths make comparisons exact. For example, 999 ms at 1 token per second gives 999 thousandths, which is below a cost of 1000, while 1000 ms gives exactly 1000 and is admitted.
- Clamping elapsed time at 0 and taking the maximum of the stored time and the new timestamp means an out-of-order request earns no refill and cannot cause later requests to be credited twice for the same interval.
- A rejection consumes nothing, and a cost above capacity can never be met because the balance never exceeds capacity.
- Keys use separate dictionary entries, so they never interact.
Complexity
Time is O(n) for n requests, with O(1) dictionary work per request. Space is O(k) for k distinct keys.
Reference solution
from typing import List
def token_bucket_decisions(capacity: int, refill_rate: int, requests: List[List]) -> List[bool]:
# Balances are kept in thousandths of a token so refill stays exact:
# refill_rate tokens/second == refill_rate thousandths per millisecond.
states = {}
results = []
cap_milli = capacity * 1000
for key, ts, cost in requests:
if key not in states:
balance, last = cap_milli, ts
else:
balance, last = states[key]
elapsed = max(0, ts - last)
balance = min(cap_milli, balance + elapsed * refill_rate)
last = max(last, ts)
need = cost * 1000
admitted = balance >= need
if admitted:
balance -= need
states[key] = (balance, last)
results.append(admitted)
return results