Documentation
¶
Overview ¶
Package ratelimit implements a sliding-window-counter rate limiter with a two-phase Reserve/Commit API. Five strategies are supported: sliding-window, fixed-window, token-bucket, leaky-bucket, session-window. Concurrency is a special meter that works with any strategy: each reservation holds a lease that Commit releases and that otherwise expires after the rule's window.
This package is pure — it has no imports from github.com/wyolet/relay/internal. Relay-specific translation (catalog.ResolvedRule → Rule) lives in internal/ratelimit.
MeterSpend is a spend cap per calendar period rather than a rate: checked at Reserve, charged at Commit.
Fixed and sliding windows, token meters and spend keep plain counters (plain.go), which a limiter may count in memory and sync as deltas; CheckPlain decides on such counts as the reserve script does.
Expected kv ops per request:
- Reserve: 1 RunScript call (all counter checks + increments atomic), or none when every rule is an Alert spend rule, which Reserve does not check.
- PrepareReserve: the same script queued on the caller's kv.Batch, so it costs no round trip of its own; nothing is queued when Reserve would make no call.
- A reserve that failed after it may have run, with a concurrency rule: 1 detached RunScript releasing its lease, on the store ReleaseUnansweredOn names.
- Commit: 1 RunScript call (concurrency lease release + token post-increment), or none when it settles nothing: an uncancelled request whose rules meter neither concurrency nor tokens. PrepareCommit queues the same script on a caller's kv.Batch.
- CommitBoth: 1 batched round trip committing two reservations that live under different hash tags (inbound policy scope + upstream hostkey scope), replacing two sequential Commit calls. Each reservation's script is individually atomic; the batch is not cross-atomic (a single CROSSSLOT script across the two tags is impossible on Redis Cluster).
- CommitAll: the same for any number of reservations: 1 batched round trip, or 1 RunScript when one settles something.
- Peek: not on the request path; 1 batched round trip of read-only scripts, one per scope.
Index ¶
- Constants
- Variables
- func BucketStart(r Rule, t time.Time) (time.Time, error)
- func CheckPlain(r Rule, cur, prev int64, now time.Time) (time.Duration, bool)
- func CounterKey(scope string, r Rule, start, now time.Time) (string, time.Duration, error)
- func PlainCount(r Rule, cur, prev int64, now time.Time) float64
- func RegisterScripts(m *kv.Mem)
- func TokenCharge(meter string, tokens map[string]int64) int64
- type ExceededErrordeprecated
- type KeyQuotaExhausted
- type Limiter
- func (l *Limiter) Commit(ctx context.Context, res *Reservation, obs Observations) error
- func (l *Limiter) CommitAll(ctx context.Context, obs Observations, res ...*Reservation) ([]Rule, error)
- func (l *Limiter) CommitBoth(ctx context.Context, a, b *Reservation, obs Observations) error
- func (l *Limiter) NewBatch(size int) *kv.Batch
- func (l *Limiter) Peek(ctx context.Context, scopes []PeekScope) ([][]int64, error)
- func (l *Limiter) PrepareCommit(b *kv.Batch, res *Reservation, obs Observations) (*PreparedCommit, error)
- func (l *Limiter) PrepareReserve(b *kv.Batch, scope string, rules []Rule) (*PreparedReserve, error)
- func (l *Limiter) ReleaseUnansweredOn(post *Limiter) *Limiter
- func (l *Limiter) Reserve(ctx context.Context, scope string, rules []Rule) (*Reservation, error)
- func (l *Limiter) ReserveOrShed(ctx context.Context, scope string, rules []Rule) (*Reservation, error)
- type Observations
- type PeekScope
- type Period
- type PlainCounter
- type PreparedCommit
- type PreparedReserve
- type Reservation
- type Rule
- type Strategy
Constants ¶
const MeterRevoked = "revoked"
MeterRevoked is a pseudo-meter: it carries no budget, only the key whose existence revokes the caller's credential. Callers ride it on the Reserve they already run so revocation costs no extra round trip.
const MeterSpend = "spend"
MeterSpend counts spend in USD nanos per calendar period in UTC. Reserve refuses once the period's spend has reached Amount (>=, unlike the other meters' >) and reserves nothing; Commit charges Observations.CostNanos, so requests in flight may overshoot by their own cost. A new period starts from zero.
Variables ¶
var ErrExceeded = errors.New("limit: budget exceeded")
ErrExceeded is the sentinel wrapped by *KeyQuotaExhausted.
var ErrRevoked = errors.New("limit: credential revoked")
ErrRevoked is returned by Reserve when a MeterRevoked rule's key exists.
ErrUnavailable is returned by Reserve when the store did not answer in time, so the request's limits could not be checked.
Functions ¶
func BucketStart ¶ added in v0.20.0
BucketStart returns the start of the window bucket or calendar period r counts in at t, the one the reserve script would read at t.
func CheckPlain ¶ added in v0.20.0
CheckPlain decides a reserve of r at now against counts the caller holds, with the reserve script's comparisons and retry-after: cur and prev are the current and previous buckets (prev is unused by fixed windows and spend). It reports whether the request fits and, when it does not, how long until it may.
func CounterKey ¶ added in v0.20.0
CounterKey returns the store key of r's counter for the bucket starting at start, and the TTL a write at now gives it when it has none. A TTL of zero or less means the bucket is too old to be read by anyone.
func PlainCount ¶ added in v0.20.0
PlainCount is the count the reserve script compares with r's amount at now, before the request's own: the current bucket for fixed windows and spend, the weighted two-bucket count for sliding windows and token meters.
func RegisterScripts ¶
RegisterScripts registers the Go emulators for limit.reserve, limit.commit and limit.peek on the given MemStore. Called once per Limiter constructed from a MemStore.
func TokenCharge ¶ added in v0.20.0
TokenCharge is what a commit adds to a token meter for tokens: input plus output for the bare meter, the named count for "tokens.<key>". Cache, reasoning and server-tool counts have meters of their own, so summing the whole map would count a request several times.
Types ¶
type ExceededError
deprecated
type ExceededError = KeyQuotaExhausted
ExceededError is an alias kept for backward compatibility with callers that use the old name. New code should use KeyQuotaExhausted directly.
Deprecated: Use KeyQuotaExhausted.
type KeyQuotaExhausted ¶
KeyQuotaExhausted is returned by Reserve when a budget is violated. The name reflects that exceeding a per-key rule is the primary signal this type carries in the post-Pick path (pipeline issue #89).
func (*KeyQuotaExhausted) Error ¶
func (e *KeyQuotaExhausted) Error() string
func (*KeyQuotaExhausted) Unwrap ¶
func (e *KeyQuotaExhausted) Unwrap() error
type Limiter ¶
type Limiter struct {
// contains filtered or unexported fields
}
Limiter enforces rate-limit rules using pkg/kv for counters. One Limiter is shared across the process; concurrent calls are safe.
func (*Limiter) Commit ¶
func (l *Limiter) Commit(ctx context.Context, res *Reservation, obs Observations) error
Commit finalizes a Reservation via one RunScript call. Tokens are incremented post-hoc; concurrency leases are always released. A repeated Commit is a no-op only when the first one wrote the idempotency guard: an uncancelled commit of a reservation with no concurrency or token-meter rule settles nothing, makes no call and writes no guard, so a later cancelled Commit still refunds it.
obs.Tokens is a map[string]int64. Per-meter increments are derived as:
- meter "tokens": obs.Tokens["input"] + obs.Tokens["output"]
- meter "tokens.<key>": obs.Tokens["<key>"]
- meter "requests": always 1 (counted at Reserve; not post-hoc), taken back when obs.Cancelled
- meter "concurrency": the reservation's lease released
func (*Limiter) CommitAll ¶ added in v0.20.0
func (l *Limiter) CommitAll(ctx context.Context, obs Observations, res ...*Reservation) ([]Rule, error)
CommitAll commits several reservations, which may live under different hash tags, with the same obs: one round trip when more than one settles something and the store batches scripts. It returns the spend rules whose cap this commit's charge reached, which happens once per rule and period.
func (*Limiter) CommitBoth ¶ added in v0.9.8
func (l *Limiter) CommitBoth(ctx context.Context, a, b *Reservation, obs Observations) error
CommitBoth finalizes two reservations. When both are present and the runner supports batching, it commits them in a single round trip (one Redis pipeline) — the reservations live under different hash tags (inbound policy scope vs. upstream hostkey scope) so a single CROSSSLOT script is impossible; batching the two independent, individually-atomic commit scripts is the Cluster-safe way to collapse the two sequential round trips into one. Both reservations receive the same obs, matching the sequential Commit call pair.
Falls back to sequential Commit when only one reservation exists, when the runner is not batch-capable, or (returning joined errors) when a batched call fails. Semantics are byte-identical to two Commit calls because the per-reservation script and args are produced by the same builder.
func (*Limiter) NewBatch ¶ added in v0.20.0
NewBatch returns a kv batch on the limiter's store with room for size commands, for PrepareReserve.
func (*Limiter) Peek ¶ added in v0.20.0
Peek returns, per scope and rule, the count Reserve compares with the rule's amount before a new request's own: requests or tokens in the window, concurrency slots held, a token bucket's drawn tokens, a leaky bucket's level, a session window's count, a spend rule's USD nanos (alert rules included). A fractional count rounds up; a revocation rule reads 0.
It reads the keys Reserve would at the same instant, built by the same code, in one batched round trip for every scope, and writes nothing: no count, no TTL.
func (*Limiter) PrepareCommit ¶ added in v0.11.7
func (l *Limiter) PrepareCommit(b *kv.Batch, res *Reservation, obs Observations) (*PreparedCommit, error)
PrepareCommit queues the commit script for res on b, built exactly as Commit builds it. It returns nil when there is nothing to commit, as Commit would make no call.
func (*Limiter) PrepareReserve ¶ added in v0.11.7
PrepareReserve queues the reserve script for rules on b. The caller runs b, then calls Finish: same script, arguments and outcome as Reserve.
func (*Limiter) ReleaseUnansweredOn ¶ added in v0.11.7
ReleaseUnansweredOn runs the releases for reserves whose reply was lost on post's store, so they do not queue behind the admission calls that just timed out. Call before serving.
func (*Limiter) Reserve ¶
Reserve checks all rules and increments counters atomically via one RunScript call. On violation, all increments from this call are rolled back and *ExceededError is returned. scope is the Redis Cluster hash-tag anchor (e.g. "policy:prod-policy").
func (*Limiter) ReserveOrShed ¶ added in v0.11.7
func (l *Limiter) ReserveOrShed(ctx context.Context, scope string, rules []Rule) (*Reservation, error)
ReserveOrShed is Reserve for admission: while the store's connection wait queue is at its bound it returns ErrUnavailable at once with the script unsent, where Reserve would wait out the pool timeout to fail the same way.
type Observations ¶
type Observations struct {
Tokens map[string]int64
Cancelled bool
// CostNanos is the request's priced cost in USD nanos, charged to its MeterSpend rules unless Cancelled.
CostNanos int64
}
Observations are passed to Commit to supply post-hoc measurements. Tokens is a map of token-type → count (e.g. {"input": 300, "output": 200}). Legacy callers that only have a total may pass {"tokens": total}. Nil Tokens is treated as all-zero.
type PlainCounter ¶ added in v0.20.0
type PlainCounter uint8
PlainCounter names how a rule counts when its whole state is one store counter per window bucket or calendar period. Only such rules can be counted elsewhere and added to the store as deltas: the reserve script reads them with GET and the commit script writes them with INCRBY.
const ( NotPlain PlainCounter = iota PlainFixedWindow PlainSlidingWindow PlainTokens PlainSpend )
func PlainCounterOf ¶ added in v0.20.0
func PlainCounterOf(r Rule) PlainCounter
PlainCounterOf reports how r counts: token buckets, leaky buckets, session windows, concurrency leases and revocation checks are NotPlain.
type PreparedCommit ¶ added in v0.11.7
type PreparedCommit struct {
// contains filtered or unexported fields
}
PreparedCommit is a Commit queued on a kv batch; Finish reads its outcome once the batch has run.
func (*PreparedCommit) Crossed ¶ added in v0.20.0
func (p *PreparedCommit) Crossed() []Rule
Crossed returns the spend rules whose cap this commit's charge reached, as CommitAll does, once the batch has run.
func (*PreparedCommit) Err ¶ added in v0.11.7
func (p *PreparedCommit) Err() error
Err is the commit script's outcome as the batch left it, before Finish counts or logs it.
func (*PreparedCommit) Finish ¶ added in v0.11.7
func (p *PreparedCommit) Finish() error
Finish returns the commit script's failure, as Commit would.
type PreparedReserve ¶ added in v0.11.7
type PreparedReserve struct {
// contains filtered or unexported fields
}
PreparedReserve is a Reserve queued on a kv batch; Finish reads its outcome once the batch has run.
func (*PreparedReserve) Finish ¶ added in v0.11.7
func (p *PreparedReserve) Finish(ctx context.Context) (*Reservation, error)
Finish returns what Reserve would have: the reservation, *ExceededError, ErrRevoked, or the script's failure.
type Reservation ¶
type Reservation struct {
ID string
// contains filtered or unexported fields
}
Reservation is returned by a successful Reserve call.
func (*Reservation) NeedsCommit ¶ added in v0.11.7
func (r *Reservation) NeedsCommit(obs Observations) bool
NeedsCommit reports whether Commit would make a call for res with obs. Safe with a nil res.
func (*Reservation) SetNoCommit ¶ added in v0.10.0
func (r *Reservation) SetNoCommit()
SetNoCommit marks res as metering nothing, so Commit is a no-op. Set by callers that reserve only to run a check (token revocation) alongside no rate-limit rule.
type Rule ¶
type Rule struct {
// Key is the caller-built scope identifier used as the last segment of
// Redis keys. Example: "Route:test-route:rl-basic".
// The pkg prepends "limit:{<scope>}:" and a strategy prefix.
Key string
// Name is for human-readable error messages only (e.g. "requests on rl-basic").
Name string
// Meter is "requests" | "tokens" | "tokens.<suffix>" | "concurrency" |
// MeterRevoked | MeterSpend.
Meter string
// Strategy controls the rate-limit algorithm.
Strategy Strategy
// Amount is the budget (requests, tokens, or concurrency slots).
Amount int64
// Window is the measurement period. For concurrency rules it is the lease
// length: a slot whose Commit never arrives frees after it, and a request
// running longer stops counting.
Window time.Duration
// Period is the calendar period a MeterSpend rule's Amount covers; such a rule ignores Window and Strategy.
Period Period
// Alert makes a MeterSpend rule count without refusing: Reserve skips it and Commit still charges it.
Alert bool
}
Rule is a single rate-limit rule passed to Reserve by the caller. The caller is responsible for building Rule.Key as a stable, unique string that identifies the rule within its scope; a counter lives as long as its Key does.
type Strategy ¶
type Strategy string
Strategy names the rate-limiting algorithm for a Rule.
const ( // StrategyTokenBucket is the default. Tokens refill continuously at // amount/window rate; burst = amount. StrategyTokenBucket Strategy = "token-bucket" // StrategySlidingWindow uses a two-bucket weighted interpolation. StrategySlidingWindow Strategy = "sliding-window" // StrategyFixedWindow resets the counter at every floor(now/window) boundary. StrategyFixedWindow Strategy = "fixed-window" // StrategyLeakyBucket drains at a constant rate; excess is rejected. StrategyLeakyBucket Strategy = "leaky-bucket" // StrategySessionWindow anchors the window to the first request after a // reset; the window does not reset in the background. StrategySessionWindow Strategy = "session-window" )