System Design Quiz Practice
Active Recall Drill Session
← Exit SessionQuestion 1 of 1
mediumSystem Design
Given a TokenBucket with capacity 5 and refillRatePerSecond 0 (no refill), what happens after 5 successful tryConsume() calls followed by a 6th?
code
class TokenBucket {
constructor({ capacity, refillRatePerSecond }) {
this.capacity = capacity; this.tokens = capacity;
this.refillRatePerSecond = refillRatePerSecond; this.lastRefill = Date.now();
}
_refill() {
const now = Date.now();
const elapsed = (now - this.lastRefill) / 1000;
this.tokens = Math.min(this.capacity, this.tokens + elapsed * this.refillRatePerSecond);
this.lastRefill = now;
}
tryConsume(n = 1) {
this._refill();
if (this.tokens >= n) { this.tokens -= n; return true; }
return false;
}
}
const b = new TokenBucket({ capacity: 5, refillRatePerSecond: 0 });
for (let i = 0; i < 5; i++) console.log(b.tryConsume());
console.log(b.tryConsume());