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

Rate limiting

Verified : Automated tests passed for: Configuration files: The configuration files on this page were checked against their schema. End-to-end run: Every step ran in a fresh test environment and the results were checked.
Page as Markdown

Enforce budget and spend limits per key by controlling request and token usage.

Attaches to:

Note

Agentgateway supports more than one configuration style. Where a feature can also be configured in the simplified llm or mcp modes, the examples on this page show each option in tabs. For more information, see Routing-based configuration.

Use rate limiting to enforce budget and spend limits per key: control the rate of requests and token usage on a route. Token-based limits let you cap usage per user, per API key, or per time window. Combined with API key authentication and observability, this gives you virtual key management.

Rate limits count requests or tokens over a period of time. To cap how many requests and connections are in flight at the same time instead, see Connection limits.

Rate limit types

Agentgateway exposes two types of rate limits:

Local rate limits apply in memory, and counters are not shared between replicas of agentgateway, nor across restarts. These are very low overhead, but not appropriate for usage where exact global counts are required, or for limits with long time windows (like monthly limits).

Remote rate limits store counters in an pluggable external data store, which enables shared state across replicas of agentgateway. This is controlled via the Envoy Rate Limit gRPC service to enable re-use with existing rate limiting services built for Envoy; the Envoy project has an example rate limiter service that can be used.

Rate limit modes

In additional to simple request-based rate limits, agentgateway can limit requests based on tokens for LLM consumption.

Request-based rate limits

By default, agentgateway applies rate limits to requests. Therefore, each request consumes 1 unit of capacity.

To explicitly set request-based rate limits, set the rate limiting type to requests as shown in the following example.

The following steps add the same localRateLimit policy as the Simplified (LLM) example in the Config file tab.

  1. Create a configuration with an LLM model, but no rate limit policy. You add the policy in the UI.

    # yaml-language-server: $schema=https://agentgateway.dev/schema/config
    llm:
      models:
      - name: "*"
        provider: openAI
        params:
          apiKey: "$OPENAI_API_KEY"
  2. Start agentgateway with this configuration.

  3. Open http://localhost:15000/ui/llm/policies (LLM > Policies), and click the Local rate limit tile.

  4. Fill out the form.

    1. Limit type: Keep Requests.
    2. Fill interval: 60s
    3. Max tokens: 10
    4. Tokens per fill: 1
    Local rate limit drawer with the Requests type, a 60s fill interval, 10 maximum tokens, and 1 token per fill
    Local rate limit drawer with the Requests type, a 60s fill interval, 10 maximum tokens, and 1 token per fill
  5. Click Save policy.

The UI omits type: requests, because requests is the default type. The form edits a single rate limit rule without a key. To add more rules or a per-key limit, use the Raw icon (<>) in the drawer header or the Config file tab.

You can also add a local rate limit policy in MCP > Policies, or in the Route policies section of a named route in Traffic > Routes.

Whether the UI can save depends on your storage mode. For more information, see Save changes from the UI.

Token-based rate limits

For tokens, each token (prompt or completion) consumes 1 unit of capacity. Because the number of tokens that are used for the completion is not known at the time the request is sent, calculating the number of tokens can become tricky. To work around this issue, agentgateway checks token-based rate limits in two phases, at request time and at response time.

To enable token-based rate limiting, set the rate limiting type to tokens. This example shows only the localRateLimit policy; attach it to a route as shown in the complete examples in the Configuration section.

  1. Open the Local rate limit policy drawer, such as in LLM > Policies.
  2. Select Tokens for the Limit type.
  3. Fill out the other fields.
    1. Fill interval: 60s
    2. Max tokens: 10
    3. Tokens per fill: 1
  4. Click Save policy.

At request time

  • When tokenize: true is not set or is set to false on the AI backend, the number of tokens that are used for the request cannot be calculated before the request is sent. Because of this, the request is allowed as long as the budget is not used up, even if the request then uses more tokens than are left. After earlier responses use up the budget, the next request is rejected with a 429 before the request reaches the LLM. The LLM typically returns the number of tokens that were used for the request when sending the response. Agentgateway verifies the number of tokens that were used in the request and the response to determine whether the rate limit was reached. By default, tokenize is set to false.
  • When tokenize: true is set, agentgateway estimates the number of tokens at request time. Because of that, the request is only allowed if the estimated number of tokens does not exceed the set rate limit.

