The token bucket strategy maintains a bucket of discrete tokens that refills continuously atDocumentation 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.
refillPerSec tokens per second. A request is admitted when at least cost tokens are present; those tokens are then consumed. When the bucket is empty (or below cost), the request is denied and nothing is consumed.
The bucket is lazily refilled — there is no background timer. On each check, ThrottleKit computes the elapsed time since the last refill, calculates how many tokens have accumulated, and clamps the total to capacity. This means refill is free unless a request arrives, and the bucket always starts full on a cold key.
Options
The bucket capacity: the maximum number of tokens the bucket can hold, and the largest instantaneous burst a cold key can absorb. When a key has been idle long enough for the bucket to fill completely, the first
capacity units of cost are admitted without any pacing delay.The sustained refill rate in tokens per second. Fractional values are accepted (e.g.,
0.5 for one token every two seconds). Together with capacity, this determines how long a depleted bucket takes to refill: capacity / (refillPerSec / 1000) milliseconds.State shape
The token bucket maintains two values per key:tokens— the current token count (fractional; lazily brought current on each check).last— the epoch-ms timestamp of whentokenswas last updated.
HASH (t and l fields) so it round-trips exactly using %.17g precision.
Code example
With a deterministic clock
Token bucket vs GCRA
Both token bucket and GCRA produce equivalent admission decisions, but they differ in what they surface and store:| Token Bucket | GCRA | |
|---|---|---|
| State per key | { tokens, last } (two floats) | One float (TAT) |
remaining field | Explicit token count | Derived from TAT math |
| Cold key behavior | Starts full (capacity tokens) | Admits burst requests instantly |
| Wire footprint | Redis HASH (two fields) | Redis GET/SET (one value) |
remaining value is the primary reason to choose token bucket over GCRA. When you surface remaining quota in API response headers (e.g., X-RateLimit-Remaining) and want clients to see a concrete token count rather than a derived estimate, token bucket makes that count directly available.
A denied request never consumes tokens.
remaining stays accurate across repeated denials, so clients can rely on it for backoff calculations.When to use token bucket
- Client-facing APIs where surfacing a concrete “tokens remaining” count in headers is important for client UX.
- Burst absorption with explicit visibility — when you want both a capacity cap and transparent reporting of how much headroom is left.
- Controlled bursts — when you want to distinguish “bucket empty right now” from “fully refilled” in client-side logic.