Skip to content
Help guide the future of agentgateway — Take the survey

Rate limit token budgets

Verified : Automated tests passed for: Configuration files: The configuration files on this page were checked against their schema.
Page as Markdown

Cap LLM token usage with a token bucket, gateway-wide or per user, in agentgateway’s memory or in a rate limit server.

Cap LLM token usage with a token bucket, per user or gateway-wide.

About rate limit token budgets

A rate limit token budget caps token usage with a token bucket rather than a fixed window. Each user or API key draws down its own bucket, and the bucket refills at a configured interval. While a bucket is empty, agentgateway rejects that user’s requests with a 429.

Unlike a per-key budget, a rate limit token budget needs no database, and it works in both standalone and Kubernetes mode. It counts tokens only, so it caps spend as an estimate rather than as a true dollar cap.

Note

Agentgateway checks a token-based rate limit in two phases, at request time and at response time. The provider reports the completion token count only in the response. For details, see Token-based rate limits.

The input count that a request debits includes the tokens that the provider read from or wrote to its prompt cache. Anthropic and Amazon Bedrock exclude cached tokens from the count that they report. A cache-heavy request against those providers therefore debits more than their reported input count. For more information, see Token usage fields.

Set a per-user token budget

To give every user a separate budget, use remoteRateLimit with a descriptor that keys on the API key identity. The rate limit server then holds the per-user counters. To deploy the server, see Deploy a rate limit server. The following examples assume that the server is reachable at localhost:8081.

  1. Configure agentgateway to send a per-user descriptor to the rate limit server. For a description of each field, see the table after the examples.

    # yaml-language-server: $schema=https://agentgateway.dev/schema/config
    llm:
      policies:
        apiKey:
          mode: strict
          keys:
          - key: sk-alice-abc123def456
            metadata:
              user: alice
          - key: sk-bob-xyz789uvw012
            metadata:
              user: bob
        remoteRateLimit:
          host: localhost:8081
          domain: token-budgets
          descriptors:
          - entries:
            - key: user_id
              # A key without a user in its metadata counts against one shared "unassigned" budget.
              value: 'has(apiKey.user) ? apiKey.user : "unassigned"'
            type: tokens
      models:
      - name: "*"
        provider: openAI
        params:
          apiKey: "$OPENAI_API_KEY"
  2. Configure the rate limit server with a per-user daily token budget. The key matches the descriptor entry key that agentgateway sends.

    # ratelimit-config/config.yaml
    domain: token-budgets
    descriptors:
      - key: user_id
        rate_limit:
          unit: day
          requests_per_unit: 100000  # 100,000 tokens per user per day

When a user reaches their daily budget, agentgateway rejects further requests with a 429 until the bucket refills.

By default, each request is charged its total token count, input plus output. To charge something else, set cost on the descriptor to a CEL expression. For example, cost: llm.outputTokens budgets only the tokens that the model generates.

# yaml-language-server: $schema=https://agentgateway.dev/schema/config
llm:
  policies:
    apiKey:
      mode: strict
      keys:
      - key: sk-alice-abc123def456
        metadata:
          user: alice
      - key: sk-bob-xyz789uvw012
        metadata:
          user: bob
    remoteRateLimit:
      host: localhost:8081
      domain: token-budgets
      descriptors:
      - entries:
        - key: user_id
          value: 'has(apiKey.user) ? apiKey.user : "unassigned"'
        type: tokens
        # Charge each request only the tokens that the model generated.
        cost: llm.outputTokens
  models:
  - name: "*"
    provider: openAI
    params:
      apiKey: "$OPENAI_API_KEY"