At response time

When the LLM returns a response, it typically provides the number of tokens that were used during the request and response. Agentgateway uses these numbers to determine if the rate limit was reached.

Note that this determination happens after the response is returned. Even, if the number of tokens that are used in the response exceeds the number of allowed tokens, the response is still returned to the user. Only subsequent requests are rate limited. If tokenize: true is set on the AI backend and tokens were estimated during the request, agentgateway verifies the actual number of tokens that were used for the request when the LLM returns its response. In the case the initial estimation was off, agentgateway adjusts the number of used tokens to count these against the set rate limit.

The input count that agentgateway charges against the limit includes the tokens that the provider read from or wrote to its prompt cache. Providers disagree about whether their own input count includes cached tokens, so agentgateway normalizes the number first. For providers that exclude cached tokens, such as Anthropic and Amazon Bedrock, a cache-heavy request therefore consumes more capacity than the provider’s reported input count. For more information, see Token usage fields.

Configuration

Local

Local rate limiting uses a Token bucket algorithm.

FieldMeaning
maxTokensMaximum, and initial, size of the bucket
fillIntervalHow often to refill the bucket
tokensPerFillHow many tokens to replenish per fill
typeThe type of rate limiting. Choose between requests for request-based rate limits, and tokens for token-based rate limits.
keyOptional CEL expression that selects the bucket a request counts against, such as the jwt.sub claim for a limit per user. Each distinct value gets its own bucket with the limits above. When unset, all requests that the rule matches share one bucket. For more information, see Per-key limits.

The following example rate limit configuration allows 5,000 LLM tokens per hour, and 60 requests per second. A tokens limit counts and rejects only requests on a route whose backend is an LLM provider, so the MCP and routing-based examples have only the requests limit. For more information, see Multiple limits.

# yaml-language-server: $schema=https://agentgateway.dev/schema/config
llm:
  policies:
    localRateLimit:
    - maxTokens: 5000
      # Every hour, refill 5000 tokens
      tokensPerFill: 5000
      fillInterval: 1h
      type: tokens
    - maxTokens: 60
      # Every second, refill 1 token
      tokensPerFill: 1
      fillInterval: 1s
      type: requests
  models:
  - name: "*"
    provider: openAI
    params:
      apiKey: "$OPENAI_API_KEY"

Note

The term “tokens” is used for two distinct meanings. In maxTokens and tokensPerFill, it indicates the “token” in the token bucket counter. Each token can allow either 1 LLM token, or 1 HTTP request, based on the type.

Multiple limits

The localRateLimit field takes a list, so you can set more than one limit on the same route, such as a requests limit and a tokens limit. Each limit has its own bucket. Agentgateway allows a request only when every limit that applies to the request has room in its bucket. If any limit has no room, agentgateway rejects the request with a 429 response.

The limits that apply depend on the backend of the route.

  • requests limits apply to every request.
  • tokens limits apply only to requests on a route whose backend is an LLM provider, because only those requests have an LLM token count. On a route to an HTTP or MCP backend, agentgateway skips tokens limits, so these limits never count or reject requests on that route. Use type: requests for those routes.

Agentgateway checks the limits in the following order.

  1. When the request arrives, agentgateway takes one token from the bucket of each requests limit. If a bucket is empty, agentgateway rejects the request. Agentgateway then puts the token back in each bucket that it already took a token from, so the rejected request does not count against any requests limit.

  2. On an LLM route, agentgateway then checks each tokens limit.

    • Without tokenize, a tokens limit rejects the request only when its bucket is empty. After the response completes, agentgateway takes the number of tokens that the model reports from the bucket.
    • With tokenize, agentgateway takes the estimated number of input tokens from the bucket. If the bucket has fewer tokens left than the estimate, the limit rejects the request.

    If a tokens limit rejects the request, agentgateway puts back the tokens that it already took from the buckets of the other tokens limits. Agentgateway does not put back the tokens from step 1. The rejected request still counts against every requests limit.

