JavaScriptFundamental (ES6), part 2
Rate limiter with burst allowance in JavaScript
85 A token bucket that allows a burst and then meters you
hardBuild a rate limiter that lets a client send a short burst immediately and then holds it to a steady rate: a bucket of tokens, one per message, refilled continuously and never past its capacity. Take the clock as an argument. Show that idling for a long time does not bank unlimited credit, and that a request larger than the bucket can never be served.
Stuck? Three hints, smallest first
- 1. Store tokens as a fraction, not an integer. The refill is
elapsed / 1000 * ratePerSecond. - 2. Refill lazily, at the top of every
take, from the time elapsed since the last refill. No interval needed. - 3.
Math.min(capacity, tokens + earned)is the whole difference between a burst allowance and an unlimited one.
function makeClock() {
let now = 0;
return { now: () => now, advance(ms) { now += ms; }, get time() { return now; } };
}
function tokenBucket({ capacity, perSecond, clock }) {
let tokens = capacity; // start full, so a first burst is allowed
let last = clock.now();
const refill = () => {
const at = clock.now();
tokens = Math.min(capacity, tokens + ((at - last) / 1000) * perSecond);
last = at;
};
return {
take(cost = 1) {
refill();
if (tokens < cost) return false;
tokens -= cost;
return true;
},
get available() { refill(); return Math.round(tokens * 100) / 100; },
};
}
const clock = makeClock();
const sms = tokenBucket({ capacity: 3, perSecond: 2, clock }); // burst of 3, then 1 every 500ms
const burst = [sms.take(), sms.take(), sms.take()];
const fourth = sms.take();
const emptied = sms.available;
clock.advance(500); // half a second earns exactly one token
const afterHalfASecond = sms.available;
const fifth = sms.take();
clock.advance(10000); // idle for ten seconds
const cappedAtCapacity = sms.available;
const tooBigForTheBucket = sms.take(4);
const stillFull = sms.available;
const pairAtOnce = sms.take(2);
const leftOver = sms.available;
// Ten attempts back to back from a fresh bucket.
const fresh = tokenBucket({ capacity: 3, perSecond: 2, clock });
let accepted = 0;
for (let i = 0; i < 10; i++) if (fresh.take()) accepted++;
console.log('burst of three :', burst, '| fourth:', fourth);
console.log('after 500ms :', afterHalfASecond, 'token(s)');
console.log('after 10s idle :', cappedAtCapacity, '<- capped, not 20');
console.log('ten rapid tries :', accepted, 'accepted');
Output
8 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 8 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('the bucket starts full, so a burst up to capacity goes straight through', burst, [true, true, true]);
test('the message after that is refused', fourth, false);
test('with the bucket empty', emptied, 0);
test('500ms at two per second earns exactly one token, and it is spendable', [afterHalfASecond, fifth], [1, true]);
test('ten idle seconds do not bank twenty tokens; the capacity is the ceiling', cappedAtCapacity, 3);
test('a request costing more than the whole bucket can never be served', [tooBigForTheBucket, stillFull], [false, 3]);
test('but a cost of two is served from a full bucket, leaving one', [pairAtOnce, leftOver], [true, 1]);
test('and ten back-to-back attempts get exactly the burst allowance', accepted, 3);
A token bucket is the limiter to reach for when traffic is bursty but the average must be held down, which describes almost every real client. Capacity is the burst you tolerate; the refill rate is the sustained throughput. A fixed window — "100 per minute" — is easier to write and allows 200 requests across a window boundary, and a leaky bucket smooths output but cannot express a burst at all.
Refilling lazily is the part worth copying. There is no interval, no background work and nothing to clean up: each call works out how much time has passed and credits that fraction of a token. A bucket nobody touches costs nothing, which matters when there is one per phone number.
Math.min(capacity, ...) is the entire safety property, and the fifth assertion is what it buys. Without it, a client idle overnight arrives with tens of thousands of tokens and can empty your SMS budget in one loop. The sixth assertion is the other edge: a cost above capacity is not "wait longer", it is never satisfiable, so it needs rejecting at the point of validation rather than being left to retry for ever.