Expand description
Rate-limiting middleware for axum, backed by governor.
§Quick start
use std::net::SocketAddr;
use axum::{Router, routing::get};
use axum_governor::{GovernorConfigBuilder, GovernorLayer, Quota, nz, extractor::PeerIp};
#[tokio::main]
async fn main() {
let cfg = GovernorConfigBuilder::default()
.with_extractor(PeerIp::default())
.expect_connect_info()
.quota_default(Quota::requests_per_second(nz!(50u32)))
.finish()
.unwrap();
let app = Router::new()
.route("/", get(|| async { "hello" }))
.layer(GovernorLayer::new(cfg));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000").await.unwrap();
axum::serve(listener, app.into_make_service_with_connect_info::<SocketAddr>())
.await
.unwrap();
}§Features
- Key extraction — sync and async extractors; built-in
PeerIp,Global,Header,Extension,SmartIp,Cookie,Compound. Seeextractor. - Per-method quotas — different limits for GET vs POST via
GovernorConfigBuilder::quota_for. - Stacked limits — ordered chain of named policies with first-reject-wins
semantics and IETF
RateLimit-Policyheader listing all entries. - Per-tier override — extractors return
extractor::KeyOutcomewithquota_overridefor per-request quota selection. - Background GC — periodic
retain_recentsweep driven by aWeak-referenced task; configurable interval and opt-out viaGovernorConfigBuilder::gc_disable. - Type erasure —
BoxedGovernorLayercollapses theKparameter for use in#[derive(Clone)] struct AppState.
§Cargo features
| Feature | Default | Enables |
|---|---|---|
dashmap | yes | Lock-free per-tier limiter cache |
tracing | yes | Per-request span and per-reject event |
json | yes | BodyPreset::ProblemJson reject bodies |
test-utils | no | test_utils helpers for downstream tests |
Re-exports§
pub use crate::boxed::BoxedGovernorLayer;pub use crate::builder::GovernorConfig;pub use crate::builder::GovernorConfigBuilder;pub use crate::error::ConfigError;pub use crate::error::ExtractionError;pub use crate::error::RejectionReason;pub use crate::extractor::AsyncKeyExtractor;pub use crate::extractor::Compound;pub use crate::extractor::Cookie;pub use crate::extractor::Extension;pub use crate::extractor::Global;pub use crate::extractor::Header;pub use crate::extractor::KeyExtractor;pub use crate::extractor::KeyOutcome;pub use crate::extractor::PeerIp;pub use crate::extractor::SmartIp;pub use crate::layer::GovernorLayer;pub use crate::quota::Quota;pub use crate::response::BodyPreset;pub use crate::response::ErrorHandler;pub use crate::snapshot::LimiterHandle;pub use crate::snapshot::LimiterSnapshot;
Modules§
- boxed
- Type-erased
BoxedGovernorLayerthat hides the key-extractor type parameter. - builder
- Builder for assembling a
GovernorConfig. - error
- Error and reason types shared across the middleware.
- extractor
- Key extraction traits and built-in extractor implementations.
- gc
- Background garbage-collection task for the key state store.
- headers
- Pure header writers for rate-limit response headers.
- layer
tower::Layerconstructor for the rate-limit middleware.- quota
- Rate quota types exposed in the public API.
- response
- Default 429 response bodies and the
BodyPresetenum. - service
tower::Serviceper-request flow.- snapshot
- Live introspection for the layer’s limiter state.
Macros§
- nz
- Re-export of
nonzero_ext::nonzero!under a shorter name. Create non-zero values from constant literals easily.
Structs§
- Mock
Clock - A mock implementation of a clock. All it does is keep track of what “now” is (relative to some point meaningful to the program), and returns that.