Rate Limit
Added: v1.0.0
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
go
r.Use(middleware.RateLimiter())With Config
go
r.Use(middleware.RateLimiterWithConfig(middleware.RateLimiterConfig{
Limit: 200,
Duration: time.Minute,
KeyFunc: func(r *http.Request) string {
return r.Header.Get("X-API-Key")
},
Skipper: zen.SkipPaths("/health"),
}))Or start from defaults and modify:
go
config := middleware.DefaultRateLimiterConfig()
config.Limit = 200
config.Duration = 1 * time.Minute
config.KeyFunc = func(r *http.Request) string {
return r.Header.Get("X-API-Key")
}
config.Skipper = zen.SkipPaths("/health")
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, API key) |
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. Successful responses include X-RateLimit-Limit (the burst capacity) and X-RateLimit-Remaining headers; these are not set on rejected requests.