Overview
theAuth has three separate rate limiting mechanisms:- The
rateLimit()plugin: per-IP limits on/auth/*endpoints, with a pluggable store. It is opt-in. - Per-endpoint limits that individual plugins declare in their endpoint metadata. These apply automatically once the plugin is installed.
- The
maxCallsPerHourpermission constraint, enforced by the permission engine for agent calls.
rateLimit option on createTheAuth() and no single shared 429 response shape. Counter storage for the plugin follows secondaryStorage (memory, database, Redis, Cloudflare KV or your own). Each mechanism is described below.
The rateLimit plugin
Install the plugin to throttle/auth/* requests by IP. Nothing is limited until you add it, and a request is only limited if its path matches a configured key (or default is set).
Counter storage. Omit it to follow
secondaryStorage.rateLimit from createTheAuth (memory by default). Pass redisStorage(), databaseStorage(), cloudflareKvStorage() or any RateLimitStore. See Secondary storage for the tradeoffs; KV counters are approximate.How many reverse proxies you run. With
x-forwarded-for: a, b, c and a count of 1 the client is c, the entry your proxy added. With 0 the header is ignored, because clients can forge it.A header your edge overwrites, such as
cf-connecting-ip or x-real-ip. Takes precedence over trustedProxyCount. Only set it when the app is reachable only through that edge.What identifies a caller.
client_id is read from the query string, a form or JSON body, or Basic auth, and falls back to the IP. A caller can rotate client ids, so use ip+client_id when you want both bounds.Limits for
/mcp/token, /mcp/register and the device endpoints. Defaults: 60/min, 10/hour, 10/min, 60/min, 20/min, 60/min. false turns one off.Rate limit key for the client part. Defaults to the IP from
trustedHeader or trustedProxyCount, and to a shared "unknown" bucket when neither is set. Forwarded headers are no longer trusted by default: if you run behind a proxy, set trustedProxyCount or trustedHeader, otherwise all clients share one bucket.window is a duration string: a number followed by s, m, h, or d (for example "30s", "15m", "1h"). Any other format throws when the first request is checked. The window is a fixed window starting at the first request for that key and path, and the counter is keyed by path plus client key.
When the limit is exceeded, the response is 429 with this body, plus Retry-After, X-RateLimit-Limit, X-RateLimit-Remaining (always 0), and X-RateLimit-Reset headers:
Adapter admission and unknown client IPs
Every framework adapter runs an admission step before authentication: tiered rate limits (strict for /mcp/token, /mcp/register and authorize, mutation, read) and a cross-site check for cookie writes. It keys on the client IP.
Hono, Next.js, SvelteKit, Astro, Nuxt, SolidStart and TanStack never see the socket peer, so without trustedProxy the IP is unknown. In that case requests fall into three fixed buckets per tier: anonymous (no credentials), cookie and authorization. The bucket never depends on the value of the header, so a random Cookie or Authorization cannot mint a fresh bucket. The consequence is that limits are not per client: all anonymous callers share one budget. The first such request logs a one-time warning through your logger.
To get per-client limits, do one of:
- Set
trustedProxy(trustedHeaderfor an edge that overwrites a header such ascf-connecting-ip, ortrustedProxyCount). - Pass
rateLimit.keywith your own function, for example one built onresolveClientIp, or on a verified OAuthclient_id.
When the counter store fails
Shared counters can fail (Redis down, database timeout). By default every limiter fails open: the request is let through, so a store outage never takes sign-in and sign-up down with it. The cost is that an attacker who can break the store can also switch throttling off. Each limiter logs a startup warning through the TheAuth logger (config.logger) while it fails open.
Set failClosed: true to refuse the request with 503 and Retry-After: 5 instead:
hibp: { failClosed: true }) and password lockout has username.lockout.failClosed; see Breach checking and Email and password. Run theauth doctor to see which limiters are failing open.
Per-endpoint limits declared by plugins
Some plugin endpoints carry their ownmetadata.rateLimit (for example the email OTP, magic link, anonymous, device, SIWE, OAuth proxy, and OAuth authorize endpoints). The plugin router enforces these with an in-process counter keyed by IP and endpoint path, and responds 429 with { "error": "Rate limit exceeded" } and no Retry-After header. They are fixed in the plugin source, not configurable through rateLimit(), and not shared across instances. Note that the router interprets window in seconds, so window: 60 means 60 seconds.
Per-agent limits with maxCallsPerHour
The permission engine supports amaxCallsPerHour constraint. When an agent exceeds its hourly call budget, authorize() returns allowed: false with a reason that starts with Rate limit exceeded.
- It is a rolling hour, not a clock-hour reset. Calls are recorded in 5 minute buckets in the
theauth_rate_limitstable, and every bucket from the last hour is summed. Because the counters live in the database, they are shared across instances. - The counter is keyed by agent ID and the requested resource string (for example
db:reports:monthly), not by the permission pattern. Adb:reports:*permission therefore keeps a separate count for each concrete resource requested. - A call is counted when the rate check passes, even if a later constraint on the same permission (argument patterns, approval, time window, IP allowlist) denies it.
- Only the first permission whose resource and action match is evaluated by
authorize(). - Budget policies (
theauth.policies) are a different module and are not part of this check.
Checking the limit in your code
authorize() does not produce an HTTP response, so choosing the status and Retry-After value is up to your code. A slot frees up when the oldest 5 minute bucket leaves the window, so a short Retry-After is reasonable. The onViolation hook receives these denials with type rate_limited.
createRateLimiter
createRateLimiter is a small in-memory sliding window limiter. It is synchronous, per process, and keyed by a string you pass in.
check(key) returns { allowed, remaining, resetAt } and consumes a slot when allowed. There are no limit, keyFn, store, or redisUrl options.
withRateLimit middleware
withRateLimit(handler, limiter, options?) wraps a plugin endpoint handler (the (request, ctx) => Promise<Response> shape used by TheAuthPlugin endpoints) so it is checked against a limiter first.
withRateLimit returns a 429 response with a Retry-After header and the body { "error": { "code": "RATE_LIMITED", "message": "Too many requests" } }, and does not call the wrapped handler. Like the plugin, withRateLimit ignores forwarded headers by default and keys on "unknown" when the client IP cannot be resolved, so every caller shares one bucket. Pass trustedProxyCount or trustedHeader, or your own keyExtractor built on resolveClientIp, when you run behind a proxy.
Next steps
Permissions
Add maxCallsPerHour and other constraints to individual permissions.
Approval flows
Pair rate limits with human-in-the-loop approval for sensitive actions.
Hooks
React to rate_limited denials with the onViolation hook.
Protecting /mcp and the device endpoints
The plugin hook runs for requests that go throughtheauth.plugins.handleRequest, which covers the device endpoints. The /mcp/token and /mcp/register handlers are mounted by your app, so run the hooks first: