← All Exercises
Token Bucket Rate Limiter
advancedgo
Background
Token buckets smooth bursty traffic while permitting short bursts; using an injected clock makes rate-limit behavior deterministic in tests.
Problem
Implement NewTokenBucket(capacity int, ratePerSecond float64, clock func() time.Time) and Allow() bool. Refill tokens from elapsed time, cap at capacity, consume one token per allowed call, and guard the state with a mutex.
Input
Capacity, refill rate per second, and a sequence of timestamps supplied by the injected clock.
Output
One boolean per Allow call indicating whether a token was consumed.
Sample tests
Sample 1
Input: capacity = 2, rate = 1/s, calls at 0s, 0s, 0s, 0.5s, 1.0s
Expected: [true, true, false, false, true]
Sample 2
Input: capacity = 1, rate = 2/s, calls at 0s and 0.5s
Expected: [true, true]
Your solution
Learning objective
Model burst capacity and sustained rate with deterministic time and mutex protection.