tower-rate-limiter
Keyed HTTP rate limiting middleware for Tower.
tower-rate-limiter lets an application decide who a request belongs to and which policy
charges it. The middleware owns the HTTP response flow without coupling the core to Axum, Tokio,
Redis, or a built-in identity policy.
Request
-> optional bypass
-> KeyExtractor
-> RateLimitPolicy::check
-> allow the ready inner service or return a response
When to use it
Use this crate when you need per-caller HTTP enforcement in a Tower service, for example:
- one quota per authenticated account or API client;
- an IP-based limit at an application boundary;
- route-specific policies composed as Tower Layers;
- fixed-window counters or GCRA quotas with process-local, Redis, or PostgreSQL state.
This is not a global concurrency limiter or a backpressure mechanism. The included policy is fixed window; other algorithms are expressed as explicit policies.
Design at a glance
| Concern | Application-facing seam | Included option |
|---|---|---|
| Caller identity | KeyExtractor | IpKeyExtractor, ClientIpKeyExtractor, TrustedProxyClientIpKeyExtractor |
| Charging algorithm | RateLimitPolicy | FixedWindow<S>, MemoryGcra, RedisGcra, PostgresGcra |
| Fixed-window storage | FixedWindowStore | MemoryStore, optional RedisStore |
| Smooth quota configuration | GcraQuota | optional Memory, Redis, and PostgreSQL GCRA policies |
| Error and rejection responses | ResponseFactory | DefaultResponseFactory |
The policy is always explicit. This makes the charging algorithm and its state-ownership boundary visible at layer construction instead of hiding process-local state behind a default singleton.
Cargo features
| Feature | Default | Adds |
|---|---|---|
memory | yes | Runtime-independent MemoryStore for FixedWindow |
axum | no | Axum ConnectInfo<SocketAddr> support in the built-in IP extractors |
redis | no | RedisStore backed by an existing multiplexed connection for FixedWindow |
redis-lua | no | Redis increment through Lua instead of MULTI/EXEC |
memory-gcra | no | MemoryGcra: process-local, governor-backed one-request GCRA |
redis-gcra | no | RedisGcra: shared one-request GCRA through an attributed Redis Lua artifact |
postgres-gcra | no | PostgresGcra: shared one-request GCRA through caller-installed PostgreSQL SQL; SQLx Tokio runtime |
runtime-tokio | no | Tokio-compatible Redis async runtime |
runtime-smol | no | Smol-compatible Redis async runtime |
tracing | no | Structured events for policy failures |
RedisStore needs an increment implementation (redis or redis-lua) together with one async
runtime (runtime-tokio or runtime-smol).
MemoryGcra needs memory-gcra only. RedisGcra needs redis-gcra together with one async
runtime and uses ordinary Redis, not a Redis module. PostgresGcra needs postgres-gcra; its SQLx
adapter is Tokio-only and requires an application-applied migration. See GCRA backends
for the shared contract and backend-specific deployment guides.
With default-features = false, the core remains usable with application-provided implementations
and does not pull in Axum, Redis, or an async runtime.
Start here
- Follow the Quick start to construct a Tower layer.
- Browse the complete examples for progressively richer integrations.
- Review Configuration before choosing policy names and failure mode.
- Read How it works for exact charging semantics.
- Use Axum and Redis, choose a GCRA backend, or implement Custom components.
- Check the Production guide before deploying behind a proxy or across replicas.
The API documentation is the complete type-level reference. The GitHub repository contains runnable examples.
Quick start
This guide builds a process-local limiter around a plain Tower service. It is the shortest path to the first working layer; the same layer can later be applied to an Axum router.
1. Add the dependency
The default feature enables the in-memory FixedWindowStore:
[dependencies]
tower-rate-limiter = "0.2"
The crate requires Rust 1.96 or newer.
2. Choose a client key
Define how a request becomes an application-owned client key and compose the Layer:
use std::{convert::Infallible, error::Error, future::ready, time::Duration};
use http::{Request, Response};
use tower::{Layer, service_fn};
use tower_rate_limiter::{FixedWindow, KeyExtractor, MemoryStore, RateLimitLayer};
#[derive(Clone, Copy)]
struct StaticClient;
impl KeyExtractor for StaticClient {
type Key = String;
fn extract<B>(&self, _request: &Request<B>) -> Result<Self::Key, tower_rate_limiter::RateLimitError> {
Ok(String::from("example-client"))
}
}
fn main() -> Result<(), Box<dyn Error>> {
dotenvy::dotenv().ok();
let limiter = RateLimitLayer::builder(StaticClient)
.policy_name("tower-example")
.with_policy(FixedWindow::new(MemoryStore::new(), 100, Duration::from_secs(60))?)
.build()?;
let _service = limiter.layer(service_fn(|_request: Request<()>| {
ready(Ok::<Response<()>, Infallible>(Response::new(())))
}));
println!("constructed a Tower MemoryStore rate limiter");
Ok(())
}
Run the complete example from the repository root:
cargo run --example tower_memory --features memory
The example uses one static key so its construction is easy to see. In a real service, extract a validated account ID, API-client ID, peer address, or another stable identity. Different callers must produce different keys; repeated requests from one caller must produce the same key.
3. Configure the policy deliberately
The minimal production-shaped builder is:
#![allow(unused)]
fn main() {
use std::time::Duration;
use tower_rate_limiter::{ConfigError, FixedWindow, IpKeyExtractor, MemoryStore, RateLimitLayer};
fn configure() -> Result<RateLimitLayer<IpKeyExtractor, FixedWindow<MemoryStore>>, ConfigError> {
let layer = RateLimitLayer::builder(IpKeyExtractor::new())
.policy_name("public-api")
.with_policy(FixedWindow::new(MemoryStore::new(), 100, Duration::from_secs(60))?)
.build()?;
Ok(layer)
}
}
build() validates layer configuration, including a non-empty policy name. FixedWindow::new(...)
validates its window, which must be at least one millisecond. The typed builder also prevents
build() until a policy has been supplied.
Builder defaults
| Setting | Default |
|---|---|
| Policy name | default-policy |
| Policy errors | Reject with 503 Service Unavailable |
| Response fields | IETF draft 11 |
A real application should set a stable policy name and select its policy deliberately. Layers that share a policy instance or backend state, policy name, and extracted key intentionally share usage.
What happens on each request
The middleware first extracts a key, scopes it with the policy name, then asks the selected policy to charge it. A policy failure consumes no quota metadata, while a charged request is not refunded based on the downstream response.
The first limit requests are allowed. Request limit + 1 is rate limited, and rejected requests
continue to increment usage without extending the active fixed window.
For a limit of 2, the sequence is:
| Request | FixedWindowUsage::used | Remaining | Result |
|---|---|---|---|
| 1 | 1 | 1 | inner service called |
| 2 | 2 | 0 | inner service called |
| 3 | 3 | 0 | 429 Too Many Requests |
The response from the second request has zero remaining quota but is still allowed. Exhaustion is
enforced only when used > limit.
Next steps
- Read How it works for the public extension points.
- Browse the complete examples for Tower, Axum, proxy handling, and Redis.
- Review every builder option in Configuration.
- Use Axum and Redis when the service needs framework or shared-store integration.
- Browse the repository’s
examples/for nested policies, proxy handling, and custom error responses.
Examples
The examples cover a framework-independent Tower service, fixed-window counters, and GCRA policies. Every page below embeds the complete source file used by the repository, so the documentation and the compiled example cannot drift independently.
| Example | What it demonstrates | Required features |
|---|---|---|
| Tower with MemoryStore | Minimal Tower Layer composition | memory |
| Axum with nested policies | ConnectInfo, global and route-scoped policies | axum,memory |
| Trusted proxy client IP | Peer-policy-gated client-IP extraction behind a trusted proxy | axum,memory |
| Axum with Redis | Shared fixed-window state, namespace, custom error responses | axum,redis,runtime-tokio |
| Axum with Memory GCRA | Process-local burst quota and application-owned periodic cleanup | axum,memory-gcra |
| Axum with Redis GCRA | Shared burst quota through ordinary Redis | axum,redis-gcra,runtime-tokio |
Run an example from the repository root with the command shown on its page. The Axum examples start
an HTTP server and keep running until interrupted. The Redis examples additionally require
REDIS_URL to reference a reachable Redis server.
These programs are intentionally small. They demonstrate the limiter boundary, not production authentication, proxy configuration, connection supervision, observability, or graceful shutdown. Review the Production guide before adapting them to a deployed service.
Tower with MemoryStore
This is the smallest complete example. It defines a KeyExtractor, creates an explicit
process-local FixedWindowStore, constructs a policy, and composes the resulting Layer around a
Tower service.
cargo run --example tower_memory --features memory
Complete source
use std::{convert::Infallible, error::Error, future::ready, time::Duration};
use http::{Request, Response};
use tower::{Layer, service_fn};
use tower_rate_limiter::{FixedWindow, KeyExtractor, MemoryStore, RateLimitLayer};
#[derive(Clone, Copy)]
struct StaticClient;
impl KeyExtractor for StaticClient {
type Key = String;
fn extract<B>(&self, _request: &Request<B>) -> Result<Self::Key, tower_rate_limiter::RateLimitError> {
Ok(String::from("example-client"))
}
}
fn main() -> Result<(), Box<dyn Error>> {
dotenvy::dotenv().ok();
let limiter = RateLimitLayer::builder(StaticClient)
.policy_name("tower-example")
.with_policy(FixedWindow::new(MemoryStore::new(), 100, Duration::from_secs(60))?)
.build()?;
let _service = limiter.layer(service_fn(|_request: Request<()>| {
ready(Ok::<Response<()>, Infallible>(Response::new(())))
}));
println!("constructed a Tower MemoryStore rate limiter");
Ok(())
}
The static key deliberately puts every request in the same bucket. Replace it with an application-owned caller identity in a real service.
Axum with nested policies
This example installs a global policy around the application and a stricter policy around the auth
routes. It also shows the ConnectInfo<SocketAddr> setup required by IpKeyExtractor and an IP
allowlist that bypasses both policies.
%%{init: {"themeVariables": {"fontSize": "10px"}, "flowchart": {"curve": "basis", "useMaxWidth": false, "padding": 5, "nodeSpacing": 15, "rankSpacing": 20}}}%%
flowchart LR
request["Request"] --> allowlisted{"Peer allowlisted?<br/>ConnectInfo IP"}
allowlisted -- "Yes" --> bypass["Bypass both Layers"]
bypass --> bypass_response["Handler response<br/>No rate-limit fields"]
allowlisted -- "No" --> global["global-limit<br/>Charges every route"]
global --> auth_route{"Under /auth?"}
auth_route -- "No" --> other["Other handler"]
other --> global_response["Handler response<br/>Global field only"]
auth_route -- "Yes" --> auth["auth-limit<br/>Charges auth routes"]
auth --> auth_handler["Auth handler"]
auth_handler --> auth_response["Handler response<br/>Auth and global fields"]
classDef entry fill:#ede9fe,stroke:#8b5cf6,color:#3b0764,stroke-width:2px
classDef decision fill:#fef3c7,stroke:#f59e0b,color:#78350f,stroke-width:1.5px
classDef policy fill:#dbeafe,stroke:#3b82f6,color:#172554,stroke-width:1.5px
classDef success fill:#dcfce7,stroke:#22c55e,color:#14532d,stroke-width:1.5px
classDef bypass fill:#f1f5f9,stroke:#64748b,color:#1e293b,stroke-width:1.5px
class request entry
class allowlisted,auth_route decision
class global,auth policy
class global_response,auth_response success
class bypass,bypass_response,other,auth_handler bypass
cargo run --example axum_memory --features axum,memory
The server listens on http://127.0.0.1:3000.
Complete source
use axum::{Router, extract::ConnectInfo, routing::get};
use http::Request;
use std::collections::HashSet;
use std::net::IpAddr;
use std::sync::Arc;
use std::{error::Error, net::SocketAddr, time::Duration};
use tower_rate_limiter::{FixedWindow, IpKeyExtractor, MemoryStore, RateLimitLayer};
// check if the request is from an allowlisted IP address
fn is_allowlisted(request: &Request<()>, allowlist: &HashSet<IpAddr>) -> bool {
request
.extensions()
.get::<ConnectInfo<SocketAddr>>()
.is_some_and(|addr| allowlist.contains(&addr.ip()))
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
let ip = "127.0.0.1".parse::<IpAddr>().unwrap();
let allowlist = Arc::new(HashSet::from([ip]));
let key_extractor = IpKeyExtractor::new();
let global_limiter = RateLimitLayer::builder(key_extractor)
.policy_name("global-limit")
.with_policy(FixedWindow::new(MemoryStore::new(), 10, Duration::from_secs(60))?)
.build()?;
let auth_allowlist = Arc::clone(&allowlist);
let auth_limiter = RateLimitLayer::builder(key_extractor)
.policy_name("auth-limit")
.skip(move |request| is_allowlisted(request, &auth_allowlist))
.with_policy(FixedWindow::new(MemoryStore::new(), 3, Duration::from_secs(60))?)
.build()?;
let auth_routes = Router::new()
.route("/login", get(|| async { "login" }))
.layer(auth_limiter);
let app = Router::new()
.route("/health", get(|| async { "ok" }))
.nest("/auth", auth_routes)
.layer(global_limiter);
let address: SocketAddr = "127.0.0.1:3000".parse()?;
let listener = tokio::net::TcpListener::bind(address).await?;
println!("listening on http://{address}");
// ANCHOR: serve
axum::serve(listener, app.into_make_service_with_connect_info::<SocketAddr>()).await?;
// ANCHOR_END: serve
Ok(())
}
An allowlisted request reaches the handler without quota metadata. A non-allowlisted request to
/auth/login can consume both policies; if the inner auth policy rejects it, the already-recorded
outer charge is not refunded.
Trusted proxy client IP
This example uses TrustedProxyClientIpKeyExtractor with an application-supplied peer policy. A
trusted proxy must remove or overwrite every supported client-IP header before forwarding the
request to the application.
cargo run --example trusted_proxy_client_ip --features axum,memory
The server listens on http://127.0.0.1:3001.
Complete source
use std::{
error::Error,
net::{IpAddr, SocketAddr},
time::Duration,
};
use axum::{Router, routing::get};
use tower_rate_limiter::{FixedWindow, MemoryStore, RateLimitLayer, TrustedProxyClientIpKeyExtractor};
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
// Replace this documentation address with application-owned proxy configuration. The proxy
// must remove or overwrite every supported client-IP Header, and ingress must prevent clients
// from bypassing it through an address accepted by this policy.
let trusted_proxy: IpAddr = "192.0.2.10".parse()?;
let key_extractor = TrustedProxyClientIpKeyExtractor::new(move |peer| peer == trusted_proxy);
let limiter = RateLimitLayer::builder(key_extractor)
.policy_name("client-ip-limit")
.with_policy(FixedWindow::new(MemoryStore::new(), 100, Duration::from_secs(60))?)
.build()?;
let app = Router::new().route("/health", get(|| async { "ok" })).layer(limiter);
let address: SocketAddr = "127.0.0.1:3001".parse()?;
let listener = tokio::net::TcpListener::bind(address).await?;
println!("listening on http://{address}");
axum::serve(listener, app.into_make_service_with_connect_info::<SocketAddr>()).await?;
Ok(())
}
The example’s documentation address is a placeholder; replace it with application configuration for
the actual proxy address or CIDR set. The policy checks the Axum ConnectInfo peer before the
extractor accepts Forwarded, X-Forwarded-For, X-Real-IP, or CF-Connecting-IP. Untrusted peers
use their socket IP even if they send those Headers. Missing peer information is rejected.
Parsing still does not authenticate Header contents. Every trusted proxy must sanitize all four supported Headers, and application ingress must prevent direct clients from connecting through an address accepted by the policy. The library does not load proxy configuration from environment variables.
Axum with Redis
This example shares usage through Redis, separates transport keys with a namespace, limits both peer addresses and user IDs, and maps application-specific identity failures to HTTP statuses.
Set REDIS_URL before running it:
export REDIS_URL=redis://127.0.0.1:6379/
cargo run --example axum_redis --no-default-features --features axum,redis,runtime-tokio
The server listens on http://127.0.0.1:3000.
Complete source
use std::{env, error::Error, net::SocketAddr, time::Duration};
use axum::{Router, routing::get};
use http::{Request, Response, StatusCode};
use tower_rate_limiter::{
FixedWindow, IpKeyExtractor, KeyExtractor, RateLimitError, RateLimitLayer, RedisStore, ResponseFactory,
ResponseReason,
};
/// Demo extractor: read a client key from `X-User-Id`.
/// Real apps should resolve identity in an earlier auth layer and read an extension instead.
#[derive(Clone, Copy)]
struct UserIdKeyExtractor;
impl KeyExtractor for UserIdKeyExtractor {
type Key = String;
fn extract<B>(&self, request: &Request<B>) -> Result<Self::Key, RateLimitError> {
let value = request
.headers()
.get("x-user-id")
.ok_or_else(missing_user_id)?
.to_str()
.map_err(|_| invalid_user_id())?;
if value.is_empty() {
return Err(missing_user_id());
}
Ok(value.to_owned())
}
}
fn missing_user_id() -> RateLimitError {
RateLimitError::Key(
String::from("missing_user_id"),
String::from("x-user-id header is required"),
)
}
fn invalid_user_id() -> RateLimitError {
RateLimitError::Key(
String::from("invalid_user_id"),
String::from("x-user-id must be valid UTF-8"),
)
}
/// Example-only HTTP mapping for the application-owned user identity extractor.
#[derive(Clone, Copy, Debug, Default)]
struct AuthResponseFactory;
impl<ReqBody, ResBody> ResponseFactory<ReqBody, ResBody> for AuthResponseFactory
where
ResBody: Default,
{
fn build(&self, _request: Request<ReqBody>, reason: ResponseReason) -> Response<ResBody> {
let status = match &reason {
ResponseReason::Error(RateLimitError::Key(code, _)) if code == "missing_user_id" => {
StatusCode::UNAUTHORIZED
},
ResponseReason::Error(RateLimitError::Key(code, _)) if code == "invalid_user_id" => StatusCode::BAD_REQUEST,
_ => reason.status_code(),
};
let mut response = Response::new(ResBody::default());
*response.status_mut() = status;
response
}
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
dotenvy::dotenv().ok();
let redis_url = env::var("REDIS_URL").expect("REDIS_URL must be set");
let client = redis::Client::open(redis_url).expect("Failed to open Redis client");
let connection = client.get_multiplexed_async_connection().await?;
let store = RedisStore::new(connection).with_namespace("axum-redis");
let global_limiter = RateLimitLayer::builder(IpKeyExtractor::new())
.policy_name("global-limit")
.with_key_encoder(|k| k.to_string())
.with_policy(FixedWindow::new(store.clone(), 10, Duration::from_secs(60))?)
.build()?;
let user_limiter = RateLimitLayer::builder(UserIdKeyExtractor)
.policy_name("user-limit")
.with_key_encoder(|k| k.to_string())
.response_factory(AuthResponseFactory)
.with_policy(FixedWindow::new(store, 3, Duration::from_secs(60))?)
.build()?;
let auth_routes = Router::new()
.route("/login", get(|| async { "login" }))
.merge(Router::new().route("/me", get(|| async { "me" })).layer(user_limiter));
let app = Router::new()
.route("/health", get(|| async { "ok" }))
.nest("/auth", auth_routes)
.layer(global_limiter);
let address: SocketAddr = "127.0.0.1:3000".parse()?;
let listener = tokio::net::TcpListener::bind(address).await?;
println!("listening on http://{address}");
axum::serve(listener, app.into_make_service_with_connect_info::<SocketAddr>()).await?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn missing_user_id_is_unauthorized() {
let response: Response<()> =
AuthResponseFactory.build(Request::new(()), ResponseReason::Error(missing_user_id()));
assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
}
#[test]
fn invalid_user_id_is_bad_request() {
let response: Response<()> =
AuthResponseFactory.build(Request::new(()), ResponseReason::Error(invalid_user_id()));
assert_eq!(response.status(), StatusCode::BAD_REQUEST);
}
#[test]
fn unrelated_key_failure_keeps_default_server_error() {
let response: Response<()> = AuthResponseFactory.build(
Request::new(()),
ResponseReason::Error(RateLimitError::Key(
String::from("socket_ip_unavailable"),
String::from("missing socket address"),
)),
);
assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
}
}
The example uses Tokio because Axum runs on Tokio. RedisStore itself also supports Smol when
redis (or redis-lua) is combined with runtime-smol. The example owns connection creation,
while RedisStore owns only atomic fixed-window usage. A production application should
additionally define connection recovery, timeouts, shutdown, and observability.
Axum with Memory GCRA
This server allows a fresh peer IP to send three requests immediately, then replenishes one request
every six seconds (10 requests per minute). Additional requests receive 429 with Retry-After.
cargo run --example axum_memory_gcra --no-default-features --features axum,memory-gcra
The server listens on http://127.0.0.1:3000/. For a fresh key, four immediate requests demonstrate
the burst and rejection:
for attempt in 1 2 3 4; do curl -i http://127.0.0.1:3000/; done
The application schedules prune_inactive_keys() every 60 seconds on a clone of the shared policy.
The library starts no cleanup task. Pruning removes inactive keys and does not impose a hard memory
limit; choose the interval and key-space budget for your workload. State is local to this process.
Complete source
use std::{error::Error, net::SocketAddr, time::Duration};
use axum::{Router, routing::get};
use tower_rate_limiter::{ConfigError, GcraQuota, IpKeyExtractor, MemoryGcra, RateLimitLayer};
fn app(policy: MemoryGcra) -> Result<Router, ConfigError> {
let limiter = RateLimitLayer::builder(IpKeyExtractor::new())
.policy_name("public-api")
.with_policy(policy)
.build()?;
Ok(Router::new().route("/", get(|| async { "hello" })).layer(limiter))
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
let quota = GcraQuota::new(10, Duration::from_secs(60), 3)?;
let policy = MemoryGcra::new(quota);
let app = app(policy.clone())?;
let address: SocketAddr = "127.0.0.1:3000".parse()?;
let listener = tokio::net::TcpListener::bind(address).await?;
// The application owns cleanup; clones share the same keyed state.
let cleanup = tokio::spawn(async move {
let mut interval = tokio::time::interval(Duration::from_secs(60));
loop {
interval.tick().await;
policy.prune_inactive_keys();
}
});
println!("listening on http://{address}");
let result = axum::serve(listener, app.into_make_service_with_connect_info::<SocketAddr>()).await;
cleanup.abort();
result?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use axum::{body::Body, extract::ConnectInfo};
use http::{Request, StatusCode};
use tower::ServiceExt;
#[tokio::test]
async fn peer_ip_is_limited_and_receives_retry_after() {
let quota = GcraQuota::new(1, Duration::from_secs(60), 1).expect("valid quota");
let app = app(MemoryGcra::new(quota)).expect("valid app");
let request = || {
let mut request = Request::new(Body::empty());
request
.extensions_mut()
.insert(ConnectInfo(SocketAddr::from(([127, 0, 0, 1], 12345))));
request
};
let allowed = app.clone().oneshot(request()).await.expect("allowed response");
assert_eq!(allowed.status(), StatusCode::OK);
let rejected = app.oneshot(request()).await.expect("rejected response");
assert_eq!(rejected.status(), StatusCode::TOO_MANY_REQUESTS);
assert!(
rejected.headers()["retry-after"]
.to_str()
.expect("valid retry header")
.parse::<u64>()
.expect("retry seconds")
> 0
);
}
}
Axum with Redis GCRA
This server enforces the same quota as the Memory GCRA example: three requests immediately per fresh peer IP, then one request replenished every six seconds.
Set REDIS_URL to a reachable Redis server with scripting enabled:
export REDIS_URL=redis://127.0.0.1:6379/
cargo run --example axum_redis_gcra --no-default-features --features axum,redis-gcra,runtime-tokio
The server listens on http://127.0.0.1:3000/. For a fresh key, the fourth immediate request
receives 429 with Retry-After:
for attempt in 1 2 3 4; do curl -i http://127.0.0.1:3000/; done
Redis keeps quota state across application restarts. Replicas using the same namespace, policy name, client key and quota share that state. The example owns connection creation; see the Redis GCRA guide for permissions and deployment limits.
Complete source
use std::{env, error::Error, net::SocketAddr, time::Duration};
use axum::{Router, routing::get};
use tower_rate_limiter::{ConfigError, GcraQuota, IpKeyExtractor, RateLimitLayer, RedisGcra};
fn app(policy: RedisGcra) -> Result<Router, ConfigError> {
let limiter = RateLimitLayer::builder(IpKeyExtractor::new())
.policy_name("public-api")
.with_policy(policy)
.build()?;
Ok(Router::new().route("/", get(|| async { "hello" })).layer(limiter))
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
dotenvy::dotenv().ok();
let client = redis::Client::open(env::var("REDIS_URL")?)?;
let connection = client.get_multiplexed_async_connection().await?;
let quota = GcraQuota::new(10, Duration::from_secs(60), 3)?;
let policy = RedisGcra::new(connection, quota).with_namespace("axum-redis-gcra");
let app = app(policy)?;
let address: SocketAddr = "127.0.0.1:3000".parse()?;
let listener = tokio::net::TcpListener::bind(address).await?;
println!("listening on http://{address}");
axum::serve(listener, app.into_make_service_with_connect_info::<SocketAddr>()).await?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use axum::{body::Body, extract::ConnectInfo};
use http::{Request, StatusCode};
use tower::ServiceExt;
#[tokio::test]
async fn peer_ip_is_limited_and_receives_retry_after() {
let client = redis::Client::open(env::var("REDIS_URL").expect("test Redis URL")).expect("valid URL");
let connection = client
.get_multiplexed_async_connection()
.await
.expect("connect to test Redis");
let quota = GcraQuota::new(1, Duration::from_secs(60), 1).expect("valid quota");
let policy =
RedisGcra::new(connection, quota).with_namespace(format!("axum-redis-gcra-test:{}", std::process::id()));
let app = app(policy).expect("valid app");
let request = || {
let mut request = Request::new(Body::empty());
request
.extensions_mut()
.insert(ConnectInfo(SocketAddr::from(([127, 0, 0, 1], 12345))));
request
};
let allowed = app.clone().oneshot(request()).await.expect("allowed response");
assert_eq!(allowed.status(), StatusCode::OK);
let rejected = app.oneshot(request()).await.expect("rejected response");
assert_eq!(rejected.status(), StatusCode::TOO_MANY_REQUESTS);
assert!(
rejected.headers()["retry-after"]
.to_str()
.expect("valid retry header")
.parse::<u64>()
.expect("retry seconds")
> 0
);
}
}
Configuration
RateLimitLayer::builder(...) uses concrete generic types for the extractor, policy, and response
factory. Most configuration is shared immutable state, so cloning a finished Layer is cheap and
produces services with the same policy.
Builder reference
| Method | Default | Purpose |
|---|---|---|
with_policy(policy) | none | Select the required RateLimitPolicy |
policy_name(name) | default-policy | Set the stable policy and key-scoping identity |
response_factory(factory) | empty default responses | Customize middleware-produced responses |
policy_failure_mode(mode) | Reject | Reject or fail open after a policy failure |
policy_failure_tracing_level(level) | WARN | Select the policy-failure event level with tracing enabled |
rate_limit_fields(fields) | Draft11 | Select or disable response fields |
with_key_encoder(fn) | raw scoped key | Transform the complete key before policy charging |
skip(predicate) | never bypass | Exempt trusted requests before charging |
Calling with_policy(...) or response_factory(...) replaces the previously selected component
of that kind.
Policy identity and state sharing
Before calling the policy, the middleware scopes the extracted client key with the policy name. Layers intentionally share state only when all of these match:
- the same policy instance or logically shared policy backend;
- the same policy name;
- the same extracted client key;
- equivalent key encoding.
Treat a policy name as a stable identifier, not display text. It must be non-empty visible ASCII;
the middleware escapes " and \\ when representing it as a Draft 11 Structured Fields string.
When policies use a backend, its own key format and namespace remain an implementation detail.
Policy failure mode
PolicyFailureMode::Reject is the default. It returns the response selected by ResponseFactory
without calling the inner service.
PolicyFailureMode::Allow favors availability. When a policy returns an error, the inner service
is called without RateLimitContext or rate-limit fields because no trustworthy Decision exists.
Client-key failures never fail open.
Enable the tracing Cargo feature to emit an event for every policy failure. Events default to
WARN; configure a policy with .policy_failure_tracing_level(tracing::Level::ERROR) when another
level is appropriate. The stable target is tower_rate_limiter::policy; fields contain
policy_name, event=policy_failure, failure_mode, and error_code. Events deliberately omit
the Client Key and diagnostic error message. The library emits events through the application’s
subscriber and never installs one.
Enable the feature and add tracing as a direct application dependency when configuring a custom
event level:
[dependencies]
tower-rate-limiter = { version = "0.2", features = ["tracing"] }
tracing = "0.1"
The feature enables policy-failure events inside tower-rate-limiter; the direct tracing
dependency lets application code name values such as tracing::Level::ERROR in the builder call.
%%{init: {"themeVariables": {"fontSize": "10px"}, "flowchart": {"curve": "basis", "useMaxWidth": false, "padding": 5, "nodeSpacing": 16, "rankSpacing": 20}}}%%
flowchart TD
policy["RateLimitPolicy::check"] --> result{"Decision or error?"}
result -- "Decision" --> evaluate["Allow or rate limit"]
result -- "Error" --> mode{"PolicyFailureMode"}
mode -- "Reject · Error(Policy)" --> factory["ResponseFactory"]
mode -- "Allow" --> allow["Call inner service<br/>without quota metadata"]
factory --> reject["Middleware response<br/>503 by default"]
classDef input fill:#ede9fe,stroke:#8b5cf6,color:#3b0764,stroke-width:2px
classDef decision fill:#fef3c7,stroke:#f59e0b,color:#78350f,stroke-width:1.5px
classDef success fill:#dcfce7,stroke:#22c55e,color:#14532d,stroke-width:1.5px
classDef danger fill:#ffe4e6,stroke:#f43f5e,color:#881337,stroke-width:1.5px
classDef process fill:#dbeafe,stroke:#3b82f6,color:#172554,stroke-width:1.5px
class policy input
class result,mode decision
class evaluate,allow success
class factory process
class reject danger
Choose this per policy based on the cost of under-enforcement:
| Policy type | Typical starting point |
|---|---|
| Abuse protection on a public read endpoint | Allow may be acceptable |
| Login, expensive work, paid quota, or write protection | Prefer Reject |
This table is operational guidance, not an automatic security policy.
Key encoding
By default, the complete scoped key is passed to the policy unchanged. Use
.with_key_encoder(...) when raw identities must not reach a policy backend or when it needs a
constrained representation.
The callback runs synchronously in the middleware future. It must be deterministic, collision-resistant for the application’s key space, non-blocking, free of I/O, and non-panicking. The crate does not choose a hashing algorithm or detect collisions.
Changing the encoder changes Policy Decision identity. Roll it out as a policy migration: old state will not automatically merge into the new representation.
Bypass
.skip(...) receives &Request<()>, which contains the request head and extensions but no body.
When it returns true, the request reaches the inner service without key extraction, policy
charging, rate-limit fields, or context.
The predicate is synchronous. Use only cheap, trusted request state such as an authentication result or deployment-validated peer extension. Do not treat an arbitrary client-supplied header as an allowlist signal.
How it works
tower-rate-limiter separates rate-limit policy from application concerns through three narrow
interfaces.
The request lifecycle
For each request presented to the Layer, the service follows this order:
- Evaluate the optional bypass predicate.
- Extract the client key synchronously.
- Derive the policy-scoped key and apply optional key encoding.
- Ask the selected policy to charge that key.
- Evaluate the returned Decision.
- Call the already-ready inner service or build an immediate response.
%%{init: {"themeVariables": {"fontSize": "10px"}, "flowchart": {"curve": "basis", "useMaxWidth": false, "padding": 5, "nodeSpacing": 14, "rankSpacing": 18}}}%%
flowchart TD
request["Request"] --> skip{"Skip predicate matches?"}
skip -- "Yes" --> skipped_inner["Inner service"]
skipped_inner --> skipped_response["Inner response<br/>No rate-limit fields"]
skip -- "No" --> key["KeyExtractor"]
key -- "Key error" --> response_factory["ResponseFactory"]
key --> policy["RateLimitPolicy::check"]
policy -- "Policy error" --> failure_mode{"Policy failure mode"}
policy --> decision{"Allowed or rate limited?"}
failure_mode -- "Allow" --> fail_open_inner["Inner service<br/>No quota metadata"]
fail_open_inner --> fail_open_response["Inner response<br/>No rate-limit fields"]
failure_mode -- "Reject" --> response_factory
decision -- "Rate limited" --> response_factory
response_factory --> middleware_response["Middleware-produced response<br/>429, 500, or 503 by default"]
decision -- "Allowed" --> context["Add RateLimitContext<br/>to the request"]
context --> inner["Inner service"]
inner --> response["Inner response<br/>Rate-limit fields appended"]
classDef entry fill:#ede9fe,stroke:#8b5cf6,color:#3b0764,stroke-width:2px
classDef process fill:#dbeafe,stroke:#3b82f6,color:#172554,stroke-width:1.5px
classDef decision fill:#fef3c7,stroke:#f59e0b,color:#78350f,stroke-width:1.5px
classDef success fill:#dcfce7,stroke:#22c55e,color:#14532d,stroke-width:1.5px
classDef neutral fill:#f1f5f9,stroke:#64748b,color:#1e293b,stroke-width:1.5px
classDef danger fill:#ffe4e6,stroke:#f43f5e,color:#881337,stroke-width:1.5px
class request entry
class key,policy,response_factory,context,inner process
class skip,failure_mode,decision decision
class response success
class skipped_inner,skipped_response,fail_open_inner,fail_open_response neutral
class middleware_response danger
Charging happens before the downstream call. The middleware does not refund quota when a handler returns an error, because the request already consumed application work.
Client key extraction
KeyExtractor synchronously derives an application-owned client key from the request. The crate
does not decide whether callers are identified by an account, credential owner, peer address, or
another value.
IpKeyExtractor reads only a peer SocketAddr extension and returns its IpAddr; it never trusts
an HTTP field. ClientIpKeyExtractor uses http-extract to check Forwarded, X-Forwarded-For,
X-Real-IP, and CF-Connecting-IP, in that order, then falls back to the peer address. These
headers are raw assertions rather than authenticated identities. The application deployment must
ensure a trusted proxy removes or overwrites every accepted header before selecting that adapter
for security-sensitive rate limiting.
TrustedProxyClientIpKeyExtractor makes the transport trust decision per request. It first requires
the socket peer, then calls an application-supplied synchronous Fn(IpAddr) -> bool policy. An
untrusted peer’s forwarding Headers are ignored and the peer becomes the key. A trusted peer uses
the same strict Header selection as ClientIpKeyExtractor and falls back to the peer only when all
supported Headers are absent. A malformed first-present Header still fails closed. The crate does
not infer trust from environment variables or Header contents.
Policy charging
RateLimitPolicy owns the algorithm and quota. It asynchronously charges a complete scoped key and
returns a Decision: Allowed or RateLimited, together with the advertised limit, window,
remaining capacity, reset duration, and—when rejected—the earliest retry duration.
Policy implementations must return a normal rate-limited Decision when quota is exhausted. They
reserve RateLimitError::Policy for cases where they cannot produce a trustworthy Decision. Policy
failures reject by default. Applications that explicitly prefer availability can select
PolicyFailureMode::Allow; the inner service is then called without claiming quota metadata.
Fixed-window behavior
FixedWindow<S> is the included policy. It delegates atomic fixed-window usage to a
FixedWindowStore. The first increment starts a window. Later increments update usage but do not
move its end time. After expiry, the next charged request starts a new window.
The first limit charged requests are allowed. Request limit + 1 is rejected, but still
increments usage without extending the window. This behavior is predictable and inexpensive, but
traffic may burst around a boundary: a caller can use the end of one window and the beginning of the
next in quick succession.
GCRA behavior
The optional MemoryGcra, RedisGcra, and PostgresGcra policies use the generic cell rate
algorithm (GCRA): a quota replenishes continuously, while burst is the total capacity a fresh
key can spend immediately. Each currently has a fixed request cost of one. GcraQuota rounds the
emission interval up to whole microseconds so the built-in adapters do not exceed the requested
long-term rate.
The policies return the same Decision meanings but do not promise identical timing fields: Memory
uses a process clock, Redis server time, and PostgreSQL database time after row locking. Choose
Memory only for process-local enforcement; Redis and PostgreSQL share state across replicas. See
GCRA backends for the common contract and its backend-specific guides.
Sliding windows, token buckets, weighted requests, and refunds are not included in the current release.
Responses and context
ResponseFactory maps middleware outcomes to the application’s response body, status, headers, and
logging policy. The default factory returns:
| Outcome | Status |
|---|---|
| Rate limited | 429 Too Many Requests |
| Client key failure | 500 Internal Server Error |
| Policy failure | 503 Service Unavailable |
Allowed requests receive RateLimitContext in their extensions. Its policy entries contain the
policy name and Decision. Use decision.remaining() for remaining capacity. The context is absent
on bypass and fail-open paths; downstream code should treat absence as “no trustworthy limiter
metadata,” not as “unlimited.”
Nested Layers append policies instead of overwriting context or response fields. See Rate limit fields for the wire representation.
Request bypass
RateLimitBuilder::skip accepts a synchronous predicate over the request head. A bypassed request
reaches the inner service without key extraction, policy charging, response fields, or
RateLimitContext.
Only use application-trusted headers or extensions in this predicate. Prefer a validated identity extension over matching a raw credential.
Layer scope and composition
Where the Layer is installed determines which routes enter the policy. Use separate Layers for separate route scopes, and give semantically different policies distinct names.
Nested limiters charge independently. If an outer policy allows the request, an inner policy may still reject it; the outer charge is not refunded. On allowed requests, context entries and response fields are appended in composition order.
Tower readiness
RateLimit implements Service when its wrapped Service implements Clone. During
RateLimit::call, the middleware replaces the wrapped Service with a clone and moves the exact
instance observed ready into ResponseFuture. Key extraction begins in the outer call, policy
charging runs while the response Future is polled, and Inner::call runs only
after the request is allowed. This preserves Tower’s readiness contract while leaving the middleware
ready for a later request. Application code should still apply timeouts and load-shedding at the
appropriate service boundaries.
Rate limit fields
Allowed and rate-limited responses can advertise quota state using RateLimit-Policy and
RateLimit. Rate-limited responses also include Retry-After even when the other fields are
disabled.
Durations are rounded up to whole seconds. Remaining quota uses saturating subtraction, so it stays at zero after a caller exceeds the limit.
Draft 11 (default)
For a policy named public-api, a quota of 100, and a 60-second window:
RateLimit-Policy: "public-api";q=100;w=60
RateLimit: "public-api";r=99;t=60
qis the configured request quota.wis the policy’s advertised window duration.ris the quota remaining after the current request.tis the policy-reported time until reset.
The optional quota-unit (qu) and partition-key (pk) parameters are not emitted. Omitting qu
means the quota unit is requests.
Draft 7
Select the older representation explicitly:
#![allow(unused)]
fn main() {
use tower_rate_limiter::{IpKeyExtractor, RateLimitBuilder, RateLimitFields, RateLimitLayer};
fn configure() -> RateLimitBuilder<IpKeyExtractor> {
RateLimitLayer::builder(IpKeyExtractor::new())
.rate_limit_fields(RateLimitFields::Draft7)
}
}
It produces fields shaped like:
RateLimit-Policy: 100;w=60
RateLimit: limit=100, remaining=99, reset=60
Draft 7 does not carry the configured policy name in either field.
Disabled
Use RateLimitFields::Disabled when another gateway owns these headers or clients must not receive
quota metadata. A rejected request still receives:
Retry-After: 42
Retry-After reflects the policy’s earliest retry duration rounded up to seconds.
Nested policies
Nested Layers append their values rather than replacing an existing field. Clients should parse the fields as structured lists and must not assume there is exactly one policy.
The fields are a client-facing projection of current state, not a substitute for server-side
enforcement. A custom ResponseFactory controls the response body and status, while the middleware
adds the configured rate-limit fields afterward.
Custom components
The core has four application-facing seams. Implement only the ones whose behavior belongs to your
application; FixedWindow, the default response factory, and the included fixed-window stores cover
common cases.
Custom client identity
KeyExtractor is synchronous and body-generic:
use http::Request;
use tower_rate_limiter::{KeyExtractor, RateLimitError};
#[derive(Clone)]
struct AuthenticatedAccount {
id: String,
}
#[derive(Clone, Copy)]
struct AccountKey;
impl KeyExtractor for AccountKey {
type Key = String;
fn extract<B>(&self, request: &Request<B>) -> Result<Self::Key, RateLimitError> {
request
.extensions()
.get::<AuthenticatedAccount>()
.map(|account| account.id.clone())
.ok_or_else(|| RateLimitError::Key(
"account_missing".into(),
"authenticated account extension is missing".into(),
))
}
}
The key only needs to implement Display. Prefer a stable, non-secret identifier. Authentication
and credential validation should happen in an earlier application layer. Normalize identity once
at this boundary rather than composing several extractors.
Custom policy
RateLimitPolicy owns one rate-limit algorithm and quota. It receives a complete policy-scoped key
and returns an asynchronous Decision:
use std::future::{Ready, ready};
use std::time::Duration;
use tower_rate_limiter::{Decision, RateLimitError, RateLimitPolicy};
#[derive(Clone, Copy)]
struct AlwaysAllow;
impl RateLimitPolicy for AlwaysAllow {
type Future = Ready<Result<Decision, RateLimitError>>;
fn check(&self, _key: String) -> Self::Future {
ready(Ok(Decision::allowed(100, Duration::from_secs(60), 99, Duration::from_secs(60))))
}
}
Return a normal Decision::rate_limited(...) when the quota is exhausted. Reserve
RateLimitError::Policy(code, message) for a backend or algorithm failure that prevents a
trustworthy Decision. Such errors follow the configured PolicyFailureMode.
Custom fixed-window storage
FixedWindowStore is the storage seam used by FixedWindow. A store must atomically increment the
complete opaque key and preserve fixed-window semantics:
use std::{future::Future, time::Duration};
use tower_rate_limiter::{FixedWindowStore, FixedWindowUsage, RateLimitError};
trait StoreShape: Clone {
type Future: Future<Output = Result<FixedWindowUsage, RateLimitError>>;
fn increment(&self, key: &str, window: Duration) -> Self::Future;
}
The illustrative StoreShape mirrors tower_rate_limiter::FixedWindowStore. An implementation
must:
- make increment and first-window creation one atomic operation;
- start expiry only on the first increment;
- avoid extending expiry on later or rejected requests;
- return usage including the current increment;
- return
used >= 1and the remainingreset_afterduration; - make clones of one store value observe the same counters;
- map backend failures to
RateLimitError::Policy(code, message).
The store receives a policy-scoped key. It must treat that string as opaque and must not reconstruct client or policy identity from its format.
FixedWindowStore requires Clone because FixedWindow clones it into each policy check. It
deliberately has no unconditional Send + Sync + 'static supertraits, and its Future is not
universally required to be Send + 'static. This keeps the core usable by local Tower executors.
Add framework-specific bounds where the policy enters that framework.
When a concrete policy is passed directly to Axum, no extra annotations are normally needed. Rust
derives whether the resulting ResponseFuture is Send + 'static from its concrete fields and
futures, so built-in policies and custom policies whose futures already satisfy those properties
compile directly:
let limiter = RateLimitLayer::builder(IpKeyExtractor::new())
.with_policy(MyPolicy::new())
.build()?;
let app = Router::new().layer(limiter);
Explicit bounds become necessary when the integration is hidden behind a generic function. Axum
requires the final middleware Future to be Send + 'static, but P: RateLimitPolicy alone
intentionally does not promise that. State the framework requirement on the generic integration
point:
fn add_rate_limit<P>(router: Router, policy: P) -> Result<Router, ConfigError>
where
P: RateLimitPolicy + Send + Sync + 'static,
P::Future: Send + 'static,
{
let limiter = RateLimitLayer::builder(IpKeyExtractor::new())
.with_policy(policy)
.build()?;
Ok(router.layer(limiter))
}
The same rule applies when a helper accepts fixed-window storage and constructs FixedWindow
itself: state S: FixedWindowStore + Send + Sync + 'static and S::Future: Send + 'static on the
integration point. The compiler reports the specific future or captured value that prevents the
composed ResponseFuture from being Send.
Custom responses
ResponseFactory receives the original request and a structured reason. ReqBody and ResBody
are independent, matching Tower services whose request and response body types differ:
use http::{Request, Response};
use tower_rate_limiter::{ResponseFactory, ResponseReason};
#[derive(Clone, Copy)]
struct ApiResponseFactory;
impl<ReqBody, ResBody: Default> ResponseFactory<ReqBody, ResBody> for ApiResponseFactory {
fn build(&self, _request: Request<ReqBody>, reason: ResponseReason) -> Response<ResBody> {
let mut response = Response::new(ResBody::default());
*response.status_mut() = reason.status_code();
response
}
}
Match ResponseReason::RateLimited(policy) to describe quota exhaustion. policy carries the
stable policy name and Decision. Match ResponseReason::Error(...) to map client-key and policy
failures. The middleware adds RateLimit, RateLimit-Policy, and Retry-After after the factory
returns where applicable.
Avoid placing secrets, raw credentials, or connection details in stable error codes, diagnostic messages, response bodies, or logs.
Axum and Redis
The core stays independent of a web framework and async runtime. Optional features provide focused
adapters without taking ownership of application lifecycle or trust policy. The axum feature
only enables Axum-aware extraction in http-extract; this crate has no direct Axum dependency, and
applications still depend on a compatible Axum version themselves.
Axum requires every installed middleware response Future to be Send + 'static. Concrete limiter
components are checked automatically when a Layer is passed directly to Router::layer, so the
built-in policies normally require no annotations. A generic helper must state its runtime bounds,
such as P: RateLimitPolicy + Send + Sync + 'static and P::Future: Send + 'static; the core
policy interface does not impose them because local Tower executors may use non-Send futures. See
Custom components for concrete and generic examples.
Axum
Enable Axum integration together with the default in-memory fixed-window store:
[dependencies]
tower-rate-limiter = { version = "0.2", features = ["axum", "memory"] }
IpKeyExtractor reads Axum’s ConnectInfo<SocketAddr> as the peer address.
ClientIpKeyExtractor uses the same value as its fallback when no supported client-IP header is
present. TrustedProxyClientIpKeyExtractor requires that peer address so an application-supplied
synchronous policy can decide whether forwarding Headers are eligible. The server must supply
connection information when serving the router:
axum::serve(listener, app.into_make_service_with_connect_info::<SocketAddr>()).await?;
See Axum with nested policies for the complete source.
If ConnectInfo is missing, IpKeyExtractor returns socket_ip_unavailable. When both a client-IP
header and ConnectInfo are missing, ClientIpKeyExtractor returns client_ip_unavailable.
TrustedProxyClientIpKeyExtractor also returns socket_ip_unavailable whenever ConnectInfo is
missing, even if a forwarding Header is present. Enabling the feature alone is not enough; the server
construction shown above inserts the peer address.
ClientIpKeyExtractor checks Forwarded, X-Forwarded-For, X-Real-IP, and CF-Connecting-IP in
that order. These are untrusted inputs: parsing does not authenticate their sender. Only select
this adapter when a trusted proxy removes or overwrites every accepted header. A malformed
first-present source returns invalid_client_ip instead of falling back to another header or the
peer address.
TrustedProxyClientIpKeyExtractor::new takes a Fn(IpAddr) -> bool policy. An untrusted peer’s
Headers are ignored without parsing and its peer IP becomes the key. A trusted peer uses the same
Header order and strict parsing as ClientIpKeyExtractor, with the peer as fallback. Prefer this
extractor when trusted proxies and direct clients can reach the same application listener. The crate
does not read environment variables or define proxy addresses; the application owns that policy.
Use IpKeyExtractor when only the socket peer should be trusted.
The trusted proxy client IP example shows the trust-policy extractor in an Axum application. A trusted peer must sanitize every supported header, and network policy must prevent direct clients from reaching the application through a trusted proxy address. Select exactly one IP extractor at the middleware boundary so every request has one normalized identity path.
Redis
Enable Redis when multiple processes need to share usage:
[dependencies]
tower-rate-limiter = { version = "0.2", default-features = false, features = ["redis", "runtime-tokio"] }
RedisStore implements FixedWindowStore and accepts an already established
redis::aio::MultiplexedConnection. Construct FixedWindow with it. The application continues to
own URL parsing, connection setup, reconnection strategy, and shutdown.
The redis feature uses one MULTI/EXEC transaction to initialize the counter, increment it, and
read its TTL. Use redis-lua in place of redis to perform the same fixed-window operation with
Lua. Either implementation must be combined with runtime-tokio or runtime-smol. A missing or
non-positive TTL is surfaced as a policy error rather than repaired implicitly.
Redis expiry uses whole milliseconds. Sub-millisecond portions are truncated, and a window shorter
than one millisecond is rejected. The in-memory store retains Duration/Instant precision.
Redis adds an rl: transport marker and the optional namespace after it receives the scoped key.
Use a namespace to separate deployments or applications sharing one Redis database. Namespace is a
transport concern; use distinct policy names for distinct rate-limit policies.
See Axum with Redis for complete connection setup, namespacing, a shared fixed-window policy, and custom error responses.
GCRA policies
MemoryGcra, RedisGcra, and PostgresGcra use the same GcraQuota and Decision contract.
Use MemoryGcra with memory-gcra for one process; it has no runtime or external dependency.
Use PostgresGcra with postgres-gcra and a caller-owned SQLx Tokio PgPool after applying
migrations/postgres/0001_gcra.sql through the application’s migration runner. The remaining
example shows Redis-specific connection setup.
GcraQuota rounds its emission interval up to whole microseconds. Backend clocks and state engines
mean equivalent policies do not promise identical per-request timing fields. See GCRA backends
before choosing a shared state service.
Redis
RedisGcra is a separate shared policy for a continuously replenished rate. Enable
redis-gcra with a runtime feature (runtime-tokio or runtime-smol), construct it
from the same established MultiplexedConnection, and pass it to with_policy(...):
#![allow(unused)]
fn main() {
use std::time::Duration;
use tower_rate_limiter::{GcraQuota, GcraQuotaError, RedisGcra};
fn configure(connection: redis::aio::MultiplexedConnection) -> Result<RedisGcra, GcraQuotaError> {
let quota = GcraQuota::new(100, Duration::from_secs(60), 20)?;
let policy = RedisGcra::new(connection, quota).with_namespace("my-service");
Ok(policy)
}
}
burst is the total instantaneous capacity; this first version charges a cost of one per request.
The policy uses Redis server time and a Lua artifact, so it needs the Redis ACL commands described
in Redis GCRA. It is not a redis-cell or Redis Stack integration.
Choosing a fixed-window store
| Requirement | MemoryStore | RedisStore |
|---|---|---|
| Single process | yes | yes |
| Counters shared across replicas | no | yes |
| External service required | no | yes |
| Survives process restart | no | usually, subject to Redis persistence |
| Runtime dependency in the adapter | none | Tokio- or Smol-compatible Redis connection |
Cloning MemoryStore shares its in-process state. Creating separate MemoryStore::new() values
creates separate counter sets. With multiple application replicas, each in-memory store enforces
its own quota, so the effective aggregate allowance can grow with replica count.
Each cached entry expires with its fixed window. Moka treats the entry as absent after that point and eventually removes it through cache maintenance without a background task.
GCRA backends
GCRA (the generic cell rate algorithm) gives each client key a continuously replenished request
quota. It differs from a fixed window: capacity returns one request at a time rather than all at a
window boundary. FixedWindow remains available when that simpler boundary-based behavior is the
right fit.
The crate includes three GCRA policies:
| Policy | State location | Shared across replicas | Runtime / service |
|---|---|---|---|
MemoryGcra | process memory | no | none; governor |
RedisGcra | Redis | yes | Tokio or Smol Redis connection |
PostgresGcra | PostgreSQL | yes | SQLx Tokio PgPool and an installed migration |
Choose a backend according to where the authoritative state must live. Do not use MemoryGcra
when a limit must be global across independently running replicas. Redis and PostgreSQL make one
backend state transition per charge; their availability and latency are part of the request path.
Common quota and decision contract
Construct each policy from a GcraQuota:
#![allow(unused)]
fn main() {
use std::time::Duration;
use tower_rate_limiter::{GcraQuota, GcraQuotaError};
fn configure_quota() -> Result<GcraQuota, GcraQuotaError> {
GcraQuota::new(100, Duration::from_secs(60), 20)
}
}
raterequests replenish overperiod.burstis the total immediate capacity of a fresh key. It is not capacity added on top ofrate.- Each included adapter charges exactly one request. Weighted charges and refunds are not part of this API.
- The configured emission interval is rounded up to whole microseconds so quota quantization itself does not increase the configured rate. This does not remove backend arithmetic error: Redis retains the upstream Lua artifact’s floating-point behavior.
- A complete burst must replenish within one year. The constructor rejects longer windows.
All adapters produce RateLimitPolicy Decision values with the same meanings: an allowed result
contains the configured limit, advertised window, remaining capacity, and reset duration; a
rejection has zero remaining capacity plus an earliest retry_after. These values drive the
middleware’s RateLimit and Retry-After fields.
The contract describes quota and decision meanings, not identical admission or duration values at
every precision boundary. Memory uses its process clock, Redis uses TIME, and PostgreSQL captures
clock_timestamp() after acquiring a row lock. Network latency, elapsed time while producing a
response, and backend-specific rounding
can make individual reset_after or retry_after values differ slightly. Treat fields as pacing
guidance, not a distributed-clock comparison API. Redis can admit fewer or more requests than exact
GCRA arithmetic at very small intervals, including exceeding the configured burst. See the
Redis precision limits before choosing microsecond-scale quotas.
The shared backend tests cover burst = 1, a non-divisible rate/period, key isolation, clone-shared
state, rejection without extending the penalty, recovery after retry, and a full burst after an idle
window. They compare those behaviors and metadata bounds rather than exact duration equality
between independently clocked backends. Separate Redis tests characterize the pinned artifact at
1µs, 10µs, and 100µs recovery boundaries and record known floating-point burst deviations.
Identity, namespace, and versioning
The layer scopes the extracted client key with policy_name before calling the policy. Give every
semantically distinct quota a stable policy name. RedisGcra and PostgresGcra additionally offer
.with_namespace(...) to separate applications or deployments that share the same backend.
All replicas that charge the same backend state identity must use the same effective quota. A quota
change changes the interpretation of stored theoretical-arrival-time state. During a rollout,
version the policy_name or backend namespace (for example, public-api-v2 or service-v2) so
old and new instances cannot reinterpret the same stored state with different emission intervals.
Allow the old state to expire before retiring its namespace.
Backend guides
- Memory GCRA covers local governor state and its process boundary.
- Redis GCRA covers the pinned upstream Lua artifact, Redis ACLs, and topology limits.
- PostgreSQL GCRA covers applying the migration, permissions, and expired-state cleanup.
Failure behavior
MemoryGcra normally has no remote dependency. Redis and PostgreSQL errors are policy failures:
PolicyFailureMode::Reject is the default and returns the configured middleware rejection
(normally 503); PolicyFailureMode::Allow must be selected explicitly and passes the request to
the inner service without rate-limit fields or context. In either mode, configure dependency
timeouts and monitor backend latency and failures.
Memory GCRA
MemoryGcra is a process-local GCRA RateLimitPolicy backed by
governor. It is appropriate for one process, development, or
limits intentionally scoped to an individual replica. It needs no async runtime and no external
service.
Setup
[dependencies]
tower-rate-limiter = { version = "0.2", default-features = false, features = ["memory-gcra"] }
#![allow(unused)]
fn main() {
use std::time::Duration;
use tower_rate_limiter::{GcraQuota, GcraQuotaError, MemoryGcra};
fn configure() -> Result<MemoryGcra, GcraQuotaError> {
let quota = GcraQuota::new(100, Duration::from_secs(60), 20)?;
let policy = MemoryGcra::new(quota);
Ok(policy)
}
}
See GCRA backends for burst, microsecond rounding, response-field, and rollout semantics shared by all three adapters.
State ownership
Cloning a MemoryGcra shares the same keyed governor limiter. Constructing a new MemoryGcra
creates a separate state set, even when the quota is identical. State is lost at process restart and
is not shared through a load balancer: three replicas can collectively admit approximately three
times a one-replica limit when requests are distributed between them.
Use RedisGcra or PostgresGcra when the quota must be authoritative across replicas. Memory
GCRA is not a replacement for a shared quota store.
Key cardinality
Warning:
MemoryGcradoes not automatically evict keys. With an unbounded stream of new client keys, memory grows without bound unless the application prunes inactive state. Pruning does not impose a hard limit on active keys or total memory.
The limiter holds keyed state in memory. Choose a bounded, application-controlled client-key space where possible, and treat unbounded attacker-controlled identities as a capacity risk. Set an application memory budget and lifecycle strategy before exposing a high-cardinality limiter.
Call prune_inactive_keys() periodically to discard keys whose state is already equivalent to a
fresh key. tracked_key_count() exposes an approximate count for capacity monitoring:
#![allow(unused)]
fn main() {
use tower_rate_limiter::MemoryGcra;
fn prune(policy: &MemoryGcra) -> usize {
policy.prune_inactive_keys();
policy.tracked_key_count()
}
}
The crate does not start a background cleanup task; the application controls scheduling and can align it with its own runtime and memory budget.
The policy charges before the downstream service runs, so an allowed request still consumes one cell if its handler later fails. There is no refund API.
Redis GCRA
RedisGcra is the included shared policy for a static, continuously replenished quota. It works
with ordinary Redis scripting and does not require Redis Stack, redis-cell, or another Redis
module. The vendored artifact requires Redis 3.2 or newer because it uses
redis.replicate_commands(); this repository’s live contract suite has been run against Redis
8.8, not a complete server-version matrix.
This page documents the Redis-specific operational contract. See GCRA backends for the
shared GcraQuota and Decision meanings, microsecond upward rounding, and namespace/versioning
rules that also apply to Memory and PostgreSQL GCRA.
Setup
Enable it with one supported async runtime:
[dependencies]
redis = "1"
tower-rate-limiter = { version = "0.2", default-features = false, features = ["redis-gcra", "runtime-tokio"] }
For Smol, replace runtime-tokio with runtime-smol. The application owns Redis URL parsing,
connection creation, reconnect strategy, and shutdown; the policy accepts an established
redis::aio::MultiplexedConnection.
#![allow(unused)]
fn main() {
use std::{error::Error, time::Duration};
use tower_rate_limiter::{GcraQuota, IpKeyExtractor, RateLimitLayer, RedisGcra};
async fn configure() -> Result<RateLimitLayer<IpKeyExtractor, RedisGcra>, Box<dyn Error>> {
let client = redis::Client::open("redis://127.0.0.1/")?;
let connection = client.get_multiplexed_async_connection().await?;
let quota = GcraQuota::new(100, Duration::from_secs(60), 20)?;
let layer = RateLimitLayer::builder(IpKeyExtractor::new())
.policy_name("public-api")
.with_policy(RedisGcra::new(connection, quota).with_namespace("my-service"))
.build()?;
Ok(layer)
}
}
rate requests replenish across period. burst is the total immediate capacity of a fresh key,
not an amount added to rate: the quota above admits at most 20 immediately, then replenishes at
100 requests per minute. This release always charges one request; it has no weighted-cost or refund
API. GcraQuota rounds the common emission interval up to whole microseconds; the complete burst
replenishment window must not exceed one year.
Redis contract
Each check invokes an atomic Lua artifact and obtains time from Redis TIME; application-host clock
skew therefore does not set the GCRA decision. The ACL principal needs EVALSHA, SCRIPT LOAD,
TIME, GET, and SET. Script caching is internal to Redis; the application does not have to load
the script itself.
Set a namespace when applications or deployments share a Redis database. The namespace separates
Redis keys; a distinct policy_name still identifies a semantically distinct middleware policy.
Every replica charging the same resulting Redis key must use the same quota. When rolling out a
quota change, version the policy name or namespace so old and new instances do not reinterpret one
stored TAT with different emission intervals.
The bundled Lua file is a verbatim copy of the allowN artifact from
go-redis/redis_rate v10.0.1. It is based
on rwz/redis-gcra; source revision, checksum, and both license notices are retained in
THIRD_PARTY_NOTICES.md.
Failure and deployment limits
PolicyFailureMode::Reject is the default: a Redis command or reply-validation failure produces
the configured middleware rejection, normally 503. Select PolicyFailureMode::Allow explicitly
only when short periods of under-enforcement are preferable to rejecting healthy requests; it calls
the inner service without rate-limit fields or context.
Redis asynchronous replication can lose recent limiter writes during failover, so a newly promoted replica may briefly admit extra requests. This release does not promise compatibility with Redis Cluster, Sentinel, or managed Redis proxies—validate the exact topology, ACL, failover, and script behavior before production use.
Precision
This policy deliberately follows the unmodified go-redis/redis_rate artifact. It uses Lua
floating-point seconds for time and TAT. Whole-microsecond GcraQuota rounding does not make that
arithmetic exact: at very small emission intervals, admission can be early or late, remaining can
be truncated, and a frozen-time burst can admit fewer or more than the configured capacity.
It does not guarantee strict microsecond enforcement or exact admission parity with Memory or
PostgreSQL.
Deterministic tests execute the pinned source with only TIME replaced and real Redis state
operations inside one atomic invocation. They cover 1µs, 10µs, and 100µs recovery boundaries.
Characterization vectors also reproduce 1006 allowed charges for a 3µs interval and burst = 1000
at Unix second 1800000000, and 1048 for a 1µs interval at Unix second 2200000000. These vectors
record upstream behavior; they are not a maximum-error bound or a recommended operating rate.
The upstream comment’s epoch boundary around 2048-09-09 is not a guarantee of exact arithmetic before that date. The Rust decoder’s 1µs tolerance validates reply duration bounds; it does not bound accumulated admission error. Treat response fields as pacing guidance and validate the chosen quota under the application’s workload when precision is important.
PostgreSQL GCRA
PostgresGcra stores GCRA state in PostgreSQL and makes each charge through a database function.
It is a shared policy: replicas that use the same database, namespace, policy name, and quota
enforce one client-key state. The adapter accepts a caller-owned sqlx::PgPool and is Tokio-only
through SQLx.
Setup and migration ownership
Enable the policy and provide SQLx in the application:
[dependencies]
sqlx = { version = "0.9", default-features = false, features = ["postgres", "runtime-tokio"] }
tower-rate-limiter = { version = "0.2", default-features = false, features = ["postgres-gcra"] }
Before serving traffic, apply the packaged, versioned migration with your application’s migration runner:
migrations/postgres/0001_gcra.sql
The same artifact is exported as POSTGRES_GCRA_MIGRATION_V1 for migration tooling that accepts
SQL text. File-oriented migration frameworks should copy the packaged SQL into the application’s
own migration directory so their normal checksum and ordering rules apply.
The crate deliberately never applies DDL or creates schema objects at runtime. Treat the migration
as part of service provisioning and roll it out before deploying code that enables PostgresGcra.
#![allow(unused)]
fn main() {
use std::time::Duration;
use tower_rate_limiter::{GcraQuota, GcraQuotaError, PostgresGcra};
fn configure(pool: sqlx::PgPool) -> Result<PostgresGcra, GcraQuotaError> {
let quota = GcraQuota::new(100, Duration::from_secs(60), 20)?;
let policy = PostgresGcra::new(pool, quota).with_namespace("my-service-v1");
Ok(policy)
}
}
See GCRA backends for the shared quota, Decision, and rollout contract.
Atomicity and time source
The migration installs tower_rate_limiter_gcra_v1.charge(...). It locks an existing key row
directly or creates a missing row, retrying the lookup on a concurrent creation or deletion.
It then captures clock_timestamp() after that lock and performs the GCRA decision and
accepted-state update in the same database function. A rejected charge intentionally does not
advance state.
Using database time avoids application-host clock skew for a decision. Requests for the same key serialize on that key’s row; different keys can proceed independently. This makes PostgreSQL a good fit only when its per-request database work and hot-key contention are acceptable for the protected endpoint.
The adapter executes one statement through the pool and is tested with PostgreSQL’s default
READ COMMITTED isolation. If the deployment changes the database or role default isolation,
validate concurrent fresh-key behavior and decide how Policy errors such as serialization failures
fit the application’s failure mode.
Permissions
Run the migration as a schema owner or migration principal. The runtime limiter principal needs access to the installed schema and function plus the table permissions used by this migration’s security-invoker function:
GRANT USAGE ON SCHEMA tower_rate_limiter_gcra_v1 TO app_limiter;
GRANT EXECUTE ON FUNCTION tower_rate_limiter_gcra_v1.charge(TEXT, TEXT, BIGINT, BIGINT) TO app_limiter;
GRANT SELECT, INSERT, UPDATE ON TABLE tower_rate_limiter_gcra_v1.state TO app_limiter;
Use a separate maintenance principal for deletion if the runtime role should not remove state.
Do not change the function to SECURITY DEFINER without a deliberate ownership and search_path
review.
Expired-state cleanup
The state table records expires_at and indexes it. This cleanup timestamp is rounded up to
whole seconds, reducing index changes and permitting HOT updates when page space is available.
It never precedes the precise TAT and can retain an inactive row for less than one additional
second. Admission, remaining capacity, retry, and reset calculations still use microsecond TAT.
The migration leaves fillfactor and autovacuum at PostgreSQL defaults.
Expired rows no longer affect a fresh GCRA decision, but PostgreSQL does not remove them
automatically. Schedule a bounded cleanup job under your operational ownership, for example
repeatedly deleting expired rows in small batches during off-peak periods. Grant that job DELETE
separately when the runtime principal does not have it.
One concurrency-safe batch shape is:
WITH expired AS (
SELECT namespace, client_key
FROM tower_rate_limiter_gcra_v1.state
WHERE expires_at <= statement_timestamp()
ORDER BY expires_at
LIMIT 1000
FOR UPDATE SKIP LOCKED
)
DELETE FROM tower_rate_limiter_gcra_v1.state AS state
USING expired
WHERE state.namespace = expired.namespace
AND state.client_key = expired.client_key;
statement_timestamp() fixes the cutoff for each batch so the expiry condition can use an index
range scan. The charge function still uses clock_timestamp() after acquiring the row lock.
Choose the interval, batch size, vacuum/monitoring policy, and retention budget for your workload; the library does not run a cleanup worker. Monitor table growth, index size, lock waits, database latency, and policy failures.
Namespace and quota rollouts
Use .with_namespace(...) to separate deployments sharing one database. The middleware-provided
policy_name is also part of the scoped client key. Every replica charging the same resulting
state identity must use the same quota. When changing a quota, version the namespace or policy
name—such as my-service-v2—rather than allowing old and new emission intervals to reinterpret
the same stored theoretical-arrival time. Retire the old identity only after its state has expired.
PostgreSQL’s primary-key index also imposes a practical bound on the combined namespace and client
key size. Built-in IP keys are small. If a custom extractor can produce long or attacker-controlled
values, use with_key_encoder to map the complete scoped key to a bounded digest before it reaches
the Policy.
Production guide
A rate limiter sits on a trust and availability boundary. Before deploying, make identity, counter sharing, failure behavior, and rollout compatibility explicit.
Deployment checklist
- Give every semantically distinct policy a stable, non-empty name.
- Extract identity from validated application state or a verified peer address.
- Define the trusted-proxy boundary before reading forwarding headers.
- Use a policy with shared state when the quota must apply across replicas.
- Decide whether a policy failure rejects or fails open for each policy.
- Apply timeouts and health monitoring to externally backed policies.
- Verify emitted fields and
429behavior from outside the service. - Avoid secrets in keys, error messages, response bodies, and logs.
Identity behind proxies
IpKeyExtractor uses only the socket peer supplied in request extensions. It is the safe default
when no trusted-proxy contract exists. ClientIpKeyExtractor checks Forwarded,
X-Forwarded-For, X-Real-IP, and CF-Connecting-IP before falling back to that socket peer. This
mirrors common reverse-proxy deployments, but the parsed Header value remains an unauthenticated
assertion.
Do not expose ClientIpKeyExtractor directly to requests that may supply those headers. The deployment
must define which proxies are trusted and ensure they remove or overwrite every accepted
client-supplied field.
When both trusted proxies and direct clients may reach the listener, use
TrustedProxyClientIpKeyExtractor with an application-owned peer policy. It rejects requests without
a socket peer, ignores all forwarding Headers from untrusted peers, and only parses them after the
peer is trusted. The policy can capture application configuration such as exact proxy IPs or a CIDR
set, but the crate never reads environment variables or supplies a network policy. Trusted proxy
ingress must still be protected from direct-client bypass. If that guarantee cannot be made, use an
authenticated identity or IpKeyExtractor.
Choose one extractor for the listener and normalize identity once. Chaining socket and header-aware extractors creates multiple trust decisions for the same request and is outside the middleware contract.
Multiple replicas
MemoryStore and MemoryGcra are process-local. If three replicas each use a 100-request limit,
a caller routed across all three may receive roughly 300 requests across their independent state.
Use FixedWindow with RedisStore, RedisGcra, or PostgresGcra when the limit must be global
across replicas.
Make load-balancer behavior part of the decision. Sticky routing may reduce the difference but does not make process-local state durable or authoritative.
GCRA backends
All three GCRA adapters share GcraQuota and Decision semantics, but their clocks and storage
engines differ. GcraQuota rounds its emission interval up to whole microseconds. Version a policy
name or backend namespace when rolling out a quota change so different emission intervals never
reinterpret one stored theoretical-arrival-time value. See GCRA backends for the shared
contract.
MemoryGcra has no remote dependency, but keyed state is local to one process and may grow with
client-key cardinality. Use a bounded application-controlled identity where possible and set a
memory lifecycle budget. Schedule prune_inactive_keys() and monitor tracked_key_count() when
the key space is not statically bounded.
Redis
RedisGcra shares a continuously replenished quota through ordinary Redis; it does not require a
Redis module. Its Lua charge uses Redis TIME, so decisions use the Redis server clock rather than
application-host clocks. Grant its ACL principal EVALSHA, SCRIPT LOAD, TIME, GET, and SET.
Choose PolicyFailureMode::Reject when over-admission is unsafe; it is the default and turns a
Redis failure into the configured middleware response. PolicyFailureMode::Allow favors
availability by passing the request through without quota metadata after a policy failure. Neither
choice repairs a lost Redis connection or replaces application timeouts and monitoring.
The Lua artifact uses Redis Lua numeric precision with a known timestamp precision boundary around
2048-09-09. Redis asynchronous replication can also lose recently accepted limiter state during a
failover, briefly allowing more requests. The first release does not promise Redis Cluster,
Sentinel, or managed-proxy compatibility; validate those topologies before relying on the policy.
The artifact is a verbatim copy from go-redis/redis_rate v10.0.1; its provenance and license
notices are in THIRD_PARTY_NOTICES.md.
PostgreSQL
PostgresGcra requires an application-owned SQLx Tokio pool and the migration at
migrations/postgres/0001_gcra.sql, applied before serving traffic. The rate-limit principal needs
schema usage, function execution, and the migration’s SELECT, INSERT, and UPDATE table
permissions. Schedule bounded deletion of expired rows with a separately privileged maintenance
job when appropriate; PostgreSQL does not clean that state automatically.
The function captures database time after locking the client-key row. A hot key therefore serializes at that row, and every check consumes PostgreSQL capacity. Monitor lock waits, database latency, table/index growth, and policy failures. See PostgreSQL GCRA for the full deployment and permission contract.
Timeouts and failure policy
The limiter awaits the selected policy future. Bound remote work with the application’s timeout strategy; an unbounded dependency call can hold the request even when the inner service was ready.
Monitor at least:
- rate-limited responses by policy;
- client-key and policy failures by stable error code;
- fail-open events when
PolicyFailureMode::Allowis used; - latency of remote policy operations;
- Redis or PostgreSQL connectivity and command failures.
Fail-open responses intentionally contain no quota metadata. Record this path in application
observability without exposing raw keys or credentials. Enabling the tracing Cargo feature emits
one structured event for every policy failure on both fail-open and reject paths. Events default to
WARN, and each policy may configure another level through the builder. Applications can use the
stable target and fields for filtering, counting, and alerting.
Policy changes and rollout
Changing a limit keeps the same active counter identity. Changing the policy name or key encoder creates a different identity, so new requests will not see the old counter.
During a rolling deployment, replicas with mismatched configuration may emit different fields or charge different counters. Coordinate changes to:
- policy names;
- window durations;
- key extraction rules;
- key encoding;
- backend namespaces;
- rate-limit field revision.
If a policy’s window changes, use a new policy name to prevent one logical counter from being used with incompatible window assumptions.
Smoke test
For a test policy with limit 2, send three requests using the same client identity:
request 1 -> inner response; remaining 1
request 2 -> inner response; remaining 0
request 3 -> 429; Retry-After present
Then repeat with a different identity and confirm it begins at its own quota. In a replicated deployment, alternate requests across replicas to verify they share one policy’s counter. Finally, exercise the chosen policy failure mode in a controlled environment.
Intentional scope
Version 0.2 provides fixed-window request counting and static, one-cost Memory, Redis, and PostgreSQL GCRA. It does not provide sliding windows, token buckets, weighted requests, refunds, Redis Cluster lifecycle management, PostgreSQL migration/cleanup automation, or a built-in proxy-address configuration source.