FieldDescription
apiKey.modeHow agentgateway handles requests without a valid API key. With strict, it rejects them. With optional, a request that has no API key passes and counts against the shared unassigned budget.
apiKey.keys[].metadataValues that agentgateway attaches to requests that use the key. CEL expressions read each value as apiKey.<name>, such as apiKey.user.
remoteRateLimit.hostThe address of the rate limit server.
remoteRateLimit.domainThe domain of the limits on the rate limit server, here token-budgets.
remoteRateLimit.descriptors[].entries[].keyThe descriptor key that the rate limit server matches, here user_id.
remoteRateLimit.descriptors[].entries[].valueA CEL expression for the descriptor value. Each user from the API key metadata gets a separate budget. The has() check gives a key without a user in its metadata the shared unassigned budget. Without the check, agentgateway skips the descriptor for that key, so the key has no budget at all.
remoteRateLimit.descriptors[].typeWhat the descriptor counts. Use tokens to count LLM tokens rather than requests.
remoteRateLimit.descriptors[].costOptional CEL expression that returns the amount to charge each request against the limit. Here, llm.outputTokens charges only the tokens that the model generated. If the expression fails, or does not return a non-negative integer, agentgateway skips the descriptor.

Set a gateway-wide token budget

For setups that do not need shared state across replicas, use localRateLimit instead of a remote server. A local limit keeps its buckets in the memory of one agentgateway instance. Each instance enforces the limit separately. A local limit supports only Seconds, Minutes, and Hours intervals and cannot express a daily budget. Without a key, a local limit is gateway-wide. Every request draws from the same bucket.

llm:
  policies:
    localRateLimit:
    - maxTokens: 5000
      tokensPerFill: 5000
      fillInterval: 1h
      type: tokens

For the full local rate limit walkthrough, see Virtual key management.

Set a per-key token budget without a server

Add key to a local rate limit rule to give each caller a separate bucket. The key field takes a CEL expression. Each distinct value that the expression returns gets a bucket with the limits of the rule. The apiKey.user expression reads the user metadata of the API key that authenticated the request. Requests whose key expression returns no value or fails to evaluate share one bucket. For more information, see Per-key limits. For a walkthrough, see Give each key its own budget.

# yaml-language-server: $schema=https://agentgateway.dev/schema/config
llm:
  policies:
    apiKey:
      mode: strict
      keys:
      - key: sk-alice-abc123def456
        metadata:
          user: alice
      - key: sk-bob-xyz789uvw012
        metadata:
          user: bob
    localRateLimit:
    - maxTokens: 5000
      tokensPerFill: 5000
      fillInterval: 1h
      type: tokens
      key: apiKey.user
  models:
  - name: "*"
    provider: openAI
    params:
      apiKey: "$OPENAI_API_KEY"

Convert a token budget to cost

To estimate the dollar value of a token budget, multiply the budget by your provider’s prices. For example, take a model that charges $30 per 1M input tokens and $60 per 1M output tokens. A 100,000-token budget with an even split between input and output costs about $4.50 per day.

cost = (50,000 / 1,000,000 x $30) + (50,000 / 1,000,000 x $60)
     = $1.50 + $3.00
     = $4.50 per day

A token budget approximates spend, but it drifts as prices or the model mix change. To cap spend in dollars directly, use a per-key dollar budget instead.

Monitor token usage

To track how much of each budget a user has consumed, query the Prometheus metrics that agentgateway exposes.

curl http://localhost:15020/metrics

Query token usage by user with the agentgateway_gen_ai_client_token_usage_sum metric, or realized cost with agw.ai.usage.cost.total. For per-key spending queries and cost tracking, see Virtual key management and Model costs. The agctl standalone budgets command reports per-key budgets, not the token buckets on this page.

Warning

When you sum token usage, do not add the input_cache_read or input_cache_write token types to the input type. The input series already includes the cached tokens, so adding them double counts.

What’s next

Was this page helpful?
Agentgateway assistant

Ask me anything about agentgateway configuration, features, or usage.

Note: AI-generated content might contain errors; please verify and test all returned information.

Tip: one topic per conversation gives the best results. Use the + button in the chat header to start a new conversation.

Switching topics? Starting a new conversation improves accuracy.
↑↓ navigate ↵ select esc dismiss

What could be improved?

Your feedback helps us improve assistant answers and identify docs gaps we should fix.

Need more help? Join us on Discord: https://discord.gg/y9efgEmppm

Want to use your own agent? Add the Solo MCP server to query our docs directly. Get started here: https://search.solo.io/.