Documentation
¶
Overview ¶
Package ratelimit provides token-bucket rate limiting keyed by a string (an IP address, account or API key): the Taker interface, an in-memory Limiter, and HTTP middleware.
The in-memory limiter is per process: behind several instances each one enforces its own limit. gorbital.dev/modules/ratelimitpg implements Taker with limits shared across instances (ADR-0052).
Stability: stable (ADR-0015, ADR-0054).
Index ¶
Constants ¶
const ( DefaultIdleTTL = 10 * time.Minute DefaultMaxKeys = 100_000 )
Defaults for New.
Variables ¶
var ErrEmptyKey = errors.New("ratelimit: empty key")
ErrEmptyKey reports a request without a key.
Functions ¶
func ByRemoteIP ¶
ByRemoteIP keys requests by the connection's remote IP, grouped as ClientKey does. Behind a proxy, run trusted-proxy middleware first so RemoteAddr holds the client address.
func ClientKey ¶
ClientKey returns the rate-limit key of a client IP address: an IPv4 address as it is, and an IPv6 address as its /64 network, since one host or customer usually holds a whole /64 and could otherwise use a new address, and a new budget, for every request. IPv4-mapped IPv6 addresses count as IPv4, and zones are ignored. A value that isn't an IP address is returned unchanged.
func Middleware ¶
Middleware limits requests with l. Limited requests receive onLimit, or a 429 application/problem+json response with a Retry-After header when onLimit is nil. When l can't decide, the request proceeds.
Types ¶
type Decision ¶
type Decision struct {
Allowed bool
// RetryAfter is how long until a request may proceed, when not allowed.
RetryAfter time.Duration
}
Decision is the outcome of one request against a limit.
type KeyFunc ¶
KeyFunc extracts the rate-limit key from a request. An empty key skips limiting for that request.
type Limit ¶
Limit is a token bucket: PerSecond requests on average, with bursts of up to Burst.
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 ¶
New returns a limiter allowing perSecond requests per key on average, with bursts of up to burst requests.
type Option ¶
type Option interface {
// contains filtered or unexported methods
}
An Option configures a Limiter.
func WithIdleTTL ¶
WithIdleTTL sets how long an unused key is remembered. Default: DefaultIdleTTL.
func WithMaxKeys ¶
WithMaxKeys 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.