For example, the Simplified (LLM) configuration in Local has a tokens limit of 5,000 LLM tokens per hour and a requests limit of 60 requests. When the 5,000 LLM tokens run out, agentgateway rejects each later request until the next hourly refill. Each rejected request still takes a token from the bucket of the requests limit.

Per-key limits

By default, every request that a rule matches counts against the same bucket, so the busiest caller can exhaust the limit for everyone else. To limit each caller separately, set key to a CEL expression. Each distinct value that the expression returns gets its own bucket with the limits of that rule. This way, you can enforce per-user, per-team, or per-model quotas without running an external rate limit server.

The following example builds on API key authentication and gives each virtual key its own budget of 1,000 LLM tokens per hour and its own limit of 60 requests per minute.

# 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:
    # Each API key gets its own budget of 1000 tokens per hour.
    - maxTokens: 1000
      tokensPerFill: 1000
      fillInterval: 1h
      type: tokens
      key: apiKey.user
    # Each API key also gets its own limit of 60 requests per minute.
    - maxTokens: 60
      tokensPerFill: 60
      fillInterval: 60s
      type: requests
      key: apiKey.user
  models:
  - name: "*"
    provider: openAI
    params:
      apiKey: "$OPENAI_API_KEY"

The expression can read anything in the request context. Common keys are the jwt.sub claim for a limit per user, jwt.team for a limit per team, and jwt.sub + "/" + llm.requestModel to give each user a separate allowance per model.

Review the following behavior before you set a key.

  • What the key can read: For LLM requests, both requests and tokens keys can read llm.requestModel and llmRequest (the parsed request body). To count requests per model, use llm.requestModel as the key. See Variables and functions.
  • Requests without a value: Requests whose key is empty, or whose expression cannot be evaluated, share a single bucket. An empty key does not exempt a request from the limit. To apply a limit to only some requests, use conditional policies instead.
  • How many buckets are kept, and where they live: Each rule keeps up to 65,536 buckets and drops the least used ones, which for that key is the same as never having been seen. Buckets are held in memory by a single agentgateway instance, so each instance enforces the limit separately. For a quota that is shared across instances, use remote rate limits.

Per-client, per-tool limits for MCP

To give each client its own allowance for each MCP tool, combine a conditional rule with a key. The following example counts only tools/call requests, so clients can still initialize and list tools after they reach a limit. The key combines the client from the API key metadata with the tool’s target and name. Each distinct value gets its own bucket of 2 calls per minute.

# yaml-language-server: $schema=https://agentgateway.dev/schema/config
mcp:
  port: 3000
  prefixMode: always
  policies:
    apiKey:
      mode: strict
      keys:
      - key: alice-key
        metadata:
          client: alice
      - key: bob-key
        metadata:
          client: bob
    localRateLimit:
      conditional:
      - condition: 'mcp.methodName == "tools/call"'
        type: requests
        maxTokens: 2
        tokensPerFill: 2
        fillInterval: 60s
        key: 'apiKey.client + "/" + mcp.tool.target + "/" + mcp.tool.name'
  targets:
  - name: everything
    stdio:
      cmd: npx
      args: ["-y", "@modelcontextprotocol/server-everything"]

When Alice calls everything_echo a third time within a minute, the gateway returns a tool result with isError: true. Bob’s calls and Alice’s calls to other tools still work. Two API keys with the same client metadata share one allowance.

{"jsonrpc":"2.0","id":3,"result":{"content":[{"type":"text","text":"rate limit exceeded (retry after 59s; limit 2, remaining 0)"}],"isError":true}}

A call whose key cannot be evaluated, such as a call to an unknown tool, uses a single bucket that all clients share.

FieldDescription
prefixModeHow to namespace tool names when you federate targets. With always, agentgateway adds the target name to every tool name, such as everything_echo, even with a single target.
apiKey.modeHow agentgateway handles requests without a valid API key. With strict, it rejects them.
apiKey.keys[].keyThe API key that the client sends as a bearer token.
apiKey.keys[].metadataValues that agentgateway attaches to requests that use the key. CEL expressions read each value as apiKey.<name>, such as apiKey.client.
localRateLimit.conditional[].conditionA CEL expression that selects the requests that the rule counts. Here, only tools/call requests count.
localRateLimit.conditional[].typeWhat the bucket counts. Use requests for MCP calls.
localRateLimit.conditional[].maxTokensThe size of the bucket, which is the number of calls that a client can make in a burst.
localRateLimit.conditional[].tokensPerFillThe number of calls that the bucket gains each fillInterval.
localRateLimit.conditional[].fillIntervalHow often the bucket refills.
localRateLimit.conditional[].keyA CEL expression. Each distinct value gets its own bucket. Here, the key is the client, the tool’s target, and the tool name.

