API Key and Model Rate Limits
Rate limits protect provider capacity and prevent one caller or model from consuming a shared quota. Configure a limit on a caller API key when the quota belongs to that caller, or on a model when every caller of that model should share the quota.
These limits belong to the API key or model on which they are configured. Rate limit policies are separate rules that can match teams, members, API keys, models, model names, or providers and divide matching traffic into independent quota buckets. A request can match API key limits, model limits, and policies at the same time. Every matching limit applies, and the gateway returns 429 before calling the provider if any bucket is exhausted.
This guide shows how to configure limits on API keys and models, verify enforcement, and choose shared counter storage. Use the control-plane path for AISIX Enterprise or AISIX Cloud, or the resources-file path for AISIX OSS. Both paths configure the same gateway capabilities.
Prerequisites
Before starting, prepare the following:
- A working model alias and caller API key that can send proxy requests. If you have not configured them yet, see Provider Keys, Model Aliases, and Caller API Keys.
- For AISIX Enterprise or AISIX Cloud, an environment with an attached gateway and a write-scoped admin token. Follow the AISIX Enterprise getting-started guide for a local evaluation, or contact API7 to request AISIX Cloud access.
- For the open-source AISIX gateway, a declarative resources file that you can validate and reload. See Reload a Resources File.
Export the gateway request values used to verify any example on this page:
# AISIX_PROXY has no trailing slash or endpoint path.
# The local quickstarts use http://127.0.0.1:3000.
export AISIX_PROXY="YOUR_AISIX_GATEWAY_URL"
export AISIX_MODEL="gpt-4o-prod"
export AISIX_API_KEY="YOUR_CALLER_API_KEY"
For the control-plane examples, also export the control-plane connection values and the resource IDs you want to limit:
# AISIX_CP includes /api and has no trailing slash.
# The local AISIX Enterprise quickstart uses http://localhost:8080/api.
export AISIX_CP="YOUR_AISIX_CONTROL_PLANE_API_URL"
export AISIX_TOKEN="YOUR_ADMIN_TOKEN"
export ENV_ID="YOUR_ENVIRONMENT_ID"
# API_KEY_ID identifies the caller key whose plaintext is AISIX_API_KEY.
export API_KEY_ID="YOUR_CALLER_API_KEY_ID"
# MODEL_ID identifies the model whose alias is AISIX_MODEL.
export MODEL_ID="YOUR_MODEL_ID"
Choose a Rate-Limit Configuration
You can configure a rate limit in two ways:
- Attach a
rate_limitblock directly to a caller API key or model. Use a caller limit when one application or tenant needs its own quota, or a model limit when every caller of an alias should share the quota. - Create a rate-limit policy when you need a separately managed quota, conditional matching, or independent buckets for teams, members, API keys, models, or providers.
A caller API key can also carry a separate request and concurrency limit for each MCP server it calls. See MCP Rate Limits and Budgets.
Every matching limit applies. For example, a request can consume capacity from its caller API key, resolved model, team, and member policies at the same time. The request continues only when every matching bucket has capacity.
Configure a Caller API Key Limit
The following examples limit one caller API key to one request per minute.
AISIX Enterprise or AISIX Cloud
In the dashboard, open API keys, expand the caller API key, and use its Rate limits controls. The Admin API provides the same configuration for automation.
Update the caller API key with a one-request-per-minute limit:
curl -sS -X PATCH "${AISIX_CP}/environments/${ENV_ID}/api_keys/${API_KEY_ID}" \
-H "Authorization: Bearer ${AISIX_TOKEN}" \
-H "Content-Type: application/json" \
-d '{
"rate_limit": {
"rpm": 1
}
}'
The change projects to attached gateways automatically.
AISIX OSS
Replace the existing caller API key entry to add the same limit. Keep its current id, display_name, key_hash, and allowed_models values:
api_keys:
- id: a31b8275-cc81-4cdc-a618-875fd28c7532
display_name: chat-app
key_hash: ${CALLER_API_KEY_SHA256}
allowed_models:
- gpt-4o-prod
rate_limit:
rpm: 1
Make the caller credential available to the validation command:
# Use the same plaintext value as the verification requests.
export CALLER_API_KEY="${AISIX_API_KEY}"
export CALLER_API_KEY_SHA256="$(printf '%s' "$CALLER_API_KEY" | sha256sum | cut -d ' ' -f 1)"
If AISIX is installed on the host, validate the complete resources file before reloading the gateway:
aisix validate --resources resources.yaml
For the Docker setup in the open-source quickstart, use the container-based validation and reload commands. The quickstart already makes CALLER_API_KEY_SHA256 available to the container.
Configure a Model Limit
Use a model limit when every caller of one alias should share the same quota. The following examples allow one request per minute across all caller API keys that use gpt-4o-prod.
AISIX Enterprise or AISIX Cloud
In the dashboard, open Models, edit the model, and use the Rate limits fields. The Admin API provides the same configuration for automation.
Update the model:
curl -sS -X PATCH "${AISIX_CP}/environments/${ENV_ID}/models/${MODEL_ID}" \
-H "Authorization: Bearer ${AISIX_TOKEN}" \
-H "Content-Type: application/json" \
-d '{
"rate_limit": {
"rpm": 1
}
}'
AISIX OSS
Add the limit to the direct model entry and retain its existing provider and provider-key settings:
models:
- id: b5d1e9b6-a895-4cc4-8812-95db86b857b0
display_name: gpt-4o-prod
provider: openai
model_name: gpt-4o
provider_key_id: 83eba07c-0ad3-4b81-b760-247f2d978e95
rate_limit:
rpm: 1
Validate the complete resources file and reload the gateway. Requests through different caller API keys now draw from the same model bucket.
Verify Rate Limiting
The preceding caller and model examples use the same one-request-per-minute limit. Configure and test one direct limit at a time so the 429 response identifies the limit under test. Use the same request sequence to verify a rate-limit policy.
After the control-plane change reaches the gateway, or after you reload the open-source resources file, send three requests:
for i in 1 2 3; do
printf "request %s: " "${i}"
curl -sS -o /dev/null -w "%{http_code}\n" -X POST "${AISIX_PROXY}/v1/chat/completions" \
-H "Authorization: Bearer ${AISIX_API_KEY}" \
-H "Content-Type: application/json" \
--data-binary @- <<EOF
{
"model": "${AISIX_MODEL}",
"messages": [
{
"role": "user",
"content": "Hello from AISIX."
}
]
}
EOF
done
The first request should reach the upstream model. The remaining requests should exceed the limit, provided all three fall within the same clock minute:
request 1: 200
request 2: 429
request 3: 429
A minute window resets at the top of each UTC minute, so a sequence that straddles that boundary can see a later request succeed.
An OpenAI-compatible rate-limit rejection returns 429 Too Many Requests with the proxy error format:
{
"error": {
"message": "request limit exceeded (requests)",
"type": "rate_limit_exceeded"
}
}
A rejection from a caller API key limit, a model limit, or a rate-limit policy carries Retry-After plus the X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset, and X-RateLimit-Scope headers. They describe the one limit that refused the request:
retry-after: 43
x-ratelimit-limit: 1
x-ratelimit-remaining: 0
x-ratelimit-reset: 43
x-ratelimit-scope: rpm
Request-count and token-limit rejections count down to the next window boundary, such as the top of the minute, or 00:00 UTC for a daily limit. With window_type: sliding, they count down to the moment enough usage leaves the rolling window instead. A concurrency rejection has no window — a slot frees when some in-flight request finishes — so it reports a fixed 60-second hint. Successful Chat Completions responses carry a different, per-dimension header family instead. See Rate-Limit Rejection Headers.
Rate Limit Fields and Counter Behavior
Caller API keys and model aliases use the same rate_limit fields. Each field is optional. When a field is omitted, AISIX does not enforce that dimension.
| Field | Limit | Window |
|---|---|---|
rps | Requests per second | 1 second |
rpm | Requests per minute | 60 seconds |
rph | Requests per hour | 3,600 seconds |
rpd | Requests per day | 86,400 seconds |
tpm | Tokens per minute | 60 seconds |
tpd | Tokens per day | 86,400 seconds |
concurrency | In-flight requests | Not windowed |
With the default window_type: fixed, each windowed field counts in a fixed window aligned to the UTC clock, not to a caller's first request. The count resets as a whole at each boundary: every second for rps, the top of every minute for rpm and tpm, the top of every hour for rph, and 00:00 UTC for rpd and tpd, which is 08:00 in UTC+8. Because the whole count resets at once, a burst at the end of one window and another at the start of the next can together admit up to twice the limit within one window's length. For example, with rpm: 100, 100 requests at 10:00:50 and another 100 at 10:01:05 are all admitted. To cap every interval of one window's length instead, use a sliding window.
AISIX checks and records the three limit dimensions at different points while processing a request:
| Dimension | When AISIX Checks It | When AISIX Records Usage |
|---|---|---|
| Request count | Before the provider call | During the pre-provider checks. When a later layer rejects the request, the counts the earlier layers took are returned; see How Requests Are Counted |
| Tokens | Before the provider call, using only tokens already recorded in the current window. Nothing is reserved for the request | After the response completes, using the usage the upstream reports |
| Concurrency | Before the provider call | Held until the response or stream completes, then released |
Token limits include prompt and completion tokens. For Anthropic traffic, they also include prompt cache creation and cache read tokens, which Anthropic reports separately from input tokens. OpenAI cached tokens are already included in prompt tokens, so AISIX does not count them twice.
Because the provider reports usage after generating a response, AISIX records a request's tokens only once it completes. Admission checks the tokens recorded so far, so the requests in flight are not counted against the limit. Usage can therefore exceed the limit, as described in Token Limit Overruns.
Only token usage that the upstream response reports, or that the gateway estimates when the response omits it, advances the token counters. Some media calls report none and are not estimated, so they add nothing to tpm or tpd: whisper-1 transcriptions and translations, every text-to-speech request, dall-e-2 and dall-e-3 image generations and edits, and video requests. Models that do report token usage, such as gpt-4o-transcribe and gpt-image-1, are counted normally. Audio duration is recorded for cost calculation only and does not count toward token limits. A call that adds no tokens is still rejected when an applicable tpm or tpd window is already exhausted, whatever its endpoint.
Token limits attached directly to caller API keys or models support minute and day windows only. There is no per-second or per-hour token field for these resources. Classic rate-limit policies also enforce token caps with minute and day windows. The AISIX Cloud Admin API rejects token caps with second or hour windows. For the open-source AISIX gateway, the resources schema accepts those combinations, but the runtime does not enforce the token cap.
Estimated Usage and Token Limits
By default, tokens the gateway estimated count toward token limits like reported tokens. An AISIX Enterprise or AISIX Cloud organization can leave them out with Keep estimated requests out of budgets and token rate limits in the Estimated usage card of the Settings view's Policies tab. The same setting leaves estimated requests out of budgets; see Leave Estimated Usage Out of Budgets for who can change it and when a change takes effect.
While the setting is on, a request whose usage the gateway estimated, even partly, adds no tokens to any token window: tpm, tpd, and a classic policy's max_tokens. Request-count limits and concurrency still count it, and the admission check before the provider call is unchanged. The usage event still records the estimated tokens. A request whose usage the upstream reported counts as before.
A stream the caller closes before the upstream reports usage is estimated too, so it adds no tokens either. Turn the setting on only when every caller is trusted.
Gateways earlier than 1.11.0 do not recognize the setting and keep counting estimated tokens toward token limits. Upgrade the gateways before relying on it.
Token Limit Overruns
When recorded usage reaches a token limit, AISIX rejects new requests, but every request it has already admitted still completes and is counted. Under concurrency, the overrun is therefore not limited to the one request that crossed the limit. It is roughly the number of requests in flight when the limit is reached, multiplied by the largest token usage of one request.
For example, with 10 requests in flight that each use at most 40 tokens, usage can exceed a tpm limit by about 400 tokens.
The number of requests in flight depends on the counter backend:
- With Redis, count the in-flight requests across all gateway instances that share the backend.
- With the memory backend, each instance counts only its own traffic, so multiply the overrun by the number of instances. The limit itself also applies per instance, as described in Choose Rate-Limit Counter Storage.
A concurrency limit caps the requests in flight, which reduces the overrun. It rejects the excess requests with 429 rather than queueing them.
AISIX does not enforce a strict token cap. Use this figure to size a limit, not as a guarantee.
Choose a Window Type
window_type selects how the minute, hour, and day limits count: rpm, tpm, rph, rpd, and tpd. It accepts fixed, the default, or sliding. It does not affect rps or concurrency.
You can set window_type in these places:
- A caller API key's
rate_limit. - Each server entry in a caller API key's
mcp_rate_limits, where it applies torpm,rph, andrpd. - A model's
rate_limit. - A conditional rate limit policy's
limits.
Classic rate limit policies, which use window with max_requests or max_tokens, always count fixed windows and do not accept window_type.
A fixed window resets at each UTC boundary, as described in Rate Limit Fields and Counter Behavior. A sliding window records usage in sub-buckets of a fixed step and checks each request against the sum of the sub-buckets that cover one full window:
| Fields | Window | Sub-Bucket Step |
|---|---|---|
rpm, tpm | 60 seconds | 10 seconds |
rph | 3,600 seconds | 5 minutes |
rpd, tpd | 86,400 seconds | 1 hour |
No interval of one window's length admits more requests than a request limit. Token limits check the same sum against recorded usage only, so requests in flight can still overrun them, as described in Token Limit Overruns. The trade-off is granularity: usage leaves the count up to one step later than the window length. For example, an rpm request recorded at 10:00:03 stops counting at 10:01:10.
The difference shows across a boundary. With rph: 10, suppose a caller sends 10 requests between 10:55 and 10:59, then 10 more starting at 11:00:
- With
fixed, the hourly count resets at 11:00, so all 20 requests are admitted within about ten minutes, close to twice the limit. - With
sliding, the sum at 11:00 still includes the requests from 10:55, so the second burst is rejected until those requests leave the window.
Changing window_type between fixed and sliding starts the counts from zero.
The rate-limit headers report a sliding window's state as follows:
- When a sliding limit rejects a request,
Retry-AfterandX-RateLimit-Resetgive the exact wait until the request can be admitted, in whole seconds, rounded up, with a minimum of 1. - For
tpmandtpd, the wait is until cumulative usage drops below the limit, because the token count of the rejected request is not known yet. - When several limits are set, the headers give the wait for the limit that rejected the request.
- On successful Chat Completions responses,
x-ratelimit-reset-requestsandx-ratelimit-reset-tokensreport the time until the whole current count has left the window.
In AISIX Enterprise and AISIX Cloud, fixed is not stored or returned by the Admin API; an omitted value reads as fixed. The control plane also drops sliding from a limit that sets none of rpm, tpm, rph, rpd, or tpd, because it would change no behavior. In AISIX OSS, the resources file accepts the field, but it affects only those five dimensions.
Upgrade Gateways Before Using Sliding Windows
sliding requires AISIX gateway 1.10.0 or later. An older gateway ignores the field and keeps counting fixed windows, and gateways of different versions that share Redis counters count separately, so together they can admit more than the limit. To prevent this, AISIX Enterprise and AISIX Cloud refuse to save sliding with 422 DP_INCOMPATIBLE while a gateway registered in the target environment runs a release older than 1.10.0.
While such a gateway is registered, every save of a caller API key, model, or rate limit policy that already holds sliding is also refused, including disabling or rotating a caller API key. Deleting one is not affected. Upgrade every gateway in the environment to 1.10.0 or later before you enable sliding windows.
Configure a Sliding Window
In the dashboard, a Window type control with Fixed window and Sliding window options appears in four forms:
- API keys: in a caller API key's Rate limits controls, and for each server under Per-MCP-server limits.
- Models: in the model's Rate limits fields.
- Rate limits: in a conditional policy's Limits section.
The control is available once the form sets at least one minute, hour, or day limit.
For automation, set window_type alongside the limits. The following request gives a caller API key a sliding limit of ten requests per hour:
curl -sS -X PATCH "${AISIX_CP}/environments/${ENV_ID}/api_keys/${API_KEY_ID}" \
-H "Authorization: Bearer ${AISIX_TOKEN}" \
-H "Content-Type: application/json" \
-d '{
"rate_limit": {
"rph": 10,
"window_type": "sliding"
}
}'
For the open-source AISIX gateway, add the same field to the entry in the resources file:
api_keys:
- id: a31b8275-cc81-4cdc-a618-875fd28c7532
display_name: chat-app
key_hash: ${CALLER_API_KEY_SHA256}
allowed_models:
- gpt-4o-prod
rate_limit:
rph: 10
window_type: sliding
How Model Limits Apply
If a request matches both caller and model limits, AISIX counts it against the request-count and concurrency limits of both buckets. Exhausting either bucket rejects the request. Tokens are not reserved in either bucket; see Token Limit Overruns.
Model limits also apply when a direct model serves as the target of a routing model or semantic router. Routing dispatch skips a target that is over its own limit and continues with the remaining targets; when every target is over its limit, the request returns 429. Semantic dispatch enforces the selected target's limit and returns 429 when that target has no capacity. How many times each layer counts a retried or failed-over request is described in How Requests Are Counted.
Inject-mode passthrough routes can also reserve model limits. AISIX does this when the request body names a model of the route's provider key's provider, by its alias or provider-native name. The matched model shares the same request-count and concurrency buckets as modeled routes; forward_client routes never consult the model probe. Caller-level request-count and concurrency layers apply to every route.
An applicable tpm or tpd window that is already exhausted still rejects a passthrough request. Passthrough usage does not advance those token counters, however, even when AISIX detects a recognized envelope and records token usage on the request's usage event.
How Requests Are Counted
A limit counts the requests that arrive at what it limits. Retries and failovers that a model performs on its own are that model's internal behavior and add nothing to the count.
- Caller limits count once per request the caller sends. These are the caller API key's own limit, the classic policies scoped to an API key, team, member, or each member in a team, and MCP server limits.
- A model group or semantic router counts once per request addressed to it. Its retries and failovers are internal. When a semantic router picks a model group as its target, that group also counts once for the request.
- A direct model counts once per request it receives. A request that a caller sends to it directly counts once, however many times AISIX retries it, because those retries are internal. When a model group dispatches to it, every attempt the group sends, same-target retries included, is a separate request that the direct model receives and counts. A direct model that is over its own limit is skipped, and the group tries the next target. Direct and routed requests to the same model share its bucket.
- A conditional policy counts like what its conditions and buckets resolve to. When the caller or the addressed group alone settles the match, the policy counts once per request, for example
member in {U} AND model in {G},model in {G, A}where G is the group, ormodel in {G} OR provider == openai. When the match depends on which direct model receives the attempt, the policy counts once per attempt at that direct model, for exampleprovider == openai,model == G AND NOT provider == X, ormodel ~= M. Agroup_bythat containsmodelorprovideralso counts once per attempt, because its buckets belong to the direct model that receives the attempt, never to the group.
These limits refer to AISIX model entries, by ID or alias, never to a provider-side model name. A classic model policy counts like the model it names. Token limits are charged once per request, with the usage of the attempt that served it.
For example, model group G has two targets: A, whose provider is openai, and B, whose provider is anthropic. A member's API key calls G. A fails and is retried once on A, then B succeeds, so the attempts are A, A, B:
| Limit | Counted |
|---|---|
The API key's own rpm | 1 |
G's own rate_limit | 1 |
A's own rate_limit | 2 |
B's own rate_limit | 1 |
Policy member in {U} AND model in {G}, group_by: [member] | 1, in that member's bucket |
Policy model == G, group_by: [model] | 2 in A's bucket, 1 in B's |
Policy model == G AND provider == openai | 2 |
If the same key calls A directly and A is retried twice before it succeeds, the request counts 1 against A's own limit.
Typical setups:
- To protect a provider deployment's quota, put the limit on the direct model that serves it.
- To cap each member's use of a group regardless of failover, match
model in {G}in a policy withgroup_by: [member]. - To give each target of a group its own cap from one policy, match
model == Gwithgroup_by: [model].
A request that the gateway's own rate limiter refuses before any attempt reaches the upstream consumes no quota at any layer. When one layer refuses a request, AISIX returns the counts the other layers had already taken for it. A model group request that returns 429 because every target was over its own limit, with no attempt sent upstream, does not charge the caller API key, the group's own limit, or the request-level policies either.
An attempt that AISIX sent upstream always counts, whatever the upstream returned, including a 5xx or an upstream 429. So does the request it belongs to: when an earlier attempt went upstream and the last target is then refused by its own limit, the request keeps the counts it already took. A count is also kept when its window has rolled over before the refund, or when the refund cannot reach Redis.
The request logs show the same distinction. In the console Logs view, a retried or failed-over request appears as one row per attempt, which lines up with the target model counters. Select Last attempt per request to see one row per downstream request instead, as described in Show the Last Attempt of Each Request.
Choose Rate-Limit Counter Storage
Gateway startup configuration determines whether rate-limit counters are local to one process or shared across gateway instances. The setting applies to limits attached directly to resources and to reusable policies enforced by that gateway.
| Backend | Counter Scope | Use When |
|---|---|---|
| Memory, the default | One gateway process | A single instance enforces the limit, or per-instance quotas are acceptable. |
| Redis | Every gateway instance using the same Redis backend | A deployment must enforce one shared request, token, or concurrency quota. |
With the memory backend, each gateway instance counts only the traffic it handles. In an evenly distributed deployment with multiple instances, the aggregate traffic admitted during a window can therefore exceed the configured per-process limit. Consistent routing can reduce that variation for one caller or tenant, but Redis is the shared-counter option.
Configure Redis when several gateway instances must enforce one quota:
ratelimit:
backend: redis
redis:
mode: single
url: redis://127.0.0.1:6379/
The gateway requires the ratelimit.redis block when ratelimit.backend is redis, and startup fails when that block is missing. A Redis the gateway cannot reach at startup no longer fails startup, but the bounded startup connection attempts can delay all listeners. After those attempts finish, Redis no longer blocks listener startup, and the gateway logs one warning with the backend, configured endpoint values, reason, and connection error. When the proxy listener becomes available, the gateway counts per replica. The warning is restated every five minutes, and a background task attaches the shared backend as soon as Redis answers. The gateway never switches permanently to the memory backend, and cluster-wide limits are not enforced while it is degraded.
The warning includes the configured endpoint values verbatim: url in single mode, nodes in cluster mode, and sentinels in sentinel mode. Any credentials embedded in those values are logged too. Use the separate username and password fields for data-node credentials. Sentinel-node credentials remain part of the sentinel URLs, so restrict access to gateway logs.
Startup fails for local configuration and resolution errors that cannot recover in the background. That includes an unparsable url; TLS material AISIX cannot read or parse; a client certificate or key configured without its matching key or certificate; ratelimit.concurrency_ttl_secs: 0; a missing url, nodes, sentinels, or master_name for the selected mode; timeout_secs: 0; or a hostname that resolves to no address. A Redis that answers and refuses the connection settings takes the degraded path instead. That covers a rejected credential, a NOAUTH or DENIED answer, and a database the server does not have. The warning carries reason=refused rather than reason=unreachable, and the five-minute restatement carries the same word. The gateway keeps re-attaching, so a credential corrected on the Redis side is adopted without a restart.
A Redis outage degrades rate limiting to process-local counters, whether the outage is already under way when the gateway starts or begins later. Requests remain protected by per-process limits, but the deployment does not enforce one cluster-wide quota during the outage. Outage-time counts are not copied back to Redis, so counters can remain different until the active windows roll over after recovery.
ratelimit.redis.timeout_secs sets how long the gateway waits before that fail-open path takes over. It defaults to 5 seconds, with a minimum of 1, and 0 is rejected at startup naming the field. Shared counting resumes on its own once Redis answers again.
timeout_secs bounds a single Redis round trip or connection attempt, including each connection attempt the gateway makes at startup. A timeout or connectivity failure makes everything that subsystem does next short-circuit for 30 seconds instead of waiting again. A server-reported Redis error fails the current operation but does not open the short circuit. The cache's exact and vector connections count as one subsystem, while the rate limiter is another. The 30-second cool-off is sized to outlast an upstream call, because a request's cache read and its cache write straddle that call. A request therefore pays the budget once for the cache and once for the rate limiter, rather than once per Redis operation. A request whose upstream leg runs longer than 30 seconds can still pay a second budget on the write. In cluster and sentinel modes, the gateway wraps the whole startup topology walk in an aggregate budget of timeout_secs multiplied by the number of configured endpoints plus one. That product bounds the whole startup connect, not each attempt within it; each attempt keeps the single timeout_secs bound. In single mode, the whole startup connect has one timeout_secs budget.
A background task, not a business request, decides when the cool-off ends: when the 30 seconds expire it sends a Redis PING, closes the short circuit on success, and re-arms another 30 seconds on failure. Requests keep short-circuiting until it closes, so no request pays the timeout to discover that Redis is still down. Commands resume only after a successful background probe. Recovery can take more than one cool-off window after Redis becomes reachable again.
Local concurrency slots are released when requests complete. An SSE relay retains every matching slot until the response body closes or is cancelled. A Redis-backed relay renews each live lease while Redis is reachable. Stale slots are recovered after concurrency_ttl_secs, which defaults to 300 seconds. If Redis reports that a live lease no longer exists, AISIX ends a passthrough SSE relay.
During a mixed-version rollout, treat earlier replicas according to how they hold each stream reservation. Where an earlier replica retains a reservation for the stream lifetime but cannot renew it, set ratelimit.concurrency_ttl_secs longer than the longest possible reservation, including the upstream-header wait and stream lifetime. A longer TTL also delays recovery of a slot left by a replica that crashes.
Passthrough SSE requires a different rollout. Replicas that release a passthrough reservation when they return the response head cannot be protected by a longer TTL. Stop sending those replicas new passthrough SSE requests before newer replicas begin enforcing the shared limit. Existing passthrough streams on the earlier replicas remain outside that concurrency count until they finish or are terminated.
Redis Connection Modes
The ratelimit.redis.mode field selects the Redis deployment type and determines which connection fields are required. The preceding example uses single mode with one url.
Use cluster for Redis Cluster seed nodes:
ratelimit:
backend: redis
redis:
mode: cluster
nodes:
- redis://10.0.0.1:6379/
- redis://10.0.0.2:6379/
Use sentinel for a Sentinel-managed master:
ratelimit:
backend: redis
redis:
mode: sentinel
sentinels:
- redis://10.0.0.1:26379/
- redis://10.0.0.2:26379/
master_name: mymaster
The required fields are:
| Mode | Required Connection Fields |
|---|---|
single | url |
cluster | One or more nodes entries |
sentinel | One or more sentinels entries and master_name |
Set username and password when Redis requires authentication. They apply in every mode, and they override a credential embedded in the url. A value supplied through the environment is therefore not outranked by a stale one left in the URL. Set them as a pair: providing either half replaces both, because composing a login from two sources produces one that exists in neither. database applies in single and sentinel modes; Redis Cluster has only DB 0. In sentinel mode, sentinel-node credentials belong in the sentinel URLs, while username, password, and database apply to the discovered Redis master.
Troubleshooting
Start with the rejected request's scope and then identify every limit that can match it.
| Symptom | What to Check |
|---|---|
| A configured limit does not apply. | For AISIX Enterprise or AISIX Cloud, confirm that the change has projected to the gateway. For the open-source AISIX gateway, confirm that the resources file was reloaded. Then verify that the request uses the expected caller API key and model. |
| A request is rejected below the expected caller limit. | Check for a model limit and rate-limit policies that match the API key, model, team, member, or provider. Every matching layer must pass. |
| Aggregate traffic exceeds the configured limit across gateway instances. | Check ratelimit.backend. The memory backend keeps an independent counter in every process; use Redis for one shared quota. |
| The limit of a model group's target model runs out sooner than the request count suggests. | This is expected when the target model retries or receives failovers: its own limits count every attempt dispatched to it, while the caller API key and the group's own limit count each request once. See How Requests Are Counted. |
| A token-limited request succeeds and the next request is rejected, or usage exceeds the limit. | This is expected when the successful responses consume the remaining token capacity. Token usage is recorded after the provider reports it, so every request in flight when the limit is reached still completes and counts. See Token Limit Overruns. |
Next Steps
Configure Rate-Limit Policies when direct caller and model limits are not expressive enough. Continue with Response Caching to reuse eligible Chat Completions responses, or review Metrics to monitor rate-limit rejections.