Documentation
¶
Overview ¶
Package ratelimit provides a per-key token-bucket rate limiter. It is used to throttle login and public HTTP endpoints (FA-API-07).
The limiter keeps one bucket per key. Each bucket holds up to Burst tokens and refills at Rate tokens per second; a request consumes one token. The number of buckets is bounded by Limit to protect against memory exhaustion through many distinct keys (for example spoofed client addresses).
Index ¶
Constants ¶
const DefaultLimit = 100_000
DefaultLimit is the number of keys a Limiter created by New keeps before it starts evicting buckets. A zero Limit field also falls back to it.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Limiter ¶
type Limiter struct {
// Rate is the number of tokens refilled per second. It should be > 0;
// a non-positive Rate disables refilling.
Rate float64
// Burst is the bucket size, the maximum number of requests allowed at once.
// Values below 1 are treated as 1.
Burst int
// Limit is the maximum number of keys kept. When the limit is reached and
// a new key arrives, buckets that are full again are dropped first; if none
// are full, the least recently used bucket is dropped.
Limit int
// Now returns the current time. Nil means time.Now. It is intended to be
// replaced in tests.
Now func() time.Time
// contains filtered or unexported fields
}
Limiter allows Burst requests per key at once and refills Rate tokens per second.
A Limiter must not be copied after first use. The zero value is usable once Rate and Burst are set; Limit falls back to DefaultLimit when it is not positive. Limiter is safe for concurrent use.
func New ¶
New returns a limiter with rate tokens per second, the given burst and a key limit of DefaultLimit.