ratelimit
Package ratelimit provides in-memory token-bucket rate limiting keyed by a string (an IP address, account or API key) and HTTP middleware.
Limits are per process. Behind several instances each instance enforces its own limit; a shared store can implement the same behaviour later.
Stability: pre-1.0 (ADR-0015).
Constants#
const DefaultIdleTTL, …#
const (
DefaultIdleTTL = 10 * time.Minute
DefaultMaxKeys = 100_000
)Defaults for New.
Functions#
func ByRemoteIP#
func ByRemoteIP(r *http.Request) stringByRemoteIP keys requests by the connection's remote IP. Behind a proxy, run trusted-proxy middleware first so RemoteAddr holds the client address.
func Middleware#
func Middleware(l *Limiter, key KeyFunc, onLimit http.Handler) func(http.Handler) http.HandlerMiddleware limits requests with l. Limited requests receive onLimit, or a 429 application/problem+json response with a Retry-After header when onLimit is nil.
Types#
type KeyFunc#
type KeyFunc func(r *http.Request) stringKeyFunc extracts the rate-limit key from a request. An empty key skips limiting for that request.
type Limiter#
type Limiter struct {
// contains filtered or unexported fields
}A Limiter tracks one token bucket per key. It is safe for concurrent use.
func New#
func New(perSecond float64, burst int, opts ...Option) *LimiterNew returns a limiter allowing perSecond requests per key on average, with bursts of up to burst requests.
func (*Limiter) Allow#
func (l *Limiter) Allow(key string) (ok bool, retryAfter time.Duration)Allow reports whether a request for key may proceed. When it may not, retryAfter is how long until one token is available.
type Option#
type Option interface {
// contains filtered or unexported methods
}An Option configures a Limiter.
func WithClock#
func WithClock(now func() time.Time) OptionWithClock sets the time source, for tests.
func WithIdleTTL#
func WithIdleTTL(d time.Duration) OptionWithIdleTTL sets how long an unused key is remembered. Default: DefaultIdleTTL.
func WithMaxKeys#
func WithMaxKeys(n int) OptionWithMaxKeys bounds memory use. When the limit is reached and no idle keys can be evicted, new keys are allowed without tracking (fail open), so a flood of distinct keys can't lock out all clients. Default: DefaultMaxKeys.