Rate Limit
In-memory rate limiting using a token bucket (golang.org/x/time/rate) per client.
Limits requests per client IP within a configurable time window, with burst support
and no window-boundary spikes (unlike fixed-window counters).
Usage
r.Use(middleware.RateLimiter())
Configuration
config := middleware.DefaultRateLimiterConfig()
config.Limit = 100 // max requests (also the burst size)
config.Duration = 1 * time.Minute
r.Use(middleware.RateLimiterWithConfig(config))
Options
| Option | Default | Description |
|---|---|---|
Limit | 100 | Max requests per time window (also the burst capacity) |
Duration | 1m | Time window - refill rate = Limit / Duration |
KeyFunc | IP-based | Custom key function (e.g., user ID) |
Skipper | nil | Skip rate limiting for matching requests |
How It Works
Each client gets a token bucket. The bucket refills at Limit / Duration tokens per
second (e.g., 100 requests/min ≈ 1.67 tokens/sec). A client can burst up to Limit
requests instantly, then must wait for tokens to refill before sending more - no
reset-boundary spikes.
Response
When rate limited, returns 429 Too Many Requests. Includes X-RateLimit-Limit
and X-RateLimit-Remaining headers on every response.