# Rate limiting & penalty

> **Sentinel v2 (beta):** This page documents Sentinel v2, a beta rewrite that may change before the stable release. It does not apply to Sentinel v1, the current stable version: see the [Sentinel v1 documentation](/docs/sentinel.md).

Sentinel limits request rates at two levels: a global limit per client IP that the operator sets in the server configuration, and per-security-group limits set by rules. Rate-limit pressure, header rotation and other misbehavior raise the client's penalty, which rules can act on.

## How it works

| Mechanism | Configured by | Counts | Over the limit |
| --- | --- | --- | --- |
| Global limit | `[rate_limit] global` | Every API request (`/v2`, and the `/v1` widget aliases with `v1_compat`), per client IP | `429 RATE_LIMITED` |
| Rule limits | `rateLimit.limits`, `rateLimit.scope` | API-key requests the rules allow, per device (EDK), client IP, or scope | `429 RATE_LIMITED` |
| Header entropy | `headerEntropy.limit` | Distinct device header sets per client IP | `429 HEADER_ENTROPY` |
| Penalty | Set by the sources below; `[penalty] ttl` | A 0–10 score per account and client IP | Nothing by itself; rules decide |

All of them live in the KV store (embedded, or `[redis]`), so replicas share their counters. The client IP is the one Sentinel resolves from `[server] trusted_proxies` and `client_ip_header`; if every client appears as your proxy's IP, they all share one bucket. See [IP resolvers](/docs/sentinel/v2/configure/ip-resolvers/) and [Listeners & reverse proxy](/docs/sentinel/v2/configure/listeners/).

### Limit syntax

Limits are comma-separated `points/duration[(params)]`, for example `10/1m,100/1h(sliding&key=ip)`:

- `points` is a whole number above 0; `duration` a number with `s`, `m`, `h` or `d`.
- Params are `&`-separated `name=value` pairs, case-insensitive. A bare `sliding` or `flexible` is short for `algo=`.
- `algo=flexible` (default) is a fixed window that starts with the first hit. `algo=sliding` counts the hits of the last `duration`.
- `key` picks the bucket (rule limits only): `edk` (default), `ip` or `uid`.

### Global limit

When enabled, every API request counts against `[rate_limit] global` by client IP, on every listener that serves the API. This includes:

