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.
Expected kv ops per request:
- Reserve: 1 RunScript call (all counter checks + increments atomic).
- PrepareReserve: the same script queued on the caller's kv.Batch, so it costs no round trip of its own.
- 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).
Index ¶
- Constants
- Variables
- func RegisterScripts(m *kv.Mem)
- type ExceededErrordeprecated
- type KeyQuotaExhausted
- type Limiter
- func (l *Limiter) Commit(ctx context.Context, res *Reservation, obs Observations) error
- func (l *Limiter) CommitBoth(ctx context.Context, a, b *Reservation, obs Observations) 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 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.
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 RegisterScripts ¶
RegisterScripts registers the Go emulators for limit.reserve and limit.commit on the given MemStore. Called once per Limiter constructed from a MemStore.
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)
- meter "concurrency": the reservation's lease released
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) 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 ¶
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 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) 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.
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
}
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" )