Token bucket limiter with lazy refill
Implement the Limiter interface and a token bucket with a mutex-protected map of buckets, lazy refill from elapsed time and an injected clock.
Objective
Build a per-key token bucket rate limiter in Go using lazy refill and an injected clock. The limiter controls how many requests each key can make over time, while keeping keys independent and making time-dependent behavior deterministic in tests.
By the end:
TokenBucketimplements theLimiterinterface.- Each key has its own token count and last-updated timestamp.
- Tokens refill lazily based on elapsed time, without timers or background goroutines.
- Concurrent calls cannot consume the same token.
- Tests verify burst capacity, refill timing, capacity limits, and key independence.
Deliverables
-
backend/internal/ratelimit/limiter.go: Declare the limiter interface.go type Limiter interface { Allow(key string) bool } -
backend/internal/ratelimit/token_bucket.go: Define the per-key state and token bucket implementation.The per-key state must use a struct to remember the available tokens as a
float64and the time at which the bucket was last updated. TheTokenBucketmust hold async.Mutex, a map of per-key states, its capacity, its refill rate per second, and its injected clock.Implement the constructor:
go func NewTokenBucket(capacity int, refillPerSec float64, now func() time.Time) *TokenBucketA nil clock must default to
time.Now.Implement the admission method:
go func (tb *TokenBucket) Allow(key string) bool -
backend/internal/ratelimit/fixed_window.go: Add a temporary compile-time stub because the provided test file also contains a test for exercise 1.14. Go compiles the entire package before running selected tests, so this symbol must exist even when you run only the token bucket tests. Exercise 1.14 replaces this stub with the real implementation.go type FixedWindow struct{} func NewFixedWindow(limit int, size time.Duration, now func() time.Time) *FixedWindow func (fw *FixedWindow) Allow(key string) boolThe stub constructor returns a
*FixedWindow, and itsAllowmethod returnsfalse. Do not implement fixed-window behavior in this exercise. -
backend/internal/ratelimit/limiter_test.go: This file is already provided. Do not rewrite it or redeclare itsfakeClocktype or test functions.The provided tests include:
TestW1B2_TokenBucket: Uses a fake clock to check burst capacity, refill timing, and the maximum capacity after idle time.TestW1B2_KeysAreIndependent: Checks that separate keys have independent token balances.TestW1B3_FixedWindowBoundary: CallsNewFixedWindowfrom exercise 1.14. The temporary stub exists only so this test file compiles before that exercise is completed.
Requirements
Constraints
- Use a per-key state struct to store the available tokens and last-updated time.
- Store per-key state in a map. A key that has never been seen must begin with a full bucket.
- Protect the map and all bucket state with a mutex.
- Lock before accessing the map and defer unlocking. The entire read, refill, and token-consumption decision must happen under the same lock.
- Refill lazily during
Allow. Do not create timers, tickers, or background goroutines. - Calculate refill as elapsed seconds multiplied by the refill rate per second.
- Keep tokens as
float64so fractional refill rates, such as0.5tokens per second, work correctly. - Cap the available tokens at the configured capacity.
- Clamp negative elapsed time to zero if the injected clock moves backwards.
- Update the bucket's last-updated time on every call.
- Read time only through the
nowfield. Calltime.Nowonly when selecting the default clock in the constructor. - Do not introduce package-level mutable state or global variables.
- Do not add comments documenting exported names. The page explains their purpose.
- Use the existing
fakeClockand tests inlimiter_test.go. Do not redeclare them in your implementation files. - Keep the temporary
FixedWindowstub minimal. It must be replaced, not kept, when completing exercise 1.14. - Follow the concepts from lesson 1.10 for mutex protection, time calculations, and injected clocks.
Acceptance criteria
Run the provided tests from backend/:
make test W=1B2For verbose output, run:
make test W=1B2 V=1You can also run the Go test command directly:
go test -race -count=1 -run TestW1B2 ./internal/ratelimit/The implementation must satisfy these behaviors:
- Initial capacity: With capacity
2, refill rate1token per second, and no elapsed time, three calls for the same key returntrue,true, andfalse. - One-second refill: With capacity
1and refill rate1, the first call returnstrue, the immediate second call returnsfalse, and a call after advancing the fake clock by one second returnstrue. - Fractional refill: With capacity
1and refill rate1, consuming the initial token and advancing the clock by one second allows one more request. Advancing only half a second after consuming that token must not allow another request. - Capacity after idle time: With capacity
2and refill rate10, advancing the clock by one hour must not accumulate more than two tokens. Exactly two requests are allowed, and the next is rejected. - Independent keys: With capacity
1, the first request for keyaand the first request for keybare both allowed. A second request for keyais rejected. - Concurrency safety: The map and token accounting are protected by the same mutex, so concurrent calls cannot both consume the final available token.
- Package compilation: The package compiles with the temporary
FixedWindowstub in place. The stub is not expected to pass fixed-window behavior tests. Exercise 1.14 replaces it with the complete implementation.
The reference solution passes every check for this exercise. Try the hints first; reading the answer before you have struggled with the problem teaches much less.
Rate limiting and token bucket algorithms
3 items
- 1.9Rate limiting: why, and the five algorithmsnot completed
- 1.10Mutexes and time: making a limiter safe and testablenot completed
- 1.11Token bucket limiter with lazy refillnot completed
Up next · Module 4 · 4 items · about 2 h 60 min
Implementation
Run locally
Write the code in your editor inside zomato-prep, then work through this list.
internal/ratelimit/limiter.godeclarestype Limiter interface { Allow(key string) bool }.NewTokenBucket(capacity int, refillPerSec float64, now func() time.Time)returns a*TokenBucket, and a nil clock meanstime.Now.- A new key starts with a full bucket; each allowed call takes one token.
- Tokens refill from elapsed time on each call and never exceed capacity.
- Two different keys never affect each other.
make test W=1B2passes.
Commands
cd backend && make test W=1B2Tests
TestW1B2_TokenBucketinbackend/internal/ratelimit/limiter_test.goTestW1B2_KeysAreIndependentinbackend/internal/ratelimit/limiter_test.go