Remote

Remote rate limits are not defined directly in agentgateway. Instead, agentgateway is configured to connect to an external rate limit server, and which “descriptors” to send to the server. The rate limit server is responsible for defining, and enforcing, the appropriate limits matching the descriptors.

Deploy a rate limit server

Agentgateway connects to any server that implements the Envoy Rate Limit gRPC service. The Envoy project provides a reference ratelimit server that stores counters in Redis. If you already run a compatible service, skip to Connect agentgateway to the rate limit server and point host at it instead.

The following example runs the ratelimit server and its Redis backing store locally with Docker Compose.

  1. Create a rate limit configuration for the server. The domain and each descriptor key must match the domain and descriptor entries that agentgateway sends (configured in the next section). This example limits each distinct organization value to 5,000 requests per hour.

    # ratelimit-config/config.yaml
    domain: example.com
    descriptors:
      - key: organization
        rate_limit:
          unit: hour
          requests_per_unit: 5000
  2. Create a Docker Compose file to run the rate limit server and Redis. The server loads every *.yaml file under the mounted config directory, and serves the gRPC API on port 8081.

    # docker-compose.yaml
    services:
      redis:
        image: redis:8-alpine
        ports: ["6379:6379"]
    
      ratelimit:
        image: envoyproxy/ratelimit:master
        depends_on: [redis]
        ports:
          - "8081:8081"   # gRPC port that agentgateway connects to
        environment:
          USE_STATSD: "false"
          LOG_LEVEL: debug
          REDIS_SOCKET_TYPE: tcp
          REDIS_URL: redis:6379
          RUNTIME_ROOT: /data
          RUNTIME_SUBDIRECTORY: ratelimit
          RUNTIME_WATCH_ROOT: "false"
        volumes:
          - ./ratelimit-config:/data/ratelimit/config
  3. Start the server.

    docker compose up -d
  4. Verify that the server is running. The ratelimit container logs the descriptors it loaded from your config.

    docker compose logs ratelimit

Note

Setting LOG_LEVEL: debug makes the server log every descriptor it receives from agentgateway at request time, which is the fastest way to confirm that your domain and descriptor keys line up on both sides.

Connect agentgateway to the rate limit server

With the server running, configure agentgateway to connect to it and specify which descriptors to send. Each descriptor value is a CEL expression. You can configure the connection in the UI or in your configuration file.

The following steps add the same remoteRateLimit policy as the Simplified (LLM) example in the Config file tab.

  1. Create a configuration with an LLM model, but no rate limit policy, and start agentgateway with it.

    # yaml-language-server: $schema=https://agentgateway.dev/schema/config
    llm:
      models:
      - name: "*"
        provider: openAI
        params:
          apiKey: "$OPENAI_API_KEY"
  2. Open http://localhost:15000/ui/llm/policies (LLM > Policies), and click the Remote rate limit tile.

  3. In the Service section, fill out the following fields.

    1. Domain: example.com. The domain must match the domain on the rate limit server.
    2. Failure mode: Keep Fail closed.
    3. Host: Replace the default host with localhost:8081, the address of the rate limit server.
  4. In the Descriptors section, configure Descriptor 1.

    1. Select Tokens for the Type.
    2. Click Add entry twice, so that the descriptor has three entries.
    3. Enter the following keys and CEL expressions in the Entries. Replace the example entry in the first row.
      KeyExpression
      some-static-value"something"
      organizationrequest.headers["x-organization"]
      authenticatedhas(jwt.sub)
  5. Click Save policy.

You can also add a remote rate limit policy in MCP > Policies, or in the Route policies section of a named route in Traffic > Routes.

Each descriptor value is a CEL expression.

