Skip to content

About

A per client token bucket rate limiter implementation in Go

Resources

Stars

1 star

Watchers

0 watching

Forks

Latest commit

 

History

8 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

tokenbucket

token bucket

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.

Architecture

token bucket implementation in this repo

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.

Files

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

Design decisions I made

  • allowCh (store): Handlers send storeReq{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 sends allowReq after receiving the *RateLimiter from the store.
  • done (limiter): closed by the store during cleanup. A closed channel is forever-ready in a select, so the limiter's run exits cleanly.
  • Double select in RateLimiter.Allow: guards against the limiter's run exiting before we send (outer select) or after it received but before it replied (inner select). Both selects also watch ctx.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() in handleReq: passed to store.Allow. Auto-cancelled by http.Server.Shutdown, so handlers parked in Allow wake instantly on shutdown and return 503.

How to run

make run          # builds to bin/rl and runs
# or
go run .

Server listens on :7777.

How to test

Basic rate limiting (single user)

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
done

Expected:

200
200
200
429
429

Per-client isolation

# 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/rl

Token refill

for 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/rl

Inactive client cleanup

Happens automatically if a user has been inactive for 5 minutes. Can be adjusted through

store.Start(ctx,time.Second)

in main.go

Concurrency (race detector)

go run -race .

Then run the curl tests above. The race detector should stay silent implying theres no race condition

Concurrency stress test

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
wait

Each user's bucket is independent so you should see a mix of 200/429 per user, no panics or hangs.

About

A per client token bucket rate limiter implementation in Go

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages