Skip to content
Recommended solution · HC-6 · Go

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

  1. Press Test first and read the failure, then read the limiter and the sweeper against the task's rules.
  2. Name each failing family and its cause before you ask for any change.
  3. Decide the refill rule, the lock and the shutdown yourself, and say how the wait for the next token is computed.
  4. Give the cases that must hold afterwards, each with its expected result, and press Test after the change.
  5. Ask the assistant to trace named cases through the final code, then Submit.
Stage 1 · per-client-rate-limiter

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

RefillTokens refill continuously at the rate per second, fractions included, and never beyond the burst.
WaitRetryAfter 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.
Idle clientsSweep removes every client idle for at least the idle time, and a returning client starts with a full bucket.
CloseClose stops the sweeper, waits for it, closes Done and is safe to call twice; afterwards every request is refused.

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; RetryAfter answers 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

  1. Refill by the elapsed seconds times the rate as a float, capped at the burst, once per request.
  2. The wait is one token minus the tokens held, divided by the rate, and zero when a token is available.
  3. One mutex guards the client map and the buckets; Sweep takes it and deletes idle clients, and the sweeper calls Sweep.
  4. 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

  1. Press Test. Test stops at the fractional refill: half a second at two tokens per second added nothing.
  2. Your message 1

    Test stops at TestFractionalRefill. Before any change, check my reading of src/limiter.go and src/sweeper.go against the code and tell me where I'm wrong; no edits yet. (1) Refill: bucketLocked adds float64(int(elapsed.Seconds())) * Rate, so the elapsed time is truncated to whole seconds and 500 ms refills nothing (TestFractionalRefill); nothing caps tokens at Burst, so a long idle gap gives more than Burst requests (TestRefillCapsAtBurst); and RetryAfter returns a fixed second instead of the wait for one token (TestRetryAfter). (2) Lifecycle: the sweeper ranges over l.clients without holding l.mu while Allow writes the map, so TestConcurrentClients will report a race; Close closes stop but the sweeper never reads it, nothing waits for the goroutine, done is never closed, and a second Close panics on a closed channel (TestCloseLifecycle). (3) Eviction: Sweep is a TODO, so idle clients are never removed and Len grows without bound (TestIdleEviction).

    Name every failing family with the line that causes it and the case that shows it, and ask for a check of your reading before any change.

    • Direction: Diagnosis: refill, 2 points
    • Direction: Diagnosis: lifecycle, 2 points
    • Direction: Diagnosis: eviction, 2 points
    • Prompt quality: Named failing test, 6 points
    • Prompt quality: Contract examples, 4 points
    • Prompt quality: Failure follow-up, 4 points
    • Verification: Named cases: refill, 2 points
    • Verification: Named cases: lifecycle, 2 points
    • Verification: Named cases: eviction, 2 points
  3. Your message 2

    Test fails at TestFractionalRefill: for "burst 2, rate 2/s; drain; advance 500ms; Allow" it expected true and got false. That is the truncation from my reading: elapsed is cut to whole seconds before it is multiplied. Now fix the three families in src/limiter.go and src/sweeper.go, keeping the middleware and the exported API: (1) bucketLocked refills tokens += elapsed.Seconds() * Rate as a float, capped at Burst, once per call; RetryAfter returns zero when tokens >= 1, otherwise (1 - tokens) / Rate seconds, and a very long wait when Rate <= 0. (2) Sweep takes l.mu and deletes every client whose last request is at least IdleTTL ago (IdleTTL <= 0 disables it); a returning client gets a new full bucket. (3) One mutex guards the client map and the buckets: the sweeper selects on stop and the ticker and calls l.Sweep(), and Close uses a sync.Once to mark closed under the lock, close stop, wait for the sweeper with a sync.WaitGroup, then close done. No time.Sleep in the package and no lock held across the next handler. Afterwards these must hold: rate 2 per second, burst 2, drained, 500 ms later Allow is true once and then false; rate 1, burst 3, 1000 s idle gives exactly 3 Allows; rate 2, burst 1, after one Allow RetryAfter is 500 ms; IdleTTL 1 minute, a client last seen 61 s ago is gone after Sweep. Don't change the tests.

    Tie the failure to its cause, then decide the refill rule, the lock and the shutdown yourself and say what must hold afterwards.

    • Direction: Refill rule, 6 points
    • Direction: Lock discipline, 6 points
    • Direction: Lifecycle, 6 points
    • Prompt quality: Specified fix: refill, 2 points
    • Prompt quality: Specified fix: lifecycle, 2 points
    • Prompt quality: Specified fix: eviction, 2 points
    • Verification: Reaction to failure, 4 points
  4. Press Test. All nine visible tests pass with the race detector after the change.
    • Verification: Run after last change, 6 points
  5. Your message 3

    Test passes. Before I submit, trace these cases through the final src/limiter.go step by step and say which line decides each step, without editing: (a) rate 2 per second, burst 2: drain both, advance 500 ms, the first Allow is true and the second false; (b) rate 1, burst 3: drain, advance 1000 s, exactly three Allows succeed; (c) rate 2, burst 1: after one Allow, RetryAfter is 500 ms, and after 500 ms more it is 0; (d) IdleTTL 1 minute: client a at t0 and b at t0+30 s, Sweep at t0+61 s leaves Len 1, and a then gets a full bucket.

    The files are fixed, so your own check is a trace of named cases through the code you changed.

    • Verification: Checks own, 4 points
  6. 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.

Direction30/30
Prompt quality20/20
Verification20/20
Correctness20/20
Code quality10/10
Stage total 100/100Grade S
Per-Client Rate Limiter Solution — Go Walkthrough | Hunicode