Agentgateway sends a tokens descriptor to the rate limit server only for requests on a route whose backend is an LLM provider, because only those requests have an LLM token count. On a route to an HTTP or MCP backend, agentgateway never sends a tokens descriptor, so the rate limit server never counts or rejects requests on that route. Use type: requests for those routes.

For a complete runnable setup, including the Envoy rate limit service configuration and the Docker commands to run it with Redis, see the traffic-ratelimiting-global example in the agentgateway repository.

Configuration from the traffic-ratelimiting-global example
config:
  tracing:
    otlpEndpoint: http://localhost:4317
    randomSampling: true
binds:
- port: 3000
  listeners:
  - protocol: HTTP
    routes:
    - policies:
        remoteRateLimit:
          domain: "agentgateway"
          host: "127.0.0.1:8081"
          # failureMode controls behavior when the rate limit service is unavailable.
          # "failOpen" (default): allow requests through on service failure.
          # "failClosed": deny requests with 500 on service failure.
          failureMode: failOpen
          descriptors:
          - entries:
            - key: "method"
              value: request.method
            - key: "path"
              value: request.path
            type: "requests"
      backends:
      - host: localhost:8080

The example also defines the limits on the rate limit server side:

domain: agentgateway
descriptors:
  - key: method
    value: "GET"
    descriptors:
      - key: path
        value: "/"
        rate_limit:
          unit: minute
          requests_per_unit: 5
  - key: method
    value: "POST"
    rate_limit:
      unit: minute
      requests_per_unit: 10

Count requests that are missing a field

Agentgateway sends a descriptor only when every one of its entries can be evaluated. If an entry reads a header, claim, or metadata field that the request does not have, agentgateway skips the whole descriptor. When no descriptor is left, agentgateway does not call the rate limit server at all, so no limit applies to that request. A local rate limit key works differently. A local rate limit counts such requests against one shared bucket.

To count every request, give each entry a fallback value for requests that do not have the field. In the following example, requests without an x-organization header count against one shared unknown organization.

# yaml-language-server: $schema=https://agentgateway.dev/schema/config
gateways:
  default:
    port: 3000
routes:
- policies:
    remoteRateLimit:
      host: localhost:8081
      domain: example.com
      descriptors:
      - entries:
        - key: organization
          # Requests without the header count against one shared "unknown" organization.
          value: '"x-organization" in request.headers ? request.headers["x-organization"] : "unknown"'
        type: requests
  backends:
  - host: localhost:8080
FieldDescription
remoteRateLimit.hostThe address of the rate limit server.
remoteRateLimit.domainThe domain of the limits on the rate limit server. The value must match a domain in the rate limit server configuration.
remoteRateLimit.descriptors[].entries[].keyThe descriptor key that the rate limit server matches, here organization.
remoteRateLimit.descriptors[].entries[].valueA CEL expression for the descriptor value. The in check returns the x-organization header when the request has it, and the fallback value unknown when it does not.
remoteRateLimit.descriptors[].typeWhat the descriptor counts. Use requests to count HTTP requests.

Compute a limit per request

By default, the rate limit server holds the limit for each descriptor in the rate_limit block of its own configuration. To let the request carry its own limit instead, set limitOverride on the descriptor. Agentgateway evaluates the CEL expression for each request and sends the result with the descriptor. The rate limit server then applies that limit in place of its own rate_limit value for the descriptor. Use this field when the limit belongs to the caller rather than to the route, such as a plan that arrives in a header or a JWT claim.

The expression must return an object with a unit and a requestsPerUnit field. In the following example, organizations on the gold plan get 3 requests per minute, and every other organization gets 1. The rate limit server’s own limit for organization does not apply.

# yaml-language-server: $schema=https://agentgateway.dev/schema/config
gateways:
  default:
    port: 3000
routes:
- policies:
    remoteRateLimit:
      host: localhost:8081
      domain: example.com
      descriptors:
      - entries:
        - key: organization
          value: '"x-organization" in request.headers ? request.headers["x-organization"] : "unknown"'
        # Organizations on the gold plan get 3 requests per minute, every other organization 1.
        limitOverride: '"x-plan" in request.headers && request.headers["x-plan"] == "gold" ? {"unit": "minute", "requestsPerUnit": 3} : {"unit": "minute", "requestsPerUnit": 1}'
        type: requests
  backends:
  - host: localhost:8080