- Every `/v2` route: login, OTP, management, detection and the widget endpoints, plus unknown `/v2` paths that answer `404`.
- With `[server] v1_compat = true`, the `/v1/challenge`, `/v1/challenge/audio/…`, `/v1/verify` and `/v1/verify/signature` aliases. They're rewritten to `/v2` before the limit, so a client's `/v1` and `/v2` requests share one bucket. See [Existing `/v1` widget paths](/docs/sentinel/v2/configure/listeners/#existing-v1-widget-paths).

The ping (`/`), `/.health`, the honeypot paths, the admin UI's static files and CORS preflights of the widget endpoints don't count. The limit's 429s count as [threat signals](/docs/sentinel/v2/features/threat-intelligence/); rule limits and header entropy don't.

### Rule limits

After the rules allow an API-key request, Sentinel counts one hit on each `rateLimit.limits` limit, in order. The first exceeded limit answers `429 RATE_LIMITED`; later limits aren't counted. The `key` param picks the bucket:

| `key` | One bucket per |
| --- | --- |
| `edk` (default) | Device: the [EDK](#device-key-edk) of client IP, User-Agent, Accept-Language and an optional seed, rotated daily |
| `ip` | Client IP |
| `uid` | Scope: all requests together |

`rateLimit.scope` sets the scope: `apiKey` (default) gives each API key its own buckets, `account` shares them across all keys of the account. With HIS on, `GET /v2/challenge` isn't counted; the `POST /v2/challenge` is.

Allowed requests of `restricted` and `full` keys carry `X-RateLimit-Limit`, `X-RateLimit-Window` and `X-RateLimit-Remaining` for the limit with the fewest remaining points. `public` keys get rate-limit headers only on the 429.

### Device key (EDK)

The EDK is a daily device identifier: 32 hex characters, a network part (from the client IP, an IPv6 address reduced to its /64) followed by a device part (client IP, User-Agent, Accept-Language and an optional seed). It's derived with an HMAC of `secrets.encryption_key`, rotates at midnight in `[edk] time_zone`, and is reported as `device.edk` by `/v2/verify`, `/v2/classifier` and `/v2/inspect`.

Users behind one IP with the same browser share an EDK. A seed separates them, for example a user ID. Sentinel reads it, in order, from:

1. `[edk] seed_header`, set by your proxy and trusted like `[server] client_ip_header`. The proxy must overwrite client-sent values.
2. `[edk] seed_cookie`, signed with `seed_cookie_secret`: `<seed>.<hex HMAC-SHA256(seed_cookie_secret, seed)>`. The widget's cross-origin requests send no cookies, so this only works when Sentinel is served same-site.

```bash
SIG=$(printf '%s' "$SEED" | openssl dgst -sha256 -hmac "$SECRET" -hex | cut -d' ' -f2)
echo "edk_seed=$SEED.$SIG"
```

An invalid cookie means no seed.

### Header entropy

Header entropy counts the distinct device header sets (`device.headerHash`: a hash of `Accept-Language`, `User-Agent`, `Sec-CH-UA-Mobile`, `Sec-CH-UA-Platform` and `Sec-CH-UA`) that one client IP shows within a fixed window. It catches clients that rotate headers to look like many devices, which also rotates their EDK. It's off until a rule sets `headerEntropy.limit`.

`GET /v2/challenge` (with HIS on, `POST /v2/challenge` instead) and `GET /v2/inspect` record the hash per client IP and `rateLimit.scope`. The request that brings more than N distinct hashes, and every later request of that IP until the window ends, gets `429 HEADER_ENTROPY`.

### Penalty

The penalty is a 0–10 score per account and client IP that expires `[penalty] ttl` after its last increase. [Scores, risk & penalty](/docs/sentinel/v2/concepts/scoring/#penalty) explains the model and lists every source. The sources this page configures:

- `rateLimit.limits` with `key=edk` or `key=ip` add 1 at every 20% of a limit's points (every `ceil(points / 5)`th hit in the window). A `key=uid` limit adds nothing, because all clients share its bucket.
- Each new distinct header hash beyond the first in a header-entropy window adds `headerEntropy.penalty`, including the one that gets the 429.
- A matching `penalty.add` rule adds its value (−10 to 10) when evaluation ends in allow, before `rateLimit.limits` is counted.

The `penalty` condition reads the value from before the current request, so a rule can deny or escalate a client once it crosses a threshold.

## Enabling it

### Global limit

The global limit is on by default at `100/1m`:

```toml
[rate_limit]
enabled = true                       # the only way to disable it
global  = "100/1m,1000/1h(sliding)"  # per client IP; key=uid is rejected here
```

`global` only takes `key=ip` (the default). An empty `global` falls back to `100/1m`. Every key is in [`[rate_limit]`](/docs/sentinel/v2/reference/configuration/#rate_limit).

### EDK seed and penalty TTL

```toml
[edk]
seed_header = "X-Edk-Seed"   # set by your proxy, e.g. to the logged-in user ID
time_zone   = "UTC"          # EDKs rotate at midnight here; pick a low-traffic zone

[penalty]
ttl = "30m"                  # a penalty expires this long after its last increase (>= 1s)
```

For the cookie seed, set `seed_cookie = "edk_seed"` and `seed_cookie_secret = "${EDK_SEED_COOKIE_SECRET}"` (at least 24 characters). An invalid `[edk]` setting fails startup. See [`[edk]`](/docs/sentinel/v2/reference/configuration/#edk) and [`[penalty]`](/docs/sentinel/v2/reference/configuration/#penalty).

### Security-group rules

This rule list denies clients with a penalty of 3 or more, then limits each client IP to 10 requests a minute and each device to 100 an hour, and caps distinct header sets at 10 per 4 hours:

```json
[
{
"name": "penalized",
"action": "deny",
"message": "Slow down.",
"conditions": [{ "field": "penalty", "operator": ">=", "value": ["3"] }]
},
{
"name": "limits",
"action": "set",
"set": [
  { "field": "rateLimit.limits", "value": "10/1m(key=ip),100/1h(sliding)" },
  { "field": "headerEntropy.limit", "value": "10/4h" },
  { "field": "headerEntropy.penalty", "value": "1" }
]
}
]
```

| Field | Default | Description |
| --- | --- | --- |
| `rateLimit.limits` | — (no limit) | Limits in the syntax above. |
| `rateLimit.scope` | `apiKey` | `apiKey` or `account` (case-sensitive). |
| `headerEntropy.limit` | — (off) | `N/DURATION`, N 1–99, DURATION `1m` to `24h`. |
| `headerEntropy.penalty` | `1` | 0–10, at most one decimal; `0` turns it off. |
| `penalty.add` | — | −10 to 10, at most one decimal; negative values lower the penalty. |

The [Rules reference](/docs/sentinel/v2/reference/rules/#rate-limiting) has the full field list, and [Security rules](/docs/sentinel/v2/policies/security-rules/) shows how to apply rules.

## Rules & signals

| Signal | Meaning |
| --- | --- |
| `429 RATE_LIMITED` | The global limit or a rule limit is exceeded. `Retry-After` is in whole seconds; `X-RateLimit-Limit` and `X-RateLimit-Window` describe the exceeded limit. |
| `429 HEADER_ENTROPY` | Too many distinct header sets from the client IP. Same headers, with the header-entropy limit. |
| `penalty` condition | The client's penalty (0–10) from before the request, compared with `=`, `!=`, `>`, `>=`, `<` or `<=`. |
| `device.headerEntropy` | In `GET /v2/inspect`: the distinct header sets in the current window; `null` when `headerEntropy.limit` is off. |
| `RATE_LIMIT` | Classifier rule for the `rateLimit` of a `POST /v2/classifier` body: a separate, caller-chosen limit. See [Classifier](/docs/sentinel/v2/features/classifier/). |

See [Error codes](/docs/sentinel/v2/reference/errors/) for the exact headers.

## Using the API

With the rules above, the first 6 requests from one IP each add pressure on the `10/1m` limit (1 point every 2 hits). The 7th is denied by the `penalized` rule:

```bash
curl 'https://sentinel.example.com/v2/inspect?apiKey=key_…'
```

```json
{
"code": "ACCESS_DENIED",
"error": "Slow down.",
"statusCode": 403,
"data": { "penalty": 3.0, "risk": 7.0, "device": { "edk": "061f…", "headerEntropy": null, … }, … }
}
```

Without the deny rule, the 11th request in the minute exceeds the limit:

```http
HTTP/1.1 429 Too Many Requests
retry-after: 60
x-ratelimit-limit: 10
x-ratelimit-window: 60

{"code":"RATE_LIMITED","error":"Too many requests.","statusCode":429}
```

A client that changes its `User-Agent` on every request hits `headerEntropy.limit`; with `2/1h`, the third distinct header set gets:

```http
HTTP/1.1 429 Too Many Requests
retry-after: 3600
x-ratelimit-limit: 2
x-ratelimit-window: 3600

{"code":"HEADER_ENTROPY","error":"Too many requests.","statusCode":429}
```

`GET /v2/inspect` shows the penalty after this request's increments, the EDK and the header-entropy count. See the [`GET /v2/inspect` API reference](/sentinel-api-docs-v2.html#tag/inspect/GET/v2/inspect).

## Tuning

- **Key by device, not IP, for public widgets.** The default `key=edk` keeps users behind one office or mobile-carrier NAT apart. Use `key=ip` to stop a client that rotates headers, or pair `key=edk` limits with `headerEntropy.limit`.
- **Add a seed for logged-in users.** With `[edk] seed_header` set to a user ID, users sharing an IP and browser get separate EDKs.
- **Escalate before blocking.** Instead of denying, use the `penalty` condition to raise `pow.cost` or turn on `codeChallenge.enabled` for penalized clients, so real users can still get through. The penalty also rises on failed verifications and HIS blocks; see [Scores, risk & penalty](/docs/sentinel/v2/concepts/scoring/#penalty).
- **Size limits to the penalty you want.** Small limits add penalty quickly: a `5/1m` limit adds 1 on every hit, a `100/1m` limit on every 20th.
- **Lower a penalty with `penalty.add`.** A negative value on a trusted condition (for example, a known `ip`) lowers it.
- **Global limit and proxies.** If legitimate traffic hits the global limit, fix `[server] trusted_proxies` or `client_ip_header` first so clients aren't seen as one IP, then raise `global`.

## Limitations

- **KV outages.** After `[rate_limit] redis_fail_threshold` (default `3`) consecutive KV failures, the global and rule limits count in each replica's memory (up to `memory_max_keys` buckets), so a client can get up to N × the limit across N replicas. With `memory_fallback = false`, requests pass unlimited instead. Header entropy and the penalty fail open: requests aren't counted, the penalty reads as 0 and increases are skipped. See [Databases](/docs/sentinel/v2/configure/databases/).
- **Sliding limits** need `EVAL` support in the KV store. On a store without it, they fall back to per-replica memory.
- **Penalty is per IP.** Every API key of the account shares it, but clients behind one NAT share it too, and a client that changes IP starts at 0.
- **EDKs rotate daily** and on rotation of `secrets.encryption_key`, which resets `key=edk` buckets.
- Changing a limit's points, duration, algorithm or key starts a fresh bucket.

## Related

- [Scores, risk & penalty](/docs/sentinel/v2/concepts/scoring/)
- [Rules reference: Rate limiting](/docs/sentinel/v2/reference/rules/#rate-limiting)
- [Configuration reference: `[rate_limit]`](/docs/sentinel/v2/reference/configuration/#rate_limit)
- [Security rules](/docs/sentinel/v2/policies/security-rules/)
- [Human Interaction Signature](/docs/sentinel/v2/features/human-interaction-signature/)
- [Threat intelligence](/docs/sentinel/v2/features/threat-intelligence/)
- [Lookups & inspect](/docs/sentinel/v2/features/lookups/)
