The AI Rate Limiting Advanced Policy provides rate limiting for all AI Policies. The
AI Rate Limiting Advanced Policy extends the
Rate Limiting Advanced Policy.
This Policy uses the token data returned by the LLM provider to calculate the costs of queries.
The same HTTP request can vary greatly in cost depending on the calculation of the
LLM providers. See Model cost management for how AI Gateway prices a request.
A common pattern to protect your AI API is to analyze and assign costs to incoming queries, then rate limit the consumer’s
cost for a given time window and provider or policy.
You can also create a generic prompt rate limit using the request prompt provider.
The AI Rate Limiting Advanced Policy supports three rate limiting strategies: local, cluster, and redis.
This is controlled by the config.strategy 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.
cluster
Counters are stored in the Kong Gateway data store and shared across nodes.
Accurate1, no extra components to support.
Each request forces a read and a write on the data store. Therefore, relatively, the biggest performance impact. Not supported in DB-less mode, hybrid mode, or Konnect deployments.
redis
Counters are stored on a Redis server and shared across nodes.
Accurate1, less performance impact than a cluster strategy.
Needs a Redis installation. Bigger performance impact than a local strategy.
[1]: Only when config.sync_rate option is set to 0 (synchronous behavior).
Two common use cases for rate limiting are:
Every transaction counts: The highest level of accuracy is needed. An example is a transaction with financial consequences.
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.
In this scenario, because accuracy is important, the local strategy is not an option.
Consider the support effort you might need for Redis, and then choose either cluster or redis.
You could start with the cluster strategy, and move to redis if performance reduces drastically.
If using a very high sync frequency, use redis. Very high sync frequencies with cluster mode are not scalable and not recommended.
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.
Together, the interaction between sync rate and window size affects how accurately the AI Rate Limiting Advanced Policy can determine traffic across all nodes.
For example, the following table represents the worst-case scenario where a full sync interval’s worth of data hasn’t yet propagated across nodes:
Property
Formula or config location
Value
Window size in seconds
Value set in config.policies[].limits[].window_size
5
Limit (in window)
Value set in config.policies[].limits[].limit
1000
Sync rate (interval)
Value set in config.sync_rate
0.5
Number of nodes (>1)
–
10
Estimated load balanced requests-per-second (RPS) to a node
Limit / Window size / Number of nodes
1000 / 5 / 10 = 20
Max potential lag in count for a given node/s
Estimated load balanced RPS * Sync rate
20 * 0.5 = 10
Max potential overage/s across all nodes
Max potential lag * Number of nodes
10 * 10 = 100
Max potential overage/s across all nodes as a percentage
Max potential overage / Limit
100 / 1000 = 10%
Effective worst case number of requests allowed at window size
Limit * Max potential overage
1000 + 100 = 1100
If you choose to switch strategies, note that you can’t port the existing usage metrics from the Kong Gateway data store to Redis.
This might not be a problem with short-lived metrics (for example, seconds or minutes)
but if you use metrics with a longer time frame (for example, months), plan your switch carefully.
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.
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.
You need:
A running Redis instance on an AWS ElastiCache instance for Valkey 7.2 or later or ElastiCache for Redis OSS version 7.0 or later
When the redis strategy is used and an AI Gateway node is disconnected from Redis, the plugin will fall back to local rate limiting.
This can happen when the Redis server is down or the connection to Redis is broken.
AI Gateway keeps the local counters for rate limiting and syncs with Redis once the connection is re-established.
AI Gateway will still rate limit, but the AI Gateway nodes can’t sync the counters. As a result, users will be able
to perform more requests than the limit, but there will still be a limit per node.
The config.policies field allows you to define rate limiting at the AI Consumer, AI Consumer Group, IP address, header, path, model, and provider level. The match conditions under config.policies.match use an AND logic, so you can combine these to set up multi-dimensional rate limiting. For example, you can set different rate limiting policies for a specific AI Consumer and model:
Make sure to replace the following placeholders with your own values:
AI_GATEWAY_ID: The id of your AI Gateway.
In this example, the limits will apply only to requests made by the specified AI Consumer to the gpt-4o model.
Policies without match conditions act as fallback and match all requests.
When defining rate limits for a specific model, these limits apply to the requested model. If a request is redirected to a different model after a failover, the request may succeed even if the final model has reached its limit.
Calendar windows budget tokens against the same period your billing already uses, such as a monthly allowance that resets on the 1st, instead of a rolling window that drifts from the billing cycle.
Set window_type: calendar on the policy and timezone to an IANA time zone, such as America/New_York. Each limit then sets a period instead of window_size:
Field
Description
period
month or week.
month_day
Required when period is month. This is the day of the month (1-31) that a monthly window starts.
week_start_day
Day of the week a weekly window starts, such as monday. Only applies when period is week.
Make sure to replace the following placeholders with your own values:
AI_GATEWAY_ID: The id of your AI Gateway.
This policy grants the premium AI Consumer Group 2,000,000 tokens per calendar month, resetting at local midnight on the 1st in America/New_York.
For calendar windows, X-AI-RateLimit-Reset and X-AI-RateLimit-Retry-After point to the next calendar boundary (the start of the next week or month in the configured time zone), not now + window_size.
When defining a policy matching a model and/or a provider, you must set the config.policies.match.partition_by field to true, otherwise the policy is not enforced.
When the AI Rate Limiting Advanced Policy is enabled, AI Gateway sends some additional headers back to the client,
indicating the allowed limits, how many requests are available, and how long it will take
until the quota is restored. It also sends the limits in the time frame and the number
of remaining minutes for each provider or policy.
If using the request prompt provider, the AI Rate Limiting Advanced Policy will send the query cost:
X-AI-RateLimit-Query-Cost: 100
Copied!
The Retry-After headers will be present on 429 errors to indicate how long the service is
expected to be unavailable to the client. When using window_type=sliding and RateLimit-Reset, Retry-After
may increase due to the rate calculation for the sliding window.
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.
The AI Rate Limiting Advanced Policy supports three strategies to calculate the number of tokens. Configure the strategy with tokens_count_strategy.
Strategy
Description
total_tokens
The total number of tokens in the request, including both prompt and completion tokens.
prompt_tokens
The tokens provided as input to the LLM.
completion_tokens
The tokens generated by the LLM in response to the prompt.
cost
The financial or computational cost incurred based on token usage. This strategy lets you limit API usage based on actual processing costs rather than raw token counts.
The AI Rate Limiting Advanced Policy limits against the same cost figure AI Gateway calculates for reporting. See Model cost calculation for the full formula, including how cache pricing, context-window thresholds, and service tiers factor in.
You define pricing per 1 million tokens in whatever unit suits your use case, whether US dollars, cents, or internal billing credits. The rate limit threshold must use the same unit.
This strategy requires input_cost and output_cost configured on the AI Model target’s config. See Model cost configuration for these and the optional cache, context-window, and service-tier fields.
You can decide to use a custom function to count the tokens for a requests.
To configure it, specify the function in config.request_prompt_count_function.
When using the request prompt provider, it will call the function to get the token count at the request level and implement a limit.