RateLimitLayer Overview in Axum
Learn why tower RateLimitLayer fails in axum, first refusing to compile and then silently doing nothing on normal routes, and the hand-rolled Arc-state limiter that returns 429 and actually works
What rate limiting means
Rate limiting means allowing only a set number of requests in a time window and doing something with the excess. A time window is a fixed stretch of time, such as one second or one minute, and the number allowed inside it is the budget. Two requests per second means a budget of two and a window of one second. The third request inside that second is excess, and the server must decide what to do with it.
The excess can be rejected, with a 429 status that tells the client it sent too many requests. It can be delayed, held until the window resets and then let through. Or it can be dropped without an answer. Which one is right depends on the client. A 429 lets a well-behaved client back off and retry later. A delay keeps the connection open and makes the client wait, which is fine for a background job and bad for an interactive user.
Rate limiting exists because servers have finite capacity and clients are not always well behaved. A bug in a client can send the same request in a tight loop. A script can hammer an expensive endpoint on purpose. A limit turns either of those from an outage into a few rejected requests. It is a guard, not a feature for the user. Nobody notices it until it saves the server.
This page is an autopsy plus a replacement. First, what tower limiter actually does. Second, why the obvious axum example fails in three different ways, each one verified by running code. Third, the hand-rolled limiter that works on normal routes. Every timing quoted below was measured on this machine against axum 0.8.9 and tower 0.5.3, not estimated.
What tower limiter actually does
Tower limiter is tower::limit::RateLimitLayer, built with a count and a window:
use std::time::Duration;
use tower::limit::RateLimitLayer;
let layer = RateLimitLayer::new(2, Duration::from_secs(1));
Three facts about it, each of which surprises someone.
It delays. It never rejects. When the budget is exhausted, the limiter does not return a 429 status. It makes the request wait until the window resets and then lets it through. A client that sends 100 requests in a burst gets 100 responses, just slowly. If you want a 429, this is the wrong layer.
The budget is global, not per client. One shared budget covers every caller, every IP address, every API key, and every route the layer wraps. There is no per-user, per-IP, or per-key variant in tower limiter. One greedy client can spend the budget for everyone.
It panics on zero arguments. RateLimitLayer::new(0, ...) and RateLimitLayer::new(5, Duration::from_secs(0)) both panic at construction time, with an assertion failure. A limit of zero requests is not "block everything". It is a programming error, and tower says so loudly. Both panics were verified by running the constructors: the zero count panics, the zero duration panics, and a normal pair of arguments does not.
With those facts in mind, here is the obvious example, and the three ways it fails in axum.
Setting up the project
Every example on this page runs in the same small project. Create it with cargo new rate-limit-demo and replace the generated Cargo.toml with this one.
[package]
name = "rate-limit-demo"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
tower = { version = "0.5", features = ["limit", "buffer", "util"] }
The versions here are axum 0.8.9, tokio 1.54.1, and tower 0.5.3. The tower features are the three this page needs: limit for the rate limiter, buffer for the workaround in the second attempt, and util for ServiceBuilder. The hand-rolled limiter at the end of the page needs no tower features at all, because it is built from axum's own middleware tools.
Attempt 1, the obvious example does not compile
use axum::{routing::get, Router};
use std::time::Duration;
use tower::{limit::RateLimitLayer, ServiceBuilder};
async fn hello() -> &'static str {
"hello"
}
fn main() {
let _app = Router::new()
.route("/", get(hello))
.layer(ServiceBuilder::new().rate_limit(2, Duration::from_secs(1)));
}
This fails to compile:
error[E0277]: the trait bound `RateLimit<Route>: Clone` is not satisfied
The cause is one of axum's two compile bounds on layers. A layer is a wrapper that turns one service into another, and a service is the object that handles a request. When axum applies a layer to a router, the service the layer produces must be Clone, clonable, because axum clones the service for each request it handles. Tower rate-limit service is not Clone. It holds a sleep timer and mutable budget state that cannot be duplicated. So the builder is rejected before the program ever runs. The error names the missing trait directly: RateLimit<Route> does not implement Clone.
This is a compile error, which is the good kind of failure. It is loud, it points at the exact line, and nothing ships while it is present. The next attempt is worse, because it also fails to compile, and the fix for it produces the most dangerous form in this page.
Clone is an axum requirement, not a tower bug:
Tower limiter was not written to be cloned, because in plain tower use a service is built once and shared. Axum clones the service per request, so it demands Clone from every layer it applies. The mismatch is between two designs, not a defect in either crate on its own.
Attempt 2, the Buffer workaround does not compile either
The standard fix for a non-Clone service is .buffer(...), which wraps the service in a channel-based worker that is clonable. A channel is a queue that passes requests from one task to another, and the worker on the other end owns the real service, so the outside handle can be cloned freely.
use axum::{routing::get, Router};
use std::time::Duration;
use tower::ServiceBuilder;
async fn hello() -> &'static str {
"hello"
}
fn main() {
let _app = Router::new()
.route("/", get(hello))
.layer(
ServiceBuilder::new()
.buffer(10)
.rate_limit(2, Duration::from_secs(1)),
);
}
This also fails to compile, with a different error:
error[E0277]: the trait bound `!: From<Box<(dyn std::error::Error + Send + Sync + 'static)>>` is not satisfied
The cause is axum's second compile bound: the service error type must convert into Infallible, the empty error type that means "this service never fails". Buffer error type is BoxError, a boxed error that can hold any error, and axum cannot turn that into a response on its own. The compiler expresses that as a missing From<BoxError> conversion for the never type, which is its way of saying the error has nowhere to go.
The fix is an outer HandleErrorLayer, listed first in the builder so it wraps the buffer. HandleErrorLayer is axum's own error handler, at axum::error_handling::HandleErrorLayer, and it turns a service error into a response. There is no equivalent layer in tower-http. The closure receives the boxed error and returns a 503 status, the code for a service that is temporarily unavailable.
use axum::{
error_handling::HandleErrorLayer, http::StatusCode, routing::get, BoxError,
Router,
};
use std::time::Duration;
use tower::ServiceBuilder;
async fn hello() -> &'static str {
"hello"
}
fn main() {
let _app = Router::new()
.route("/", get(hello))
.layer(
ServiceBuilder::new()
.layer(HandleErrorLayer::new(|_: BoxError| async {
StatusCode::SERVICE_UNAVAILABLE
}))
.buffer(10)
.rate_limit(2, Duration::from_secs(1)),
);
}
This compiles. It is also the most dangerous form in this page, because it compiles and does nothing.
HandleErrorLayer lives in axum, not tower-http:
tower_http::error::HandleErrorLayer does not exist. Tower-http has no error module at all. The import is axum::error_handling::HandleErrorLayer. Every example that imports it from tower-http fails to compile, and the error points at the import, not at the layer.
Attempt 3, the compiling form silently does nothing
Send three requests to the router above, with a budget of two per second. If the limiter worked, the third request would be delayed by about a second while the window resets. Measured against a live server, each of the three requests finished in a few milliseconds. In one run the times were 0.064, 0.002, and 0.015 seconds, and all three returned 200. No delay at all. The limiter is a no-op, a piece of code that runs and changes nothing.
The reason is how axum 0.8 applies layers to normal routes. For a .route() route, axum does not build the middleware service once at startup. It stores the layer and rebuilds the service fresh for each request. Tower limiter keeps its budget in the service struct, the object built by the layer. So each request gets a fresh service with a fresh, full budget. The first request of every rebuild is always within budget, because the budget was just created. The limiter cannot see the previous request, because the previous service was thrown away with it.
Think of it as a bouncer who is hired fresh for every guest and told the club is empty. Each guest is the first guest the bouncer has ever seen. No guest is ever turned away, because the count resets before every arrival. The rule is correct. The memory of who came before is gone.
The proof is the same stack on a route built with route_service, where axum layers the service eagerly, once, instead of rebuilding it per request. route_service takes a raw service, not a handler, so the route is built from a plain function that answers every request with hello.
use std::convert::Infallible;
use axum::{error_handling::HandleErrorLayer, extract::Request, http::StatusCode, response::Response, BoxError, Router};
use std::time::Duration;
use tower::ServiceBuilder;
#[tokio::main]
async fn main() {
let svc = tower::service_fn(|_req: Request| async {
Ok::<_, Infallible>(Response::new(axum::body::Body::from("hello")))
});
let app = Router::new()
.route_service("/", svc)
.layer(
ServiceBuilder::new()
.layer(HandleErrorLayer::new(|_: BoxError| async {
StatusCode::SERVICE_UNAVAILABLE
}))
.buffer(10)
.rate_limit(2, Duration::from_secs(1)),
);
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
Three requests to this router took 0.003, 0.001, and 0.984 seconds. The third request waited about one second, until the one-second window reset, exactly as tower limiter is designed to do. The same stack, the same budget, two different results. The only difference is whether the service is shared across requests or rebuilt for each one.
Do not take this as a recommendation to use route_service for your routes. It takes a raw service, not a handler, so you lose extractors, routing, and everything else that makes axum routes convenient. It proves the diagnosis. It is not a usable pattern for a normal app.
A compiling rate limiter that does not limit is worse than no rate limiter:
A missing limiter is visible. There is no code, and anyone reading the router can see it. A tower limiter on a .route() route looks like protection and provides none. If you have shipped this pattern, remove it or replace it with the pattern below, and test it with three rapid requests, the way this page does.
The working pattern, a hand-rolled limiter with Arc-shared state
The fix follows from the diagnosis. If the service is rebuilt per request, the shared state must not live in the service. It must live in the layer, behind an Arc, where the rebuild clones it instead of replacing it. An Arc is a shared pointer that lets several owners share one value, and cloning it shares the value rather than copying it. The simplest way to write that in axum is a middleware function with state: the state is cloned into each request handling, and the Arc inside it is shared across all of them.
use axum::{
extract::{Request, State},
http::StatusCode,
middleware::{self, Next},
response::{IntoResponse, Response},
routing::get,
Router,
};
use std::{
sync::{Arc, Mutex},
time::{Duration, Instant},
};
async fn hello() -> &'static str {
"hello"
}
#[derive(Clone)]
struct Window {
start: Instant,
count: u64,
}
#[derive(Clone)]
struct Limiter {
max: u64,
per: Duration,
window: Arc<Mutex<Window>>,
}
impl Limiter {
fn new(max: u64, per: Duration) -> Self {
Self {
max,
per,
window: Arc::new(Mutex::new(Window {
start: Instant::now(),
count: 0,
})),
}
}
// Synchronous check: the std MutexGuard never crosses an await point.
fn allow(&self) -> bool {
let mut w = self.window.lock().unwrap();
if w.start.elapsed() >= self.per {
w.start = Instant::now();
w.count = 0;
}
if w.count >= self.max {
return false;
}
w.count += 1;
true
}
async fn limit(&self, request: Request, next: Next) -> Response {
if !self.allow() {
return (StatusCode::TOO_MANY_REQUESTS, "slow down").into_response();
}
next.run(request).await
}
}
#[tokio::main]
async fn main() {
let limiter = Limiter::new(2, Duration::from_secs(60));
let app = Router::new()
.route("/", get(hello))
.layer(middleware::from_fn_with_state(
limiter,
|State(lim): State<Limiter>, req: Request, next: Next| async move {
lim.limit(req, next).await
},
));
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
The hand-rolled limiter needs no tower at all, so its Cargo.toml is the same project file with the tower line removed and nothing else changed. The package section stays exactly as in the setup section above.
[package]
name = "rate-limit-demo"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
The Window holds the start of the current window and the number of requests counted inside it. The Limiter holds the budget, the window length, and the window itself behind an Arc and a Mutex. A Mutex is a lock that lets one thread at a time touch the value inside it. The Limiter is Clone, and cloning it clones the Arc, so every request handling shares the same window. That single fact is the whole fix. The state lives in the layer, not in the service, so the per-request rebuild cannot reset it.
The allow method is the check. It locks the window, and if the window has expired it starts a fresh one with a count of zero. If the count has reached the budget it returns false without counting. Otherwise it counts the request and returns true. The limit method is the middleware. It calls allow, and when the answer is false it returns a 429 response with the body slow down, without ever calling the handler. When the answer is true it calls next.run(request), which passes the request on to the handler. Next is the remainder of the middleware stack, including the handler, and run is the call that hands control to it.
Three rapid requests to this router return statuses 200, 200, 429. The third is rejected with 429 Too Many Requests and the body slow down. That is a rejection, not a delay, which is what an API client can actually act on: back off and retry, instead of waiting on an open connection.
Two implementation details deserve attention. The lock never crosses an await point. allow() is a synchronous method: it locks the Mutex, checks and updates the window, and drops the guard before returning. The async part, calling next.run(request), happens after the guard is gone. Holding a standard library MutexGuard across an .await makes the future non-Send, and axum requires middleware futures to be Send, so the program would fail to compile. Keep the check synchronous, as above.
The window is fixed, not sliding. When the window expires, the count resets to zero. That is the simplest correct window, and it is enough for most APIs. A sliding window or a token bucket is a refinement of the same structure, same Arc, same middleware shape, not a different pattern. A token bucket is a limiter that refills the budget gradually instead of all at once at the window boundary.
How to tell the hand-rolled limiter is working:
Send three rapid requests against a budget of two. If the statuses come back 200, 200, 429, the limiter works. If all three come back 200, the state is not shared across requests, and the counter is resetting. That one probe is the whole test.
Limiting per client instead of globally
The limiter above shares one budget across all callers. Most APIs want a budget per client instead, so one greedy caller cannot spend everyone's budget. The change is small and stays inside the same structure: keep a map from a client key to a window, behind the same Arc and Mutex, instead of a single window.
use std::collections::HashMap;
#[derive(Clone)]
struct KeyedLimiter {
max: u64,
per: Duration,
windows: Arc<Mutex<HashMap<String, Window>>>,
}
impl KeyedLimiter {
fn new(max: u64, per: Duration) -> Self {
Self {
max,
per,
windows: Arc::new(Mutex::new(HashMap::new())),
}
}
fn allow(&self, key: &str) -> bool {
let mut map = self.windows.lock().unwrap();
// Evict expired windows so the map does not grow without bound.
map.retain(|_, w| w.start.elapsed() < self.per);
let w = map.entry(key.to_string()).or_insert(Window {
start: Instant::now(),
count: 0,
});
if w.start.elapsed() >= self.per {
w.start = Instant::now();
w.count = 0;
}
if w.count >= self.max {
return false;
}
w.count += 1;
true
}
async fn limit(&self, request: Request, next: Next) -> Response {
let key = request
.headers()
.get("x-api-key")
.and_then(|v| v.to_str().ok())
.unwrap_or("anonymous")
.to_string();
if !self.allow(&key) {
return (StatusCode::TOO_MANY_REQUESTS, "slow down").into_response();
}
next.run(request).await
}
}
The Window type is the same one from the global limiter, and the wiring is the same shape, with KeyedLimiter in place of Limiter in the from_fn_with_state call. The limit method reads the key from the x-api-key header, falling back to the single string anonymous when the header is absent, and checks that key budget. The allow method looks the key up in the map, creating a fresh window for a key it has never seen, and counts against that window only.
Two warnings come with the map. First, it grows without bound. Every new key adds an entry, and entries for keys that never return stay in memory. The retain line in allow drops windows older than the window length on every check, so dead keys are evicted as part of normal traffic. Without that line, the limiter becomes a slow memory leak. Second, the key must be trustworthy. An IP address taken from the X-Forwarded-For header is client-controlled unless your proxy strips it, and an API key that is missing should map to a single anonymous bucket, as above, or be rejected outright, not to a fresh bucket per request. A limiter keyed on something the client can rotate at will limits nothing.
Verified against a live server, three rapid requests with one key return 200, 200, 429, and three rapid requests with a different key return 200, 200, 429 as well. The budgets are independent. The first key being exhausted does not slow the second key at all.
What tower limiter is good for
Tower limiter is not a bad layer. It is a layer for a different context. It works correctly wherever the service is shared across requests: a plain tower service that is not rebuilt per request, a route_service endpoint, or a client-side service where one service instance makes many calls. In those contexts its delay-instead-of-reject behaviour is a feature: it smooths bursts instead of failing them. A client that sends a burst of requests gets them all answered, spread out over time, instead of getting rejections it must handle.
In axum, on normal .route() routes, the per-request rebuild makes it a no-op, and the hand-rolled pattern above is the working replacement. The choice is not between a good layer and a bad layer. It is between a layer whose state lives in the service, which axum rebuilds, and a limiter whose state lives in the layer, which axum keeps.
One more pointer, clearly labelled as unverified: crates exist that provide per-client limiting for axum, and tower_governor is the name most often mentioned. It was not installed or tested for this page, so nothing here claims it works, compiles against these versions, or behaves in any particular way. Treat it as a lead to evaluate yourself, not as a recommendation.
How to test your limiter
The test is the same shape as the probe used throughout this page. Build the router, send more requests than the budget allows, fast, and assert on the statuses. For a budget of two per sixty seconds, three rapid requests must return 200, 200, 429. The test must run against the real router, not against the limiter in isolation, because the failure mode lives in the interaction between the limiter and axum per-request rebuild. A unit test of the allow method alone would pass for the tower limiter too. Its budget logic is correct. It is the wiring that defeats it. Test the wired router, with the budget exceeded, on every change to the middleware stack.
Test with the budget exceeded or do not test at all:
A limiter test that sends fewer requests than the budget proves nothing. The tower limiter passes it, the hand-rolled limiter passes it, and a router with no limiter at all passes it. The only request that distinguishes a working limiter from a broken one is the one over the budget. Always send one more request than the budget allows.
Common mistakes
Expecting a 429 from tower limiter. It delays. It never rejects. If your client needs a 429, build the hand-rolled limiter.
Expecting per-user limits from tower limiter. The budget is global, one budget for all callers. Per-key limiting needs the map variant above.
Putting the counter in the service struct. In axum 0.8 the service is rebuilt per request, so a plain counter field resets on every request. Shared state goes in the layer, behind an Arc.
Holding a MutexGuard across an await. The middleware future becomes non-Send and fails to compile. Do the check in a synchronous helper, as above.
Passing zero to RateLimitLayer::new. Both new(0, ...) and new(5, Duration::from_secs(0)) panic at construction.
Importing HandleErrorLayer from tower-http. It does not exist there. It is axum::error_handling::HandleErrorLayer.
Not testing with three rapid requests. The tower limiter failure mode is silence. The only way to know a limiter works is to send more requests than the budget allows, fast, and check the one that must fail.
Summary
The decision this page leaves behind is a choice between two shapes of state. State that lives in the service is rebuilt with the service, and in axum that rebuild happens per request, so a service-held budget is always full. State that lives in the layer behind an Arc survives the rebuild, because the layer is cloned, not remade. Tower limiter is the first shape, which is why it compiles with a buffer and a handler, delays correctly on a shared service, and silently does nothing on a normal route. The hand-rolled limiter is the second shape, which is why three rapid requests return 200, 200, 429 instead of three 200s. When you reach for a limiter, ask where its state lives. If the answer is the service, it will not limit your routes. If the answer is the layer, it will.