Documentation
¶
Overview ¶
Package ratelimit holds the token buckets of a policy's rate limits (design 0009, #705): one engine-wide Store of every limit's buckets, per key, in a fixed-size table.
A bucket is stored with the generic cell rate algorithm (GCRA): one int64, the time at which it will be full again (the theoretical arrival time, TAT). A bucket whose TAT is past is full, exactly as if it were absent, which is what makes evicting it safe.
The table is sharded: each shard is a mutex and an open-addressed array of 40-byte entries with no pointers, so the garbage collector never scans it and nothing is allocated per request. A key lives in the 8 slots from its hashed one; when they are all taken, a free entry (a full bucket, or one of a limit no longer in the bundle) is reused first, then the one closest to full for its own limit. A bucket over its limit, or limited recently, is reused only when its limit holds more than its share of the neighbourhood; when none can be, the new key is counted in one of its limit's overflow buckets, chosen by its hash.
Index ¶
- Constants
- func Capacity(keys int, memLimit int64) int
- type Decision
- type Identity
- type Key
- type Limit
- type Live
- type Store
- func (s *Store) AllowEvent(l Limit, t time.Time) bool
- func (s *Store) Capacity() int
- func (s *Store) Collectors() []prometheus.Collector
- func (s *Store) EventsDropped() uint64
- func (s *Store) Evictions() (idle, active uint64)
- func (s *Store) EvictionsOverShare() uint64
- func (s *Store) Exceeded(detect bool)
- func (s *Store) HeaderKey(value string) Key
- func (s *Store) Intern(id Identity) uint32
- func (s *Store) Keys() int64
- func (s *Store) Limit(id Identity, requests int64, period time.Duration, burst int64) Limit
- func (s *Store) Observe(l Limit, k Key, t time.Time, live *Live) Decision
- func (s *Store) ObserveN(l Limit, k Key, t time.Time, live *Live, n int64) Decision
- func (s *Store) Overflows() uint64
- func (s *Store) Peek(l Limit, k Key, t time.Time) Decision
- func (s *Store) Refund(l Limit, k Key, d Decision)
- func (s *Store) RefundN(l Limit, k Key, d Decision, n int64)
- func (s *Store) Settle(l Limit, k Key, d Decision, t time.Time, delta int64)
- func (s *Store) SkippedNoKey()
- func (s *Store) Take(l Limit, k Key, t time.Time, live *Live) Decision
- func (s *Store) TakeN(l Limit, k Key, t time.Time, live *Live, n int64) Decision
- func (s *Store) TokenLimit(id Identity, tokens int64, period time.Duration, burst int64) Limit
- func (s *Store) Unsample(l Limit, k Key, n uint32)
- func (s *Store) Wait(l Limit, k Key, t time.Time) time.Duration
- func (s *Store) WaitN(l Limit, k Key, t time.Time, n int64) time.Duration
Constants ¶
const ( // EventsPerLimit caps the security events of one limit, per second. EventsPerLimit = 100 // EventsPerEngine caps the security events of every limit together, // per second: at EventsPerLimit, one flooded limit would fill the // engine's event buffer (10,000 events) in 100 s while its operator is // away, pushing out the attacks that matter. EventsPerEngine = 10 )
const DefaultKeys = 262_144
DefaultKeys is the table's default capacity: buckets held at once per engine (--rate-limit-keys).
const MaxDebt = time.Hour
MaxDebt is how long a key's debt may keep it over a token limit at most, unless twice the limit's window (two bursts) is longer: one request that used far more than its estimate is owed in full, up to an hour of the limit's rate.
Variables ¶
This section is empty.
Functions ¶
Types ¶
type Decision ¶
type Decision struct {
// Allowed is whether the request is within the limit (it was charged).
Allowed bool
// RetryAfter is, when not Allowed, how long until it would be: whole
// seconds, at least one.
RetryAfter time.Duration
// Event is whether this limited request becomes a security event: the
// key's first limited request, then one a minute.
Event bool
// Sampled is, with Event, the limited requests the event stands for,
// this one included.
Sampled uint32
// contains filtered or unexported fields
}
Decision is a limit's answer for one request.
type Identity ¶
type Identity struct {
// PolicyUID is the policy's UID.
PolicyUID string
// Name is the limit's name, unique in the policy.
Name string
// Key is the key spec, for example "ip/56" or "header/x-api-key".
Key string
}
Identity names a limit across bundles: the same identity keeps its ID, and so its buckets, whatever its rate and burst.
type Key ¶
type Key struct {
// contains filtered or unexported fields
}
Key is what a limit counts by: a client address, masked, or a keyed hash of a header's value. The zero Key is no key.
type Limit ¶
type Limit struct {
// contains filtered or unexported fields
}
Limit is a compiled rate limit: requests per period per key, in bursts of at most burst.
type Live ¶
type Live struct {
// contains filtered or unexported fields
}
Live is the set of limit IDs of one compiled bundle: an entry of a limit not in it is free. The nil Live holds every ID.
type Store ¶
type Store struct {
// contains filtered or unexported fields
}
Store holds the buckets of every limit of every policy, shared by every bundle's compiled policies, so a bundle swap keeps them. It is safe for concurrent use.
func New ¶
New returns a Store of at most keys buckets, fewer when keys entries would take more than a quarter of memLimit (the Go runtime's soft memory limit, GOMEMLIMIT; math.MaxInt64 or less than 1 means none, and then 64 MiB at most). Capacity reports what it holds.
func (*Store) AllowEvent ¶
AllowEvent reports whether a sampled event of limit l at t is kept, under the per-limit and engine-wide caps. A refused one is counted as dropped.
func (*Store) Collectors ¶
func (s *Store) Collectors() []prometheus.Collector
Collectors returns the Store's metrics. None is labelled by limit or key: both are unbounded.
func (*Store) EventsDropped ¶
EventsDropped is the sampled events the caps left out.
func (*Store) Evictions ¶
Evictions reports the entries reused for a new key: idle ones (a full bucket, or a limit no longer live: nothing lost) and active ones (the bucket closest to full, whose state is forgotten).
func (*Store) EvictionsOverShare ¶
EvictionsOverShare reports the entries reused for a new key although they were protected (over their limit, or limited recently): every entry was, and theirs was a limit holding more than its share of the neighbourhood.
func (*Store) HeaderKey ¶
HeaderKey is the key of a header's value: a 64-bit hash keyed with the Store's seed, so neither memory nor events hold the value.
func (*Store) Intern ¶
Intern returns the ID of a limit's identity, the same for the life of the Store. IDs are never reused.
func (*Store) Keys ¶
Keys is the buckets the Store holds now, full ones included until they are reused.
func (*Store) Limit ¶
Limit compiles a limit of the identity id: requests per period, in bursts of burst (requests when not positive). requests and period are at least 1 and 1ns.
func (*Store) Observe ¶
Observe is Take for a limit that only logs (Detect): its buckets are never protected from eviction, so an observed limit can't push others' keys out, and a key find holds no entry for is let through uncounted rather than share an overflow bucket whose refusals would be logged against it.
func (*Store) ObserveN ¶
ObserveN is Observe for a request that weighs n tokens. A key the table can't hold is let through uncounted: its Decision isn't Counted.
func (*Store) Overflows ¶
Overflows reports the requests of new keys find held no entry for: every entry of their neighbourhood was protected, and no limit held more than its share of it. A Block limit's are counted in an overflow bucket, a Detect limit's aren't counted.
func (*Store) Peek ¶
Peek is Take without the charge, of a Block TokenLimit: whether key k has a token left at t, a limited request sampled into events as Take samples it. A token limit refuses a key in debt with it before the request's weight is known. It only looks: a key the table doesn't hold is looked for in the limit's overflow bucket, if it has one, and is allowed otherwise (nothing counted, nothing owed); no entry is claimed.
func (*Store) Refund ¶
Refund gives back the token a request took from l for key k, when a later limit refused it; d is Take's decision for it.
func (*Store) RefundN ¶
RefundN gives back the n tokens a request took; d is TakeN's decision for it.
func (*Store) Settle ¶
Settle corrects key k's bucket of l, a TokenLimit, by delta tokens at t, d being TakeN's or ObserveN's decision for the request: a request charged an estimate that its response says it used delta more (debt: the bucket fills later) or -delta fewer (a refund). A key in debt is over the limit until the bucket refills past it. A refund is bounded by the burst; a debt, and the bucket's whole debt however many responses settle at once, by the debt horizon: MaxDebt of the limit's rate, or two bursts when more. So a key isn't put out for longer than that, and the cap still keeps the clock from overflowing.
func (*Store) SkippedNoKey ¶
func (s *Store) SkippedNoKey()
SkippedNoKey counts a request an IP limit couldn't count: no valid client address.
func (*Store) Take ¶
Take checks the request of key k at t against l and, when it is within the limit, charges it, in one step. live is the compiled bundle's set of limits, for reusing the entries of others.
func (*Store) TakeN ¶
TakeN is Take for a request that weighs n tokens (an LLM request's estimated tokens, design 0012 §6), of a TokenLimit: GCRA with a weight, the request taking n tokens in one step, or none. A request heavier than the burst never fits.
func (*Store) TokenLimit ¶
TokenLimit is Limit for a limit of tokens (design 0012 §6), which TakeN, ObserveN, Peek and Settle charge: its burst is at most what keeps the window (burst × interval) within a quarter of the clock's range, so a weighted request on top of the most debt Settle leaves (two windows, or MaxDebt) can't overflow it. A burst of a billion tokens at one an hour is cut to about 640 million.
func (*Store) Unsample ¶
Unsample gives back the n limited requests a sampled event stood for, when the event caps dropped it: the key's next event counts them. A key the table doesn't hold (evicted, or counted in an overflow bucket, whose events stand for several keys) gets nothing back.