Map Tile Burst Allowance
A map company sells tile access to app developers. Panning a map needs a burst of tiles, then nothing for a while, so each API key gets a token bucket instead of a fixed per-minute cap. The bucket holds up to capacity tokens, a request spends tokens, and one token drips in every intervalMs milliseconds. A full bucket allows a burst, and the drip rate sets the long-run rate.
This is the token bucket from Rate Limiting (see also Design a Rate Limiter). No timer refills the bucket. Instead, each request works out how many tokens have arrived since the last one, and that calculation is where most bugs occur.
Your task
Write a class TokenBucket:
constructor(capacity, intervalMs)creates a bucket that starts full at time 0.take(t, cost)handles a request at timet(milliseconds) needingcosttokens. If the bucket holds at leastcost, remove them and returntrue. Otherwise returnfalseand remove nothing.available(t)returns how many tokens the bucket holds at timetand changes nothing else.
Drips happen at fixed times: intervalMs, 2 × intervalMs, 3 × intervalMs, and so on. Each adds one token, unless the bucket is full, in which case the token is lost. A drip at exactly time t counts before the request at t.
class TokenBucket
Examples
new TokenBucket(3, 1000) .take(0, 1) .take(100, 1) .take(200, 1) .take(300, 1) .take(1000, 1) .take(1500, 1) .available(2000)
[null, true, true, true, false, true, false, 1]
The burst at 0, 100 and 200 ms empties the 3 tokens. At 300 ms nothing has dripped yet, so the request is rejected. The drip at 1,000 ms adds a token, which the request at 1,000 spends. At 1,500 ms the bucket is empty again, so that request is rejected, and the drip at 2,000 ms leaves 1 token.
new TokenBucket(2, 1000) .take(0, 2) .take(600, 1) .take(1200, 1) .take(1900, 1) .take(2000, 1)
[null, true, false, true, false, true]
A cost-2 request empties the bucket at 0. At 600 ms no drip has happened. By 1,200 ms the drip at 1,000 has added a token, so the request is allowed; measuring time "since the last request" would wrongly reject it. The drip at 2,000 ms supplies the token for the last request.
Constraints
- 1 ≤ capacity ≤ 1,000,000
- 1 ≤ intervalMs ≤ 1,000,000
- 1 ≤ cost ≤ 1,000,000 (a cost above capacity can never succeed)
- 0 ≤ t ≤ 1,000,000,000,000, and t never decreases from one call to the next
- At most 2,000 calls per test
Start with brute force
A gateway with a million API keys cannot run a million refill timers. Simulating each drip inside every call is also too slow, because a 1 ms interval with calls a trillion milliseconds apart takes a trillion steps.
One division counts the drips in O(1), and the bucket is two numbers per key, small enough for a shared in-memory store.
Hints
0 of 4 shown- Hint 1
How many drips happen between calls at times
aandb? Try a = 600, b = 1,200 with a 1,000 ms interval, then a = 0, b = 600. - Hint 2
The number of drips up to time
tisfloor(t / intervalMs). The drips between two calls are the difference of those counts, so nothing is lost to rounding. - Hint 3
Store the token count and the drip count at the last update. On every call, add the new drips to the tokens, clamp to
capacity, and save the new drip count. - Hint 4
takerefills first, then compares withcost.availablerefills and then returns the count. Refilling early is harmless because you store the drip count, not the call time.
Walkthrough and solution
Unlocks when you pass every test. Stuck for a while? Looking is fine too, as long as you then close it and write the code yourself.
How to solve it
The bucket stores two numbers: the current token count and the number of drips counted so far. Every call first catches up on the drips that have happened. The total number of drips up to t are floor(t / intervalMs), so the new drips are that total minus the stored count.
Trace the second example, capacity 2, interval 1,000:
- At t = 0 with cost 2 there are no drips, and 2 tokens is enough, so the request takes them and 0 are left.
- At t = 600 with cost 1, floor(600 / 1000) = 0, so there are no new drips, and 0 tokens is less than 1, so the request is rejected.
- At t = 1,200 with cost 1, floor(1200 / 1000) = 1, so there is one new drip. The request takes it, 0 tokens are left, and the stored drip count becomes 1.
- At t = 1,900 there is still only 1 drip, so the request is rejected.
- At t = 2,000 there are 2 drips, one of them new, so the request is allowed.
The key point is to store the drip count instead of the last call time. gained = floor((t - last) / interval); last = t throws away the 600 ms of progress made before the call at 600, so it wrongly rejects the request at 1,200. In a real gateway, refill and take must be one atomic step in the shared store, or two servers can spend the same token.
class TokenBucket {
constructor(capacity, intervalMs) {
this.capacity = capacity;
this.intervalMs = intervalMs;
this.tokens = capacity; // starts full
this.drips = 0; // drips counted so far (drip k happens at k * intervalMs)
}
refill(t) {
const drips = Math.floor(t / this.intervalMs);
// add the drips since the last update; anything above capacity is lost
this.tokens = Math.min(this.capacity, this.tokens + (drips - this.drips));
this.drips = drips;
}
take(t, cost) {
this.refill(t);
if (this.tokens < cost) return false; // not enough: take nothing
this.tokens -= cost;
return true;
}
available(t) {
this.refill(t);
return this.tokens;
}
}class TokenBucket:
def __init__(self, capacity, interval_ms):
self.capacity = capacity
self.interval_ms = interval_ms
self.tokens = capacity # starts full
self.drips = 0 # drips counted so far (drip k happens at k * interval_ms)
def _refill(self, t):
drips = t // self.interval_ms
# add the drips since the last update; anything above capacity is lost
self.tokens = min(self.capacity, self.tokens + (drips - self.drips))
self.drips = drips
def take(self, t, cost):
self._refill(t)
if self.tokens < cost: # not enough: take nothing
return False
self.tokens -= cost
return True
def available(self, t):
self._refill(t)
return self.tokensRun your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.