A per-client token bucket rate limiter for HTTP requests. Each client gets an independent bucket and the registry of buckets is owned by a single goroutine and accessed exclusively via channels.
The system has two layers, both built on the owner goroutine + request/reply channel pattern:
HTTP handler ──allowCh──▶ Store.run (owns ulm map)
│
▼
*RateLimiter pointer
│
──reply (per-request)─┘
│
▼
rl.Allow() in handler's goroutine ──requests──▶ Limiter.run (owns tokens)
│
▼
bool reply
RateLimiterStore owns a map[string]*ClientRL. Handlers send storeReq messages on allowCh and the store looks up or creates the client's limiter, bumps lastSeen, and sends the *RateLimiter back on a per-request reply channel.
RateLimiter owns its tokens and lastRefill state. Each client gets one limiter, and its run goroutine processes Allow requests via a requests channel. A done channel signals retirement when the store evicts an inactive client. Both Allow methods are context.Context aware and return (bool, error), so in-flight handlers unblock immediately when http.Server.Shutdown cancels their request context.
The store hands back a *RateLimiter pointer instead of a bool. The token check (Allow()) runs in the caller's goroutine, so 100 different clients' token checks run in parallel rather than serializing through the store's single run loop.
Cleanup of inactive clients is folded into the store's run select loop via a time.Ticker — no separate cleanup goroutine. When a client exceeds maxInactiveTime, the store closes the limiter's done channel (retiring its goroutine) and deletes the entry from the map.
| File | Role |
|---|---|
main.go |
HTTP server wiring, graceful shutdown via signal.NotifyContext + http.Server.Shutdown |
store.go |
RateLimiterStore channel-based registry of per-client limiters, cleanup ticker |
rate-limiter.go |
RateLimiter core ratelimiter implementation with refill logic |
Makefile |
make build / make run |
allowCh(store): Handlers sendstoreReq{userID, reply}here and the single store owner goroutine reads them.reply(store): per-request return channel, buffered size 1. The owner sends the limiter back. Buffered because this way the owner never blocks if the caller is slow to receive.requests(limiter): per-limiter inbox. The caller sendsallowReqafter receiving the*RateLimiterfrom the store.done(limiter): closed by the store during cleanup. A closed channel is forever-ready in aselect, so the limiter'srunexits cleanly.- Double
selectinRateLimiter.Allow: guards against the limiter'srunexiting before we send (outer select) or after it received but before it replied (inner select). Both selects also watchctx.Done()so a cancelled request unblocks at any point. Without all of this, a caller could hang forever if cleanup fires mid-request. r.Context()inhandleReq: passed tostore.Allow. Auto-cancelled byhttp.Server.Shutdown, so handlers parked inAllowwake instantly on shutdown and return503.
make run # builds to bin/rl and runs
# or
go run .Server listens on :7777.
With MaxTokens = 3 and RefillRatePerSecond = 0.5, ravikishan should get 3 200s then 429s:
for i in $(seq 1 5); do
curl -s -o /dev/null -w "%{http_code}\n" -H "X-User-ID: ravikishan" http://localhost:7777/rl
doneExpected:
200
200
200
429
429
# Drain ravikishan, then tomas should still get 200 (independent bucket)
for i in $(seq 1 5); do
curl -s -o /dev/null -w "%{http_code}\n" -H "X-User-ID: ravikishan" http://localhost:7777/rl
done
curl -s -o /dev/null -w "%{http_code}\n" -H "X-User-ID: tomas" http://localhost:7777/rlfor i in $(seq 1 3); do
curl -s -o /dev/null -w "%{http_code}\n" -H "X-User-ID: ravikishan" http://localhost:7777/rl
done
sleep 2 # at 0.5 tokens/sec, 2s refills 1 token
curl -s -o /dev/null -w "%{http_code}\n" -H "X-User-ID: tomas" http://localhost:7777/rlHappens automatically if a user has been inactive for 5 minutes. Can be adjusted through
store.Start(ctx,time.Second)in main.go
go run -race .Then run the curl tests above. The race detector should stay silent implying theres no race condition
for u in ravikishan tomas frank palmer pedro marco moi enzo cahill; do
( for i in $(seq 1 10); do
curl -s -o /dev/null -w "%{http_code}\n" -H "X-User-ID: $u" http://localhost:7777/rl
done ) &
done
waitEach user's bucket is independent so you should see a mix of 200/429 per user, no panics or hangs.

