← All Exercises

Refill a Token Bucket Correctly

basicjavascript~20min

Background

Gateways use token buckets because they tolerate short bursts while enforcing an average rate. Off-by-one mistakes either reject valid bursts or let traffic through unbounded.

Problem

Implement the token-bucket decision for one request: refill tokens for the elapsed time up to capacity, then allow the request only when enough tokens remain after paying the cost.

Input

JSON object: { capacity, refillPerSecond, tokens, elapsedMs, cost }

Output

JSON object: { allowed: boolean, tokensAfter: number }

Sample tests

Sample 1

Input: {"capacity":10,"refillPerSecond":2,"tokens":1,"elapsedMs":2000,"cost":3}
Expected: {"allowed":true,"tokensAfter":2}

Sample 2

Input: {"capacity":10,"refillPerSecond":2,"tokens":9,"elapsedMs":0,"cost":10}
Expected: {"allowed":false,"tokensAfter":9}

Your solution

Learning objective

Implement a burst-tolerant limiter whose accept/reject decision can be replayed from inputs alone.