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:

  • TokenBucket implements the Limiter interface.
  • 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 float64 and the time at which the bucket was last updated. The TokenBucket must hold a sync.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) *TokenBucket

    A 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) bool

    The stub constructor returns a *FixedWindow, and its Allow method returns false. 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 its fakeClock type 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: Calls NewFixedWindow from 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 float64 so fractional refill rates, such as 0.5 tokens 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 now field. Call time.Now only 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 fakeClock and tests in limiter_test.go. Do not redeclare them in your implementation files.
  • Keep the temporary FixedWindow stub 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/:

bash
make test W=1B2

For verbose output, run:

bash
make test W=1B2 V=1

You can also run the Go test command directly:

bash
go test -race -count=1 -run TestW1B2 ./internal/ratelimit/

The implementation must satisfy these behaviors:

  • Initial capacity: With capacity 2, refill rate 1 token per second, and no elapsed time, three calls for the same key return true, true, and false.
  • One-second refill: With capacity 1 and refill rate 1, the first call returns true, the immediate second call returns false, and a call after advancing the fake clock by one second returns true.
  • Fractional refill: With capacity 1 and refill rate 1, 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 2 and refill rate 10, 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 key a and the first request for key b are both allowed. A second request for key a is 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 FixedWindow stub in place. The stub is not expected to pass fixed-window behavior tests. Exercise 1.14 replaces it with the complete implementation.
Finished Exercise 1.11?

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

Alternative rate limiters and testing

Up next · Module 4 · 4 items · about 2 h 60 min

Start module 4

Implementation

Run locally

Write the code in your editor inside zomato-prep, then work through this list.

  1. internal/ratelimit/limiter.go declares type Limiter interface { Allow(key string) bool }.
  2. NewTokenBucket(capacity int, refillPerSec float64, now func() time.Time) returns a *TokenBucket, and a nil clock means time.Now.
  3. A new key starts with a full bucket; each allowed call takes one token.
  4. Tokens refill from elapsed time on each call and never exceed capacity.
  5. Two different keys never affect each other.
  6. make test W=1B2 passes.

Commands

terminal
cd backend && make test W=1B2

Tests

  • TestW1B2_TokenBucket in backend/internal/ratelimit/limiter_test.go
  • TestW1B2_KeysAreIndependent in backend/internal/ratelimit/limiter_test.go