Skip to main content

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

OptionDefaultDescription
Limit100Max requests per time window (also the burst capacity)
Duration1mTime window - refill rate = Limit / Duration
KeyFuncIP-basedCustom key function (e.g., user ID)
SkippernilSkip 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.