Table-driven tests with a fake clock, plus one race test

Write your own table-driven tests for both limiters using a fake clock, and add a concurrent test that passes under the race detector.

Objective

Write deterministic, table-driven tests for the token bucket and fixed-window limiters, then verify their concurrency safety with a race-enabled test run. By the end:

  • token_bucket_test.go covers burst capacity, refill timing, fractional refill, capacity limits, and independent keys.
  • fixed_window_test.go covers window resets, partial usage, independent keys, and the fixed-window boundary burst.
  • Each scenario runs as a named subtest using t.Run.
  • A concurrent test verifies that exactly 100 requests are allowed when eight goroutines compete for the same key.
  • The complete package passes with Go's race detector enabled.

Deliverables

Write these files in backend/internal/ratelimit/, using package ratelimit.

  • backend/internal/ratelimit/token_bucket_test.go: a table-driven TestTokenBucket_Table using a fake clock and named cases.
  • backend/internal/ratelimit/fixed_window_test.go: a table-driven TestFixedWindow_Table and the concurrency test TestFixedWindow_Concurrent.

The table should describe each scenario with a name, limiter configuration, and a sequence of steps. A step should capture any clock advance and the expected result of the next Allow call.

The concurrency test should use the existing limiter constructor:

go
func NewFixedWindow(limit int, size time.Duration, now func() time.Time) *FixedWindow

Reuse the fakeClock type already declared in limiter_test.go. It provides Now() and Advance(d time.Duration) and is safe for concurrent use. Do not redeclare it.

Requirements

Constraints

  • Write tests in package ratelimit, the same package as the limiter implementations.
  • Use Go's testing package and named subtests with t.Run. Do not reuse or redefine any TestW1B* names from limiter_test.go.
  • Use a table-driven test structure for both limiter test functions. Each case must have a descriptive name.
  • Use the injected clock for all time-dependent tests. Do not use the real clock or time.Sleep.
  • Create a fresh fake clock and limiter for every subtest. Do not let state from one case affect another.
  • Report failures with the case name and the step that failed. A failure should make it clear which expected admission result was incorrect.
  • In TestFixedWindow_Concurrent, start eight goroutines, each making 1,000 calls to Allow("hot").
  • Coordinate completion with a WaitGroup. Call wg.Add(8) before launching the goroutines and defer wg.Done() inside each goroutine.
  • Protect the shared allowed-request count with a mutex or an atomic counter. The test must not introduce a data race of its own.
  • Assert the final total of allowed calls, not the order in which goroutines happen to execute.
  • Do not modify limiter_test.go or its provided tests.

Acceptance criteria

Token bucket cases: TestTokenBucket_Table must include all of these named scenarios:

  • Burst up to capacity, then reject an additional request.
  • Refill after exactly one second at a rate of one token per second.
  • Partial refill: half a second at a rate of one token per second is not enough to admit another request.
  • Long idle period: accumulated tokens never exceed capacity.
  • Fractional refill: a rate of 0.5 tokens per second produces one token after two seconds.
  • Independent keys: consuming tokens for one key does not affect another key.

Fixed-window cases: TestFixedWindow_Table must include:

  • The limit is reached and the next request is rejected.
  • A new window resets the count.
  • Partly used capacity in one window does not carry over to the next.
  • Different keys have independent counts.
  • Boundary burst: with a 10-second window, three requests at the last second of one window and three at the first second of the next are all allowed. This demonstrates that a fixed window can allow a 2x burst around its boundary.

Concurrency test: TestFixedWindow_Concurrent must:

  • Configure a limit of 100 and a window large enough that the fake clock never advances into another window.
  • Launch eight goroutines, each making 1,000 calls for the same key.
  • Count successful calls safely across goroutines.
  • Wait for all goroutines to finish.
  • Assert that exactly 100 calls were allowed.

Provided tests and race run:

  • TestW1B4_TokenBucketConcurrent in limiter_test.go must continue to pass. It runs eight goroutines making 1,000 calls each against a token bucket with capacity 100 and refill rate 0, and expects exactly 100 allowed calls.
  • From backend/, run make test W=1B4.
  • Run go test -race -count=1 -v ./internal/ratelimit/ and confirm the full package passes with no race reports.
  • As a final experiment, deliberately comment out the mutex lock in FixedWindow.Allow and run the race-enabled tests again. Observe the concurrent test and race detector fail, then restore the lock and confirm the tests pass.
Finished Exercise 1.15?

Alternative rate limiters and testing

4 items

  • 1.12Go testing: testing.T, subtests and table-driven testsnot completed
  • 1.13Goroutines, WaitGroup and the race detectornot completed
  • 1.14Limiter interface and a FixedWindow implementationnot completed
  • 1.15Table-driven tests with a fake clock, plus one race testnot completed

HTTP rate limiting

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

Start module 5

Implementation

Run locally

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

  1. You wrote token_bucket_test.go and fixed_window_test.go with table-driven cases and subtests.
  2. Cases cover the burst up to capacity, refill after one second, independent keys and the window boundary.
  3. A fake clock is a variable you advance, never time.Sleep.
  4. One test starts 8 goroutines that each call Allow 1000 times and checks that exactly capacity calls were allowed.
  5. go test -race ./internal/ratelimit/... passes.

Commands

terminal
cd backend && go test -race -count=1 ./internal/ratelimit/...
terminal
cd backend && make test W=1B4

Tests

  • TestW1B4_TokenBucketConcurrent in backend/internal/ratelimit/limiter_test.go