Per-Client Rate Limiter
A debugging task on a small Go token-bucket rate limiter with a background sweeper that forgets idle clients. Six of the nine supplied tests fail, in three families: the refill arithmetic, a sweeper that races and never stops, and idle eviction that was never written.
On this page
The codebase
The package keeps one token bucket per client. Tokens refill over time from an injected clock up to a burst size, the middleware answers a refused request with its wait, and a background goroutine should forget clients that stay idle.
The nine visible tests run with the race detector, and Test stops at the first failure. Verification after Submit adds five hidden tests.
The assistant explains the code and Go on request and makes the changes you direct. The session's files are fixed, so a check of your own is a trace or a run you ask the assistant for.
Where things live
src/limiter.goAllow, AllowN, RetryAfter, Len, Sweep, Close and the bucket refill: where the refill rule, the lock and the eviction live.src/sweeper.goThe background goroutine that looks for idle clients on a ticker.src/middleware.goThe HTTP middleware over the limiter. Its behaviour must stay as shipped.tests/The visible tests, read-only: the limiter, the middleware and the race test.Rules that shape every fix
- Keep the middleware's behaviour and the exported API.
- Go 1.23, standard library only: no module can be added.
- Every method is safe for concurrent use, no lock is held across the next handler, and nothing in the package sleeps to order goroutines.
How to work the fix
- Press Test first and read the failure, then read the limiter and the sweeper against the task's rules.
- Name each failing family and its cause before you ask for any change.
- Decide the refill rule, the lock and the shutdown yourself, and say how the wait for the next token is computed.
- Give the cases that must hold afterwards, each with its expected result, and press Test after the change.
- Ask the assistant to trace named cases through the final code, then Submit.
Fix the limiter
What the ticket asks
Six of the nine supplied tests fail on the shipped limiter. Find out why and fix the package, including the idle-client eviction.
Keep the middleware's behaviour as it is, and keep to the standard library.
Where to look
src/limiter.goThe refill cuts the elapsed time to whole seconds and never caps the bucket, the wait is a fixed second, and Sweep is an empty stub.src/sweeper.goThe goroutine reads the client map without the lock and never looks at the stop channel.tests/race_test.goMany clients at once while the sweeper runs: the race detector names the unlocked read.What the tests pin down
RetryAfter is the exact time until one token is available: zero when one is, and a very long wait when the rate is zero or less.Where the shipped limiter goes wrong
- The refill converts the elapsed time to whole seconds before multiplying, so half a second adds nothing, and nothing caps the bucket at the burst;
RetryAfteranswers a fixed second. - The sweeper ranges over the client map without the limiter's lock while requests write it, and Close closes a stop channel nothing reads, waits for nothing, never closes Done and panics when called twice.
- Sweep is a stub, so idle clients are never removed and the map grows without bound.
The fix
- Refill by the elapsed seconds times the rate as a float, capped at the burst, once per request.
- The wait is one token minus the tokens held, divided by the rate, and zero when a token is available.
- One mutex guards the client map and the buckets; Sweep takes it and deletes idle clients, and the sweeper calls Sweep.
- Close runs once: it marks the limiter closed under the lock, closes the stop channel, waits for the sweeper and closes Done.
src/limiter.goThe refill keeps fractions and stops at the burst.- elapsed := now.Sub(b.last)- b.tokens += float64(int(elapsed.Seconds())) * l.opts.Rate+ if elapsed := now.Sub(b.last); elapsed > 0 {+ b.tokens = math.Min(float64(l.opts.Burst), b.tokens+elapsed.Seconds()*l.opts.Rate)+ }src/limiter.goRetryAfter answers the time until one token.- if b := l.bucketLocked(client); b.tokens >= 1 {+ b := l.bucketLocked(client)+ if b.tokens >= 1 { return 0 }- return time.Second+ if l.opts.Rate <= 0 {+ return 365 * 24 * time.Hour+ }+ return time.Duration((1 - b.tokens) / l.opts.Rate * float64(time.Second))src/limiter.goSweep removes idle clients under the lock. func (l *Limiter) Sweep() {- // TODO: remove clients whose last request is at least IdleTTL ago.+ l.mu.Lock()+ defer l.mu.Unlock()+ if l.closed || l.opts.IdleTTL <= 0 {+ return+ }+ now := l.opts.Now()+ for client, b := range l.clients {+ if now.Sub(b.last) >= l.opts.IdleTTL {+ delete(l.clients, client)+ }+ } }src/sweeper.goThe sweeper stops on the stop channel and sweeps through the locked Sweep, and Close waits for it once.- for range ticker.C {- now := l.opts.Now()- idle := 0+ for {+ select {+ case <-l.stop:+ return+ case <-ticker.C:+ l.Sweep()+ }+ }Tests that prove it
- Half a second refilling one token at two per second, and a long idle gap giving at most the burst.
- The exact wait after one request, the wait of a fresh client, and a zero rate that never refills.
- Idle clients removed while active ones stay, and isolation between clients.
- Close twice, Done closed, and many clients against the running sweeper with the race detector on, plus a hidden stress test of Sweep and Close together.
The conversation
Only your side is shown: the assistant reads, writes and runs between your messages. Each chip is a rubric item the step earns.
DirectionPrompt qualityVerificationCorrectnessCode quality
- Press Test. Test stops at the fractional refill: half a second at two tokens per second added nothing.
- Press Test. All nine visible tests pass with the race detector after the change.
- Verification: Run after last change, 6 points
- Submit. The stage closes. Scope, the fourteen visible and hidden tests and code quality are judged on the final code.
- Direction: Scope, 6 points
- Correctness: Hidden tests, 20 points
- Code quality: Code quality, 10 points
Where the stage lands
Measured when this conversation was played on the platform. A+ needs 92, S needs 95.