Token budget
Give each visitor a budget that refills over time, and spend it according to the real cost of each request.
The token budget fits when not all requests are equal: a call to an AI model, for example, costs more than a simple read. Each visitor has a bucket of tokens that refills regularly; each request spends a certain number of them. When the bucket is empty, the request is denied with a 429 response.
The problem
A rate limit treats every request the same. But a call to an AI model, a document generation or an SMS costs far more than displaying a page: a user can stay under the request limit while costing you a lot.
What it stops
- overconsumption of an expensive resource: AI tokens, SMS, compute;
- abuse of a free plan or a trial;
- spikes that exceed your budget, while still letting reasonable bursts through.
When to use it
Chatbots and AI features, exports, message sending: anywhere you want a budget per user and per period, rather than a plain number of requests.
Configuration
import { tokenBucket } from "@zarex/express"; // or your framework's package
rules: [tokenBucket({ capacity: 100, refillRate: 10, interval: "1m" })],Here, each visitor has at most 100 tokens, and gets 10 back every minute.
Spending several tokens
By default, a request spends 1 token. Give the real cost with tokensRequested:
app.use(
"/api/chat",
zarex({
key: process.env.ZAREX_KEY!,
rules: [
tokenBucket({
capacity: 5000,
refillRate: 500,
interval: "1h",
characteristics: ["userId"],
}),
],
call: (req) => ({
characteristics: { userId: req.user?.id },
tokensRequested: estimateCost(req.body),
}),
})
);Options
| Option | Values | Default | Role |
|---|---|---|---|
capacity | from 1 to 1,000,000 | required | Maximum number of tokens in the bucket. A new visitor starts with a full bucket. |
refillRate | from 1 to 1,000,000 | required | Tokens given back at each elapsed interval. |
interval | "30s", "1m", "1h", "1d"… (366 days at most) | required | How often the bucket refills. |
characteristics | list of names (16 at most) | ["ip"] | What identifies a visitor. |
mode | "LIVE" · "DRY_RUN" · "OFF" | "LIVE" | Deny, only observe, or disable. |
And in call:
| Value | Default | Role |
|---|---|---|
tokensRequested | 1 | Tokens spent by this request. A positive whole number; any other value counts as 1. |
How the bucket empties and refills
Measured example with capacity: 10, refillRate: 2, interval: "1s", and requests of 4 tokens:
| Request | Result | Tokens left |
|---|---|---|
| 1st, 4 tokens | allowed | 6 |
| 2nd, 4 tokens | allowed | 2 |
| 3rd, 4 tokens | denied | 2 (a denied request spends nothing) |
| 4th, 1 token | allowed | 1 |
| one second later, 4 tokens | denied | 3 (1 + 2 given back) |
- Refilling happens per full interval:
refillRatetokens for each elapsedinterval, never abovecapacity. - A denied request spends no tokens: the visitor can try again as soon as the bucket holds enough.
- A request asking for more than
capacityis always denied, since the bucket can never hold that many. Plan a capacity above the cost of your largest request.
What it shares with rate limiting
As with rate limiting:
- the bucket depends on the rule's settings and on the visitor, not on the route: the same rule on two routes shares the same bucket;
- changing
capacity,refillRate,intervalorcharacteristicsgives everyone a new, full bucket; characteristicscombine, fall back to the IP when none is present, and must never be limited to a value shared by all your visitors (see this reminder);- an IP address can be shared by many visitors: on a public route, combine a loose per-IP limit with a per-account limit (see Shared IP addresses);
- in
DRY_RUN, nothing is blocked, and the decision log shows what would have been denied; - a denial answers
429, with aRetry-Afterheader when trying again makes sense.
What the decision contains
The rule's result, in decision.results (ruleType: "TOKEN_BUCKET"), contains in reason:
| Field | Meaning |
|---|---|
tokens_remaining | Tokens left in the bucket after this request. |
tokens_requested | Tokens requested by this request. |
capacity | The bucket's capacity. |
retry_in_ms | Denied request: milliseconds before the bucket holds enough tokens. Allowed request: before the next refill. 0 for a request larger than capacity, which will never go through. |
Example, the 3rd request of the table above (denied):
{ "tokens_remaining": 2, "tokens_requested": 4, "capacity": 10, "retry_in_ms": 999 }