← All Exercises

Token Bucket Rate Limiter Simulation

intermediatejavascript~20min

Background

Token buckets allow short bursts while enforcing a long-run average rate, which matches how APIs throttle clients. The same math drives traffic shaping in routers and cloud quotas.

Problem

Implement a token bucket with a capacity and a refill rate per second. The bucket starts full. For each request carrying a timestamp and a token cost, first refill tokens by elapsed time since the previous request (capped at capacity), then admit the request if enough tokens exist, deducting the cost; otherwise reject it. Output the verdict per request and the final token count.

Input

A JSON object {"capacity": number, "ratePerSec": number, "requests": [{"t": number, "n": number}]} with non-decreasing timestamps.

Output

A JSON object {"allowed": boolean[], "finalTokens": number} where finalTokens is rounded to two decimals.

Sample tests

Sample 1

Input: {"capacity":3,"ratePerSec":1,"requests":[{"t":0,"n":1},{"t":0,"n":3},{"t":1,"n":2},{"t":3,"n":1}]}
Expected: {"allowed":[true,false,true,true],"finalTokens":2}

Sample 2

Input: {"capacity":5,"ratePerSec":0.5,"requests":[{"t":0,"n":5},{"t":1,"n":2},{"t":2,"n":1},{"t":10,"n":5}]}
Expected: {"allowed":[true,false,true,false],"finalTokens":4}

Your solution

Learning objective

Model continuous refill, burst tolerance, and the admit-or-reject decision of a token bucket.