apistockdocs
v0.4 GitHub apistock.dev
Technical/Core packages

ratelimit

import "apistock.dev/ratelimit"Source on GitHub

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, …#

go
const (
	DefaultIdleTTL = 10 * time.Minute
	DefaultMaxKeys = 100_000
)

Defaults for New.

Functions#

func ByRemoteIP#

go
func ByRemoteIP(r *http.Request) string

ByRemoteIP keys requests by the connection's remote IP. Behind a proxy, run trusted-proxy middleware first so RemoteAddr holds the client address.

func Middleware#

go
func Middleware(l *Limiter, key KeyFunc, onLimit http.Handler) func(http.Handler) http.Handler

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.

Types#

type KeyFunc#

go
type KeyFunc func(r *http.Request) string

KeyFunc extracts the rate-limit key from a request. An empty key skips limiting for that request.

type Limiter#

go
type Limiter struct {
	// contains filtered or unexported fields
}

A Limiter tracks one token bucket per key. It is safe for concurrent use.

func New#

go
func New(perSecond float64, burst int, opts ...Option) *Limiter

New returns a limiter allowing perSecond requests per key on average, with bursts of up to burst requests.

func (*Limiter) Allow#

go
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#

go
type Option interface {
	// contains filtered or unexported methods
}

An Option configures a Limiter.

func WithClock#

go
func WithClock(now func() time.Time) Option

WithClock sets the time source, for tests.

func WithIdleTTL#

go
func WithIdleTTL(d time.Duration) Option

WithIdleTTL sets how long an unused key is remembered. Default: DefaultIdleTTL.

func WithMaxKeys#

go
func WithMaxKeys(n int) Option

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.

v0.4
esc
↑↓ move↵ openesc close