axum_gcra
GCRA-based Rate Limiter for Axum with per-route/per-key rate limiting.
Summary
This crate provides a robust implementation of a rate-limiting Layer and Service for axum using the
GCRA algorithm, which allows for average throughput and burst request limiting. Rather than providing a global
rate-limiter for all routes, this crate allows for individual routes/paths to be configured with separate
rate-limiting quotas and for the extraction of arbitrary keys from the request for additional compartmentalization.
For example:
use Duration;
use ;
use ;
async
Keys
In order for the rate limiter to be able to differentiate between different clients, the RateLimitLayer can be
configured with single or composite keys that are extracted from the request. For example, to rate limit based on
the client's IP address, the following could be used with the provided RealIp extractor:
use ;
use ;
type Key = RealIp; // could also be `(RealIp, UserSession)`, for example.
let app = new
// keys are any type that can implement `FromRequestParts` and `axum_gcra::Key`
.route
// The key type must also be specified when extracting the `RateLimiter` extension.
.route
.route_layer;
Please read the documentation for [RealIp] for more information.
Garbage Collection
Internally, the rate limiter uses a shared hash map structure to store the state of each key. To avoid it growing indefinitely, a garbage collection mechanism is provided that will remove entries that have expired and no longer needed. This can be configured to run based on the number of requests processed or on a fixed time interval in a background task. For example:
use Duration;
use ;
use ;
let app = new
.route
.route_layer;
See the docs for [GCInterval] for more information.