# Rate Limit Counter Storage

Rate-limit counters use process-local memory by default. In a two-instance deployment, each instance can therefore admit up to the configured limit. Configure Redis when the deployment must enforce one shared request, token, or concurrency quota.

Both gateway instances then read and update the same counter:

<!-- -->

Backend selection also determines how AISIX starts, degrades, recovers, authenticates to Redis, and maintains concurrency leases during rolling upgrades.

## Prerequisites[​](#prerequisites "Direct link to Prerequisites")

Before configuring shared counters, prepare the following:

* Two AISIX gateway instances that load the same environment or resources snapshot
* A Redis deployment reachable from both gateway instances
* A working model alias and caller API key
* Direct origins for both gateway instances, so verification can send one request to each

Export the values used in the verification example:

```
# Gateway origins have no trailing slash or endpoint path.

export AISIX_PROXY_A="YOUR_FIRST_GATEWAY_ORIGIN"

export AISIX_PROXY_B="YOUR_SECOND_GATEWAY_ORIGIN"

export AISIX_MODEL="YOUR_MODEL_ALIAS"

export AISIX_API_KEY="YOUR_CALLER_API_KEY"
```

## Choose Memory or Redis[​](#choose-memory-or-redis "Direct link to Choose Memory or Redis")

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, aggregate traffic can therefore exceed the configured per-process limit. Consistent routing can reduce that variation for one caller or tenant, but only Redis provides a shared counter.

## Configure and Verify Redis[​](#configure-and-verify-redis "Direct link to Configure and Verify Redis")

Use the same Redis configuration on every gateway instance that should enforce the shared quota:

config.yaml

```
ratelimit:

  backend: redis

  redis:

    mode: single

    url: redis://YOUR_REDIS_HOST:6379/
```

Replace `YOUR_REDIS_HOST` with the shared Redis hostname or address, apply the configuration to both gateway instances, and restart them.

### Verify Shared Counting[​](#verify-shared-counting "Direct link to Verify Shared Counting")

