Skip to Content
ZarexDocs

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:

server.ts
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

OptionValuesDefaultRole
capacityfrom 1 to 1,000,000requiredMaximum number of tokens in the bucket. A new visitor starts with a full bucket.
refillRatefrom 1 to 1,000,000requiredTokens given back at each elapsed interval.
interval"30s", "1m", "1h", "1d"… (366 days at most)requiredHow often the bucket refills.
characteristicslist of names (16 at most)["ip"]What identifies a visitor.
mode"LIVE" · "DRY_RUN" · "OFF""LIVE"Deny, only observe, or disable.

And in call:

ValueDefaultRole
tokensRequested1Tokens 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:

RequestResultTokens left
1st, 4 tokensallowed6
2nd, 4 tokensallowed2
3rd, 4 tokensdenied2 (a denied request spends nothing)
4th, 1 tokenallowed1
one second later, 4 tokensdenied3 (1 + 2 given back)
  • Refilling happens per full interval: refillRate tokens for each elapsed interval, never above capacity.
  • A denied request spends no tokens: the visitor can try again as soon as the bucket holds enough.
  • A request asking for more than capacity is 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, interval or characteristics gives everyone a new, full bucket;
  • characteristics combine, 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 a Retry-After header when trying again makes sense.

What the decision contains

The rule's result, in decision.results (ruleType: "TOKEN_BUCKET"), contains in reason:

FieldMeaning
tokens_remainingTokens left in the bucket after this request.
tokens_requestedTokens requested by this request.
capacityThe bucket's capacity.
retry_in_msDenied 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 }

On this page