Skip to main content

Module rate_limit

Module rate_limit 

Source
Expand description

Fixed-window rate limiter as a ServerInterceptor.

The distinction from a token bucket is not cosmetic and this line used to get it wrong: a fixed window admits up to 2 × requests_per_window across a window boundary — the tail of one window and the head of the next — where a token bucket would not. Anyone sizing a limit against an upstream’s hard ceiling needs to read that from the summary, not discover it further down.

Provides RateLimitInterceptor, a ready-made interceptor that limits request throughput per caller. The caller key is derived from CallContext::caller_identity; for unauthenticated callers behind a trusted reverse proxy, the client IP can be taken from x-forwarded-for (see RateLimitConfig::trusted_proxy_hops).

§Example

use a2a_protocol_server::rate_limit::{RateLimitInterceptor, RateLimitConfig};

let limiter = RateLimitInterceptor::new(
    RateLimitConfig::default()
        .with_requests_per_window(100)
        .with_window(std::time::Duration::from_secs(60)),
)
.expect("valid rate limit config");

Then add it to the handler builder:

let handler = RequestHandlerBuilder::new(executor)
    .with_agent_card(card())
    .with_interceptor(limiter)
    .build()?;

§Caller identity

The per-caller key is derived in this order:

  1. CallContext::caller_identity — set by an authentication interceptor. This is the recommended source: it cannot be forged by the client.

    Register the authentication interceptor before this one. The chain runs interceptors in registration order over one CallContext, so a limiter registered first reads an identity nothing has set yet and keys on the client address instead (steps 2 and 3), or on the shared anon key (step 4) where no address is recorded. Nothing rejects that ordering; it just stops being per-caller.

    JwtAuthInterceptor (the auth-jwt feature) records the validated issuer and sub; ApiKeyAuthInterceptor and BearerTokenAuthInterceptor record a label when built with with_labelled_keys / with_labelled_tokens, each qualified by its scheme (caller_id). The credential is never the key: caller keys reach a shared rate-limit table, logs and metrics, and a secret belongs in none of those.

  2. The client IP from x-forwarded-for, only when RateLimitConfig::trusted_proxy_hops is non-zero. The header is client-controlled, so by default (trusted_proxy_hops == 0) it is ignored entirely — otherwise a caller could evade the limit by forging a fresh address on every request. The hop count alone cannot tell a request through the proxies from one sent straight to the server, so RateLimitConfig::trusted_proxies names the proxies’ address ranges: when it is set, a connection from outside them is not believed and is keyed by its own address (step 3). A port in an entry (203.0.113.7:51234) is dropped.

  3. The connection’s peer address, when trusted_proxy_hops is zero (or trusted_proxies is set and the peer is not in it) and the binding records one (every built-in listener does: serve, Server, axum with ConnectInfo or PeerAddr, gRPC, WebSocket). An IPv4 address is one budget; an IPv6 address spends its /64’s, since one host is routinely given a whole /64. Behind trusted proxies the peer is the proxy, so it is not used. Until 2026-10-18 this step did not exist and every such caller shared step 4’s budget (the maintainer’s decision of that day).

  4. A shared anon key. The remaining callers (a forwarded chain shorter than trusted_proxy_hops, or a transport that records no peer) share one budget, which keeps the limit enforceable (fail-closed) at the cost of granularity.

Keys carry their kind as a prefix (id:, ip:, tenant:, anon), so a caller identity can never name another kind’s bucket.

Size RateLimitConfig::max_buckets for the distinct client addresses one window can see: once it is full of live buckets, a new address is charged to one shared overflow bucket (see below) instead of refused.

§Design

Uses a fixed-window counter per caller key. Windows are aligned to wall clock seconds. When a request exceeds the per-window limit, the before hook returns A2aError::rate_limited, with the time left in the window as the retry delay. A2A / JSON-RPC define no dedicated throttling code, so the code is an internal error (-32603), the one spec §3.3.2 gives for “rate limit exceeded”; what tells a client to back off is the binding’s status (HTTP 429 with Retry-After, gRPC RESOURCE_EXHAUSTED) and a google.rpc.RetryInfo detail on every binding.

The bucket map is bounded by RateLimitConfig::max_buckets. When the map is full and stale buckets cannot be evicted, new callers share one overflow bucket with the limit of any one caller, in addition to the bound (so the map holds at most max_buckets + 1), and RateLimitInterceptor::overflowed counts how many requests it took. Callers that already have a bucket are unaffected. Until 2026-11-01 new callers were refused outright: a set of max_buckets callers active in every window locked out every other caller for as long as they stayed active, and the refusal looked like an ordinary rate limit (audit H16); the overflow bucket trades fairness among the callers beyond the bound for never locking them all out, and its refusal says which it is.

For production deployments requiring sliding windows, distributed counters, or more sophisticated algorithms, implement a custom ServerInterceptor or use a reverse proxy (nginx, Envoy).

Structs§

InvalidTrustedProxy
Why a string is not a TrustedProxy.
PostgresRateLimitCounter
A RateLimitCounter backed by a PostgreSQL table.
RateLimitConfig
Configuration for RateLimitInterceptor.
RateLimitInterceptor
A fixed-window rate limiting ServerInterceptor.
TrustedProxy
An address range of reverse proxies this server trusts to say who the client is.

Enums§

ForwardedHeader
The header trusted reverse proxies record the client’s address in.

Constants§

DEFAULT_MAX_BUCKETS
Default cap on the number of tracked caller buckets.

Traits§

RateLimitCounter
A request counter every replica shares.