First configure a one-request-per-minute limit on a caller API key, as described in [Configure a Caller API Key Limit](https://docs.api7.ai/ai-gateway/traffic-controls/rate-limits.md#configure-a-caller-api-key-limit). Wait for a new UTC minute, then address two gateway instances directly and send one request through each:

```
for AISIX_PROXY_INSTANCE in "${AISIX_PROXY_A}" "${AISIX_PROXY_B}"; do

  curl -sS -o /dev/null -w "%{http_code}\n" \

    -X POST "${AISIX_PROXY_INSTANCE}/v1/chat/completions" \

    -H "Authorization: Bearer ${AISIX_API_KEY}" \

    -H "Content-Type: application/json" \

    --data-binary @- <<EOF

{

  "model": "${AISIX_MODEL}",

  "messages": [{"role": "user", "content": "Verify shared rate limiting."}]

}

EOF

done
```

The first request should return `200` and the second `429`.

| Result                           | What to Check                                                                                                                                             |
| -------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- |
| The first request returns `429`. | The current minute already contains usage. Wait for the next UTC minute and retry.                                                                        |
| Both requests return `200`.      | Confirm that the limit reached both gateways and that they use `ratelimit.backend: redis`, the same Redis deployment, and the same environment namespace. |

The `200`, `429` sequence confirms that both gateways used the same counter. With the memory backend, each instance would admit its own first request, producing `200`, `200` instead.

## Handle Redis Failures[​](#handle-redis-failures "Direct link to Handle Redis Failures")

AISIX distinguishes configuration errors from Redis availability problems:

| Situation                                                                             | Gateway Behavior                                                                                                                                       | Operator Action                                                                                                   |
| ------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------- |
| The Redis configuration is missing or cannot be used locally.                         | Startup fails.                                                                                                                                         | Correct the configuration and restart the gateway.                                                                |
| Redis is unreachable during startup.                                                  | Startup attempts can delay the listeners. The gateway then serves with per-process counters, logs `reason=unreachable`, and retries in the background. | Restore Redis availability.                                                                                       |
| Redis responds but refuses the credentials or database, such as `NOAUTH` or `DENIED`. | The gateway serves with per-process counters, logs `reason=refused`, and retries in the background.                                                    | Correct the Redis-side credentials or database. The gateway reconnects without a restart.                         |
| Redis becomes unavailable after startup.                                              | The gateway continues with per-process counters. Counts recorded during the outage are not copied to Redis.                                            | Restore Redis; shared enforcement resumes automatically, while divergent counts expire with their active windows. |

The startup warning names the backend, configured endpoints, failure reason, and connection error. It repeats every five minutes until a background task attaches the shared backend. This degraded state does not permanently change `ratelimit.backend` to `memory`.

Redis endpoint values can expose credentials

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.

### Fix Startup Configuration Errors[​](#fix-startup-configuration-errors "Direct link to Fix Startup Configuration Errors")

Startup stops for local configuration and resolution errors that cannot recover in the background, including:

* An unparsable `url` or a hostname that resolves to no address
* TLS material AISIX cannot read or parse
* A client certificate or key without its matching key or certificate
* A zero `ratelimit.concurrency_ttl_secs` or `timeout_secs`
* A missing `url`, `nodes`, `sentinels`, or `master_name` for the selected mode

### Configure Timeouts and Recovery[​](#configure-timeouts-and-recovery "Direct link to Configure Timeouts and Recovery")

`ratelimit.redis.timeout_secs` controls Redis connection and command waits:

| Case                            | Behavior                                                                                                                                                                      |
| ------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Field value                     | Defaults to `5` seconds and has a minimum of `1`. A value of `0` stops startup and names the field.                                                                           |
| One Redis operation             | Each round trip or connection attempt can wait up to `timeout_secs`.                                                                                                          |
| `single` mode startup           | The complete startup connection has one `timeout_secs` budget.                                                                                                                |
| `cluster` or `sentinel` startup | The complete topology walk has an aggregate budget of `timeout_secs` multiplied by the configured endpoint count plus one. Each attempt still has the single-operation bound. |
| Timeout or connectivity failure | Redis operations short-circuit for 30 seconds. A background `PING` restores shared counting after Redis responds, so business requests do not probe the failed connection.    |

The cache and rate limiter use separate recovery circuits. An outage affecting both can therefore make one request incur one timeout from each subsystem before their circuits open.

Recovery can take more than one 30-second interval after Redis becomes reachable if the first background probe still fails.

## Manage Concurrency Leases During Rollouts[​](#manage-concurrency-leases-during-rollouts "Direct link to Manage Concurrency Leases During Rollouts")

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.

Mixed-version rollout

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.

## Configure Redis Connection Modes[​](#configure-redis-connection-modes "Direct link to Configure 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:

config.yaml

```
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:

config.yaml

```
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 override credentials embedded in the data-node URL. Set them as a pair: providing either field replaces both, which prevents AISIX from composing a login from two sources.

`database` applies in `single` and `sentinel` modes; Redis Cluster uses DB 0 only. In sentinel mode, credentials in the sentinel URLs authenticate to the Sentinel nodes. The separate `username`, `password`, and `database` fields apply to the discovered Redis master.

## Troubleshooting[​](#troubleshooting "Direct link to Troubleshooting")

| Symptom                                                                  | What to Check                                                                                                                |
| ------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------- |
| 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 gateway is serving traffic but cluster-wide limits are not enforced. | Check for Redis startup or outage warnings. AISIX uses process-local counters until the shared backend reconnects.           |

## Next Steps[​](#next-steps "Direct link to Next Steps")

Return to [API Key and Model Rate Limits](https://docs.api7.ai/ai-gateway/traffic-controls/rate-limits.md) to configure and verify limits. Review [Rate Limit Request and Token Counting](https://docs.api7.ai/ai-gateway/traffic-controls/rate-limit-runtime-behavior.md) for model routing, retries, token accounting, and refunds.
