Token-Bucket Rate Limiter
Source: Custom
Topics: Channels, time.Ticker, Context
Problem
Implement a token-bucket rate limiter.
Requirements:
New(rps int, burst int) *Limiter — create a limiter allowing rps tokens per second with an initial burst of burst.
Allow() bool — consume and return a token immediately if one is available, otherwise return false.
Wait(ctx context.Context) error — block until a token is available or ctx is cancelled; return ctx.Err() on cancellation.
Type:
type Limiter struct { ... }
func New(rps int, burst int) *Limiter
func (l *Limiter) Allow() bool
func (l *Limiter) Wait(ctx context.Context) error
Key concepts
- Token bucket via buffered channel:
make(chan struct{}, burst) holds available tokens.
- time.NewTicker: a background goroutine fires
rps times per second and adds one token; uses select default to skip if bucket is full.
- Non-blocking select:
Allow uses default to return false immediately if no token is available.
- Context-aware select:
Wait selects on both l.tokens and ctx.Done().
Run
go test -v -bench=. -benchmem ./challenges/concurrency/rate-limiter/
Sign in to submit your solution.