FieldDescription
remoteRateLimit.descriptors[].limitOverrideOptional CEL expression that returns the limit for this descriptor, as an object with unit and requestsPerUnit, such as {"unit": "minute", "requestsPerUnit": 5}. Valid unit values are second, minute, hour, day, month, and year. The rate limit server applies this limit in place of its own limit for the descriptor. The field sets the limit, not the cost of a request. To set the cost, use cost.

The rate limit server applies an override even when none of its own rules match the descriptor. However, the domain must still exist in the rate limit server configuration. The Envoy reference ratelimit server ignores every descriptor for a domain that it does not know, so the override has no effect. For a server configuration with the example.com domain, see Deploy a rate limit server.

When the limitOverride expression cannot return a usable limit, agentgateway skips the whole descriptor. No limit applies to the request for this descriptor, not even the rate limit server’s own rule. The time when you find the problem depends on the type of error.

  • Invalid CEL: Agentgateway rejects the configuration when the configuration loads.
  • A field that the request does not have, such as a missing header: Agentgateway skips the descriptor for that request only. To prevent this, guard any value that might be absent, as the example does with in.
  • A valid expression that returns an unusable limit, such as a misspelled unit: Agentgateway does not catch the error when the configuration loads. Instead, agentgateway skips the descriptor for every request.

Limit MCP tool calls

Every MCP message, such as initialize, tools/list, or tools/call, is a separate HTTP request, so a rate limit on an MCP route counts each of these messages. To limit only tool calls, and each tool separately, send the tool’s target and name as a descriptor entry. Include the target so that tools with the same name on different targets get separate limits. On an MCP route, a descriptor can read the parsed MCP request through the mcp variable.

# yaml-language-server: $schema=https://agentgateway.dev/schema/config
gateways:
  default:
    port: 3000
routes:
- policies:
    remoteRateLimit:
      host: localhost:8081
      domain: mcp-tools
      descriptors:
      - entries:
        # "<target>/<tool>" for a tools/call request, and "none" for other MCP methods.
        - key: tool
          value: 'mcp.methodName == "tools/call" ? mcp.tool.target + "/" + mcp.tool.name : "none"'
        type: requests
  backends:
  - mcp:
      targets:
      - name: everything
        stdio:
          cmd: npx
          args: ["@modelcontextprotocol/server-everything"]
FieldDescription
remoteRateLimit.hostThe address of the rate limit server.
remoteRateLimit.domainThe domain of the limits on the rate limit server, here mcp-tools.
remoteRateLimit.descriptors[].entries[].keyThe descriptor key that the rate limit server matches, here tool.
remoteRateLimit.descriptors[].entries[].valueA CEL expression for the descriptor value. For a tools/call request, the value is the tool’s target and name, such as everything/echo. For every other MCP method, the value is none.
remoteRateLimit.descriptors[].typeWhat the descriptor counts. Use requests for MCP calls.
backends[].mcp.targetsThe MCP servers behind the route. Here, one stdio target that is named everything.

On the rate limit server, define a limit for each tool that you want to limit. The following configuration allows one call per minute to the echo tool on the everything target. Other tools, and every request that is sent with the none value, match no rule and are not limited. A request that agentgateway cannot read as an MCP message, or a call to a tool that does not exist, sends no descriptor and is not limited either.

# ratelimit-config/mcp-tools.yaml
domain: mcp-tools
descriptors:
  - key: tool
    value: everything/echo
    rate_limit:
      unit: minute
      requests_per_unit: 1

When a client calls the echo tool a second time within the minute, the call returns a tool result with isError: true, as described in Responses when a request is limited.

For a local alternative that gives each client its own allowance per tool, see Per-client, per-tool limits for MCP.

Failure behavior

By default, if the remote rate limit service is unavailable or returns an error, agentgateway fails closed: the request is denied with a 500 Internal Server Error. This prevents unmetered traffic in the event of a service outage.

To allow requests through when the rate limit service is unavailable, set failureMode to failOpen:

remoteRateLimit:
  host: localhost:8081
  domain: example.com
  failureMode: failOpen
  descriptors:
  - entries:
    - key: organization
      value: 'request.headers["x-organization"]'
    type: requests
ValueBehavior
failClosed (default)Deny requests with 500 when the rate limit service is unavailable
failOpenAllow requests through when the rate limit service is unavailable

Warning

Be cautious when setting the failure mode to failOpen. While this setting prevents service disruptions if the rate limiting server is unavailable, rate limits are not enforced for your routes until the rate limiting server is available again.

Backend connection policies

You can configure connection policies on the remoteRateLimit field to secure or tune how agentgateway connects to the rate limit service. This includes TLS, authentication, and connection timeouts.

By default, agentgateway waits 10 seconds for the rate limit service to respond. When the wait runs out, the call fails and the failureMode setting decides what happens to the request. To use a different timeout, set policies.http.requestTimeout.

The route’s own timeout.requestTimeout does not limit how long agentgateway waits for the rate limit service. A rate limit service that accepts the connection but does not answer therefore delays each request for the full wait before failureMode applies. To bound that delay, set policies.http.requestTimeout to a value that is lower than the route’s request timeout.

remoteRateLimit:
  host: ratelimit-service:8081
  domain: my-api
  policies:
    backendAuth:
      key:
        file: /secrets/api-key
    backendTLS:
      root: /certs/ca.pem
      insecure: false
    tcp:
      connectTimeout: 3s
  descriptors:
    - entries:
        - key: service
          value: '"my-service"'
  failureMode: failOpen
FieldDescription
policies.backendAuthCredentials to authenticate to the rate limit service. Supports key (API key from file or inline), gcp, aws, and azure auth.
policies.backendTLSTLS settings for the connection to the rate limit service. Use root to specify a CA cert, insecure: true to skip certificate verification (not recommended for production).
policies.tcp.connectTimeoutConnection timeout as a duration string, such as 3s.
policies.http.requestTimeoutTimeout for each call to the rate limit service, as a duration string such as "1s". If unset, calls to the rate limit service time out after 10 seconds. The route’s own timeout.requestTimeout does not limit this wait.

Responses when a request is limited

When a rate limit rejects a request, agentgateway returns a 429 Too Many Requests response. Responses also carry headers that describe the limit that applied, so that clients can slow down before agentgateway rejects their requests. A local rate limit always adds these headers. A remote rate limit adds them only when the rate limit server returns the current limit for a descriptor, as the Envoy reference ratelimit server does.

HeaderDescription
x-ratelimit-limitThe limit of the bucket or descriptor that applied. When more than one limit applies, the headers describe the limit with the fewest requests remaining.
x-ratelimit-remainingHow much of that limit is left.
x-ratelimit-resetThe number of seconds until the limit resets.
retry-afterOn a 429 response only. The number of seconds until the client can retry.

For a remote rate limit, retry-after is the longest wait among all the descriptors that are over their limit. The x-ratelimit-* headers describe only the descriptor with the fewest requests remaining. When more than one descriptor is over its limit, retry-after can therefore be longer than x-ratelimit-reset.

A local rate limit returns the body rate limit exceeded. A remote rate limit returns the body that the rate limit server sends, which is empty for the Envoy reference ratelimit server.

For MCP requests, the rejection takes the form that MCP clients expect.

  • A rejected tools/call request gets a tool result with isError: true and a text such as rate limit exceeded (retry after 12s; limit 1, remaining 0).
  • Other requests that carry a JSON-RPC id, such as initialize, get an HTTP 200 response with a JSON-RPC error with code -32003.
  • A notification, which has no id, gets a plain 429 response.
  • A request over the legacy SSE transport (/sse) gets a plain 429 response.

For a remote rate limit, a non-empty body from the rate limit server replaces the rate limit exceeded text in the tool result and in the JSON-RPC error message. The Envoy reference ratelimit server sends an empty body, so the text stays rate limit exceeded. Other rate limit servers can send their own text.

For more information, see Tool-call error results.

Conditional execution

To apply different rate limits based on the request, use the conditional field. For example, you can apply stricter limits on writes than on reads. For details, see Conditional policies.

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/.