ThrottleKit’s admission module provides higher-order building blocks for controlling whether work should be attempted at all, upstream of per-key rate limits. These APIs compose with the coreDocumentation Index
Fetch the complete documentation index at: https://mintlify.com/AmeyaBorkar/throttlekit/llms.txt
Use this file to discover all available pages before exploring further.
Limiter interface via combineDecisions and cover adaptive client-side throttling, weighted
max-min fairness, streaming token budgets, online learned reservations, analytics decoration,
approximate sketch-based limiting, and multi-dimensional enforcement.
All of these are exported from the top-level throttlekit package.
unifiedAdmission
Compose three orthogonal admission axes — rate, concurrency, and cost — into oneUnifiedAdmitter
via the combineDecisions algebra. Evaluation order is concurrency → rate → cost, first denial
short-circuits.
The rate axis — a
Limiter returning a Decision for (key, 1) per admit call.The concurrency axis — a
ConcurrencyGuard from adaptiveConcurrency(). State is local
(in-process); no store round trip.The cost axis — a
Limiter returning a Decision for (key, cost) where cost is the
per-request weight."sequential" (default) runs axes in order; first deny short-circuits. "lua-fused" collapses
rate + cost into one Redis EVALSHA — requires the fused option group."marginal" (default) admits when every axis independently allows. "joint-lp" additionally
applies a bid-price filter (value ≥ p_R + p_C · cost). @experimental.Injectable time source. Defaults to the system clock.
UnifiedAdmitter Methods
Async admit. Works for any backend mix.
Synchronous admit. Throws when any configured axis lacks a synchronous code path. Not available
with
backend: "lua-fused".Snapshot of the most recent admit’s per-axis decisions. Each call returns a fresh frozen object
safe to leak into telemetry. Short-circuited axes are
undefined.UnifiedAdmission Fields
The combined Decision across all configured axes.
Release the held concurrency slot when work finishes. Pass
dropped: true to signal overload.
Idempotent; a no-op on denied admissions.The axis whose denial bound this admission (
"rate" / "concurrency" / "cost"), or
undefined when admitted or when the joint-LP policy filter denied.true when the admission was denied specifically by the joint-LP bid-price filter — every
per-axis budget had slack, but value < p_R + p_C · cost. Absent or falsy under
policy: "marginal" or any axis-bound denial.tokenBudget
Windowed token-budget meter for post-hoc costs (e.g. LLM output tokens billed as they stream).Token budget
L enforced per window. Floored to an integer; must be ≥ 1.Window width in ms. Windows are epoch-aligned.
Injected clock. Defaults to the system clock.
Atomically debit
tokens (default 1) against the current window. Stop-at-boundary: a debit is
admitted iff budget remains before it (served < L).Promise-returning form of
debitSync. Resolves synchronously.Tokens remaining in the current window (
≥ 0). Rolls the window but does not debit.Forget all usage; the next call starts a fresh window.
distributedTokenBudget
The fleet-shared,Store-backed sibling of tokenBudget. The same stop-at-boundary rule run as an
atomic read-modify-write against a shared counter, so one budget L is enforced across every
gateway with per-token overshoot of 0 independent of fleet size.
adaptiveThrottle
Google SRE client-side adaptive throttling. Sheds requests locally before they leave the client when the backend’s accept rate drops.Acceptance multiplier
K from the SRE formula. Default 2. Higher values tolerate more backend
rejection before shedding locally. Must be ≥ 1.Rolling accounting window width in ms. Default
10_000.Injected clock. Defaults to the system clock.
Source of randomness for the probabilistic shed. Inject a seeded PRNG for deterministic tests.
Default
Math.random.Decide whether to send the next request. Returns
true to send, false to shed.
priority in [0, 1] scales the shed probability by (1 - priority).Feed back the backend’s outcome. Call only for sent requests (not shed ones).
The current local reject probability
p in [0, 1]. Read-only.A point-in-time snapshot for metrics and introspection: rolling request and accept counts plus
the current reject probability.
weightedFairShare
Weighted equal-share fairness across tenants. One global budget per epoch-aligned window, split proportionally to per-tenant weights.Global admissions budget shared across all tenants per window.
Window width in ms. Windows are epoch-aligned.
Per-tenant weight. Default
() => 1 (equal — equivalent to fairShare).Injected clock. Defaults to the system clock.
weightedMaxMin
Weighted max-min fair allocation of an integerlimit across tenants with known demands. Work-
conserving and weight-honoring. Returns integer credits per tenant.
weightedFairShare.
fairShare
Equal-share fairness across tenants — an online approximation of max-min fair allocation. One global budget oflimit admissions per epoch-aligned window is split so no single tenant can
monopolize it.
Global admissions budget shared across all tenants per window.
Window width in ms. Windows are epoch-aligned:
floor(now/windowMs)*windowMs.Injected clock. Defaults to the system clock.
Synchronous, zero-
await check for tenant with the given cost (default 1).Promise-returning form of
checkSync; resolves synchronously.Reset one tenant’s usage (it leaves the active set), or — with no argument — the whole window.
guaranteedShare
Compute the guaranteed weighted sharefloor(w_i · limit / W) for each tenant given their weights
and a total limit. Returns the static floor a weighted max-min split never drops a backlogged tenant
below.
criticalFractile
The critical-fractile quantile levelτ = overrunCost / (holdCost + overrunCost) — the cost
quantile that minimises the asymmetric newsvendor / pinball loss, and the target
learnedReservation descends onto.
learnedReservation
Online newsvendor learner for per-request token reservations. Descends onto the cost-optimalcriticalFractile quantile with O(√T) regret. @experimental.
Penalty per token reserved but unused. Must be
> 0.Penalty per token of realised cost beyond the reservation. Must be
> 0.Upper clamp on the reservation (the per-request cap
m). Must be > 0.Lower clamp on the reservation. Default
0.predictiveReservation
Learning-augmented reservation. Blends a per-request output-length prediction with the robustlearnedReservation via a Hedge meta-learner: accurate predictions drive cost toward the
clairvoyant optimum; adversarial ones fall back to the no-regret quantile. @experimental.
withAnalytics
Wrap aLimiter to track its traffic in-process with Space-Saving top-K heavy hitter detection.
Zero config, no OpenTelemetry required. @experimental.
How many heavy hitters each summary tracks. Default
10.Fixed, epoch-aligned window width in ms. Default
60_000.Injected clock.
tapDecisions
Wrap aLimiter so a callback fires once per completed check. The tap never breaks the limiter —
exceptions inside it are caught and dropped.
sketchRateLimit
Approximate, fixed-memory rate limiter over an unbounded key universe backed by a Count-Min Sketch. Memory isO(1/epsilon · ln(1/delta)) — independent of key count. Never over-admits
(hard, non-probabilistic guarantee). @experimental.
Maximum requests admitted per key within each window.
Window width in ms. Epoch-aligned.
Additive accuracy: overestimates a key’s count by at most
epsilon * N. Default 0.01.Failure probability for the epsilon bound. Default
0.001.Use the Estan–Varghese conservative-update rule for tighter estimates. Default
true.32-bit hash seed. Defaults to a per-instance random value (recommended). Pass a fixed value only
for reproducible tests.
multiRateLimit / all / any
Multi-dimensional limiter: evaluate per-IP ∧ per-user ∧ per-route (etc.) atomically. On a synchronous store reads all dimensions, decides, then commits all-or-none. On Redis fuses every dimension into a single Lua round trip.all(dimensions)— allow only if every dimension allows. Consume nothing unless all allow (no partial consume).any(dimensions)— allow if any dimension allows. Consume only the dimensions that individually allow.