ratelimit

package
v0.7.0-rc.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 29, 2026 License: Apache-2.0 Imports: 10 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

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

View Source
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
)
View Source
const DefaultKeys = 262_144

DefaultKeys is the table's default capacity: buckets held at once per engine (--rate-limit-keys).

View Source
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

func Capacity

func Capacity(keys int, memLimit int64) int

Capacity is the buckets a Store of keys holds under memLimit: keys, or fewer when they would take more than a quarter of memLimit, or of 64 MiB without one.

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.

func (Decision) Counted

func (d Decision) Counted() bool

Counted reports whether the request was charged to a bucket: Allowed and counted, so RefundN and Settle have one to correct.

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.

func IPKey

func IPKey(a netip.Addr, v6Prefix int) (Key, bool)

IPKey is the key of the client address a: IPv4 by its address (an IPv4-mapped IPv6 address counts as IPv4), IPv6 by its first v6Prefix bits. It reports false for an invalid address, which no IP key counts.

func (Key) Valid

func (k Key) Valid() bool

Valid reports whether k is a 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.

func (Limit) Burst

func (l Limit) Burst() int64

Burst is the most a key may take at once.

func (Limit) ID

func (l Limit) ID() uint32

ID is the limit's ID in its Store.

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.

func NewLive

func NewLive(limits ...Limit) *Live

NewLive returns the set of limits.

func (*Live) Add

func (s *Live) Add(l Limit)

Add adds l to the set.

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

func New(keys int, memLimit int64) *Store

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

func (s *Store) AllowEvent(l Limit, t time.Time) bool

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) Capacity

func (s *Store) Capacity() int

Capacity is the buckets the Store holds at most.

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

func (s *Store) EventsDropped() uint64

EventsDropped is the sampled events the caps left out.

func (*Store) Evictions

func (s *Store) Evictions() (idle, active uint64)

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

func (s *Store) EvictionsOverShare() uint64

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) Exceeded

func (s *Store) Exceeded(detect bool)

Exceeded counts a request over a limit: denied, or logged (detect).

func (*Store) HeaderKey

func (s *Store) HeaderKey(value string) Key

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

func (s *Store) Intern(id Identity) uint32

Intern returns the ID of a limit's identity, the same for the life of the Store. IDs are never reused.

func (*Store) Keys

func (s *Store) Keys() int64

Keys is the buckets the Store holds now, full ones included until they are reused.

func (*Store) Limit

func (s *Store) Limit(id Identity, requests int64, period time.Duration, burst int64) 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

func (s *Store) Observe(l Limit, k Key, t time.Time, live *Live) Decision

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

func (s *Store) ObserveN(l Limit, k Key, t time.Time, live *Live, n int64) Decision

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

func (s *Store) Overflows() uint64

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

func (s *Store) Peek(l Limit, k Key, t time.Time) Decision

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

func (s *Store) Refund(l Limit, k Key, d Decision)

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

func (s *Store) RefundN(l Limit, k Key, d Decision, n int64)

RefundN gives back the n tokens a request took; d is TakeN's decision for it.

func (*Store) Settle

func (s *Store) Settle(l Limit, k Key, d Decision, t time.Time, delta int64)

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

func (s *Store) Take(l Limit, k Key, t time.Time, live *Live) Decision

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

func (s *Store) TakeN(l Limit, k Key, t time.Time, live *Live, n int64) Decision

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

func (s *Store) TokenLimit(id Identity, tokens int64, period time.Duration, burst int64) Limit

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

func (s *Store) Unsample(l Limit, k Key, n uint32)

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.

func (*Store) Wait

func (s *Store) Wait(l Limit, k Key, t time.Time) time.Duration

Wait is how long until key k's request at t would be within l, without charging it: 0 when it is now, whole seconds otherwise.

func (*Store) WaitN

func (s *Store) WaitN(l Limit, k Key, t time.Time, n int64) time.Duration

WaitN is Wait for a request of n tokens.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL