Rate Limiting Policy

Related Documentation
Made by
Kong Inc.
Incompatible with
on-prem
Minimum Version
AI Gateway - 2.0

Rate limit how many HTTP requests can be made in a given period of seconds, minutes, hours, days, months, or years. If the AI Model, AI Agent, or AI MCP Server handling the request has no authentication layer, the client IP address is used to identify clients. Otherwise, the AI Consumer is used once an AI Auth Strategy has authenticated the request.

This Policy counts requests. To rate limit on LLM token usage or cost instead, use the AI Rate Limiting Advanced Policy, which reads the token data returned by the AI Model Provider.

Example

The following example creates a global Rate Limiting Policy that allows 100 requests per minute per AI Consumer:

policy.yaml
ai_gateway_policies:
  - ref: rate-limiting-global
    ai_gateway: !lookup {id: !env AI_GATEWAY_ID}
    display_name: Rate Limiting - Global
    name: rate-limiting-global
    type: rate-limiting
    enabled: true
    global: true
    config:
      minute: 100
      limit_by: consumer
      policy: local

Make sure to replace the following placeholders with your own values:

  • AI_GATEWAY_ID: The id of your AI Gateway.

Strategies

The Rate Limiting Policy supports two rate limiting strategies: local and redis. This is controlled by the config.policy parameter.

Strategy

Description

Pros

Cons

local Counters are stored in-memory on the node. Minimal performance impact. Less accurate. Unless there’s a consistent-hashing load balancer in front of AI Gateway, it diverges when scaling the number of nodes.
redis Counters are stored on a Redis server and shared across nodes. Accurate1, shared across all nodes. Needs a Redis installation. Bigger performance impact than a local strategy.

[1]: Only when the config.sync_rate option is set to -1 (synchronous behavior).

Two common use cases for rate limiting are:

  1. Every transaction counts: The highest level of accuracy is needed. An example is a transaction with financial consequences.
  2. Backend protection: Accuracy is not as relevant. The requirement is only to protect backend services from overloading that’s caused either by specific users or by attacks.

Every transaction counts

In this scenario, because accuracy is important, the local strategy is not an option. Use redis.

If you use a very high sync frequency, redis is the only workable choice. The sync frequency becomes higher when the sync_rate setting is a lower number. For example, a sync_rate of 0.1 is a much higher sync frequency (10 counter syncs per second) than a sync_rate of 1 (1 counter sync per second).

You can calculate what is considered a very high sync rate in your environment based on your topology, number of AI Policies, their sync rates, and tolerance for loose rate limits.

Backend protection

If accuracy is less important, choose the local strategy. You might need to experiment a little before you get a setting that works for your scenario. As AI Gateway scales to more nodes, more user requests are handled. When the number of nodes scales down, the probability of false negatives increases. Make sure to adjust your rate limits when scaling.

For example, if a user can make 100 requests every second, and you have an equally balanced 5-node AI Gateway deployment, you can set the local limit to 30 requests every second. If you see too many false negatives, increase the limit.

To minimize inaccuracies, consider using a consistent-hashing load balancer in front of AI Gateway. The load balancer ensures that a user is always directed to the same AI Gateway node, which reduces inaccuracies and prevents scaling problems.

Using cloud authentication with Redis

If your AI Policy uses a Redis datastore, you can authenticate to it with a cloud Redis provider. This allows you to rotate credentials without relying on static passwords.

The following providers are supported:

  • AWS ElastiCache
  • Azure Managed Redis
  • Google Cloud Memorystore (with or without Valkey)

Each provider also supports an instance and cluster configuration.

Limit by

Use config.limit_by to choose what the Policy aggregates counters against:

Value

Description

consumer The authenticated AI Consumer. This is the default.
consumer-group The AI Consumer Group the AI Consumer belongs to.
credential The credential the AI Consumer authenticated with. Use this to limit each API key separately when one AI Consumer holds several.
ip The client IP address. See Limit by IP address.
header The value of the header named in config.header_name.
path The request path set in config.path.

Limit by IP address

If limiting by IP address, it’s important to understand how AI Gateway determines the IP address of an incoming request.

The IP address is extracted from the request headers sent to AI Gateway by downstream clients. Typically, these headers are named X-Real-IP or X-Forwarded-For.

By default, AI Gateway uses the header name X-Real-IP to identify the client’s IP address. If your environment requires a different header, you can specify this by setting the real_ip_header Nginx property. Depending on your network setup, you may also need to configure the trusted_ips Nginx property to include the load balancer IP address. This ensures that AI Gateway correctly interprets the client’s IP address, even when the request passes through multiple network layers.

Headers sent to the client

When this Policy is enabled, AI Gateway sends some additional headers back to the client, indicating the state of the rate limits in place:

Header

Description

RateLimit-Limit Allowed limit in the timeframe.
RateLimit-Remaining Number of available requests remaining.
RateLimit-Reset The time remaining, in seconds, until the rate limit quota is reset.
X-RateLimit-Limit-Second The time limit, in number of seconds.
X-RateLimit-Limit-Minute The time limit, in number of minutes.
X-RateLimit-Limit-Day The time limit, in number of days.
X-RateLimit-Limit-Month The time limit, in number of months.
X-RateLimit-Limit-Year The time limit, in number of years.
X-RateLimit-Remaining-Second The number of seconds still left in the time frame.
X-RateLimit-Remaining-Minute The number of minutes still left in the time frame.
X-RateLimit-Remaining-Day The number of days still left in the time frame.
X-RateLimit-Remaining-Month The number of months still left in the time frame.
X-RateLimit-Remaining-Year The number of years still left in the time frame.
Retry-After This header appears on 429 errors, indicating how long the upstream service is expected to be unavailable to the client.

You can optionally hide the limit and remaining headers with the config.hide_client_headers option.

If more than one limit is set, the Policy returns multiple time limit headers. For example:

X-RateLimit-Limit-Second: 5
X-RateLimit-Remaining-Second: 4
X-RateLimit-Limit-Minute: 10
X-RateLimit-Remaining-Minute: 9

If any of the limits are reached, the Policy returns an HTTP/1.1 429 status code to the client with the following JSON body:

{ "message": "API rate limit exceeded" }

Override the status code with config.error_code and the message with config.error_message.

The headers RateLimit-Limit, RateLimit-Remaining, and RateLimit-Reset are based on the Internet-Draft RateLimit Header Fields for HTTP and may change in the future to respect specification updates.

Help us make these docs great!

Kong Developer docs are open source. If you find these useful and want to make them better, contribute today!