Per-client rate limiting
Learn how to limit requests per client IP with tower_governor, what the token bucket does, how the 429 response works, and how to key limits by API key instead
Rate limiting means allowing only a set number of requests in a time window and deciding what happens to the rest. Per-client rate limiting keeps a separate budget for each client, usually identified by IP address, so one greedy client cannot spend the budget for everyone else. The tower_governor crate provides this as a Tower layer for Axum: a quota per key, refilled over time, with a 429 answer when the quota is empty. This page builds it, runs it, and shows the exact moment a request is turned away.
Where This Fits
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 global limit would punish every client for one client's behaviour. A per-client limit isolates the damage: the greedy client gets 429 responses, and everyone else keeps working. The limit is a guard, not a feature for the user. Nobody notices it until it saves the server.
Think of a water tank with a tap per house. Each house gets its own tank, refilled at a steady rate. One house leaving its tap open drains only its own tank. The other houses keep their water. A single shared tank would let one house drain the whole street. The quota is the tank, the refill period is the tap filling it back up, and the burst size is how big the tank is.
The Smallest Working Version
One route, one layer, one quota: five requests in a burst, refilling one request every two seconds, keyed by the client's IP address.
[package]
name = "rate-limit-api"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
tower_governor = "0.8"
use axum::{Router, routing::get};
use tower_governor::{GovernorLayer, governor::GovernorConfigBuilder};
async fn hello() -> &'static str {
"hello"
}
pub fn app() -> Router {
let governor_conf = GovernorConfigBuilder::default()
.per_second(2)
.burst_size(5)
.finish()
.unwrap();
Router::new()
.route("/", get(hello))
.layer(GovernorLayer::new(governor_conf))
}
The app() function returns a plain router, so tests can call it. The conversion to a service that carries connection information happens in main, because that is where the server is started:
use rate_limit_api::app;
use std::net::SocketAddr;
#[tokio::main]
async fn main() {
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
println!("Listening on http://127.0.0.1:3000");
axum::serve(listener, app().into_make_service_with_connect_info::<SocketAddr>())
.await
.unwrap();
}
Run it and send seven requests quickly:
for i in 1 2 3 4 5 6 7; do curl -s -o /dev/null -w "%{http_code} " http://127.0.0.1:3000/; done; echo
On the machine used to check this page, the answer was:
200 200 200 200 200 429 429
Five requests succeed. The sixth and seventh are refused with 429, Too Many Requests. Wait three seconds and try again:
sleep 3; curl -s -o /dev/null -w "%{http_code}\n" http://127.0.0.1:3000/
200
The quota refilled while waiting, one request every two seconds, so after three seconds there is budget again. The full 429 response looks like this:
HTTP/1.1 429 Too Many Requests
x-ratelimit-after: 1
retry-after: 1
content-length: 30
Too Many Requests! Wait for 1s
The retry-after header tells the client how many seconds to wait before trying again, and the body says the same in words. The number counts down as the bucket refills: a request that arrives just after a refill can show 0, and one that arrives just after the burst is spent shows 1 or more.
Working Setup:
If five fast requests answer 200, the sixth answers 429, and a request after a short wait answers 200 again, the limiter is working per client. If every request answers 200, the layer is not in the path, or the quota is larger than the test. If every request answers 500, the IP address is missing, and the next section explains why.
The Pieces, One at a Time
1. The quota: per_second and burst_size
let governor_conf = GovernorConfigBuilder::default()
.per_second(2)
.burst_size(5)
.finish()
.unwrap();
GovernorConfigBuilder::default() starts from the crate defaults: a burst of 8 and a refill period of 500 milliseconds. .per_second(2) changes the refill to one request every two seconds. .burst_size(5) changes the tank to five requests. .finish() builds the configuration, returning Option<GovernorConfig>, and .unwrap() takes it out, because the combination of a two second period and a burst of five is valid. A zero period or a zero burst would make finish() return None, and the unwrap would panic, which is the crate's way of saying the configuration makes no sense.
The two numbers describe different things, and confusing them is the most common mistake. The burst size is how many requests can arrive at once. The period is how fast the budget comes back. Five per two seconds means a client can send five requests instantly, then must wait two seconds for the next one, then two more seconds for the one after that. It does not mean five requests every two seconds forever. After the burst, the steady rate is one request every two seconds.
2. The layer: GovernorLayer
.layer(GovernorLayer::new(governor_conf))
GovernorLayer wraps the router the way any Tower layer does. Each incoming request passes through it before reaching the handler. The layer looks up the client's key, checks the budget for that key, and either passes the request on or answers 429 itself. The handler never runs for a rejected request, which is the point: the expensive work is skipped, not just delayed.
3. The key: the peer IP, and why ConnectInfo is required
axum::serve(listener, app().into_make_service_with_connect_info::<SocketAddr>())
The default key extractor is PeerIpKeyExtractor. It reads the peer IP address from the connection information Axum attaches to each request. That information only exists when the service is built with into_make_service_with_connect_info::<SocketAddr>(). Without it, the extractor finds nothing, and the layer answers 500 with an Unable To Extract Key error instead of limiting anything. The 500 is the symptom of a missing setup step, not of a request being limited.
This is the single most important mechanical detail on the page. The layer, the quota, and the route can all be right, and the server will still answer 500 to every request if the serve call is the plain form. The plain form is axum::serve(listener, app()). The working form carries the into_make_service_with_connect_info::<SocketAddr>() call. When a rate limited server answers 500, check the serve call first.
The Concept Behind It
The mechanism is a token bucket. A token bucket is a container that holds tokens, fills at a steady rate, and spends one token per request. A request that finds a token takes it and proceeds. A request that finds the bucket empty is refused. The burst size is the size of the bucket. The refill period is how fast tokens drip in. The bucket never holds more than its size, so a client that waits an hour does not accumulate an hour of budget. It accumulates one full bucket, and no more.
The token bucket is why bursts work the way they do. A client that has been quiet has a full bucket and can spend five requests at once. A client that has been busy has an empty bucket and must wait for the drip. The bucket is per key, so each client has its own. The word bucket is the mental model to keep: size, drip rate, and one token per request.
Why Per Client Instead of Global
A global limit, one budget shared by every caller, is simpler to build and easier to reason about. It also has a failure mode that matters: one client spending the budget locks everyone else out. A per-client limit costs a map from client to bucket, and the map grows with the number of clients, but it isolates misbehaviour. The choice is between simplicity and isolation, and for a public API the isolation is usually worth the map.
The map itself needs care. Entries for clients that never return stay in the map, so the crate provides a way to clean up: the configuration exposes a limiter handle with a len() count and a retain_recent() sweep, and the crate's own example runs a background thread that logs the size and sweeps stale entries every minute. For a small service the growth is slow, but it is still growth, and it deserves the same thought as any unbounded map.
Two Different Limits on Two Different Routes
Not every route deserves the same budget. A public read can be generous. A login route should be strict, because a login route is where password guessing happens. The clean way to give routes different limits is to build two small routers, each with its own layer, and merge them.
use axum::{Router, routing::get};
use tower_governor::{GovernorLayer, governor::GovernorConfigBuilder};
async fn hello() -> &'static str {
"hello"
}
async fn admin() -> &'static str {
"admin area"
}
fn public_router() -> Router {
let config = GovernorConfigBuilder::default()
.per_second(2)
.burst_size(5)
.finish()
.unwrap();
Router::new().route("/", get(hello)).layer(GovernorLayer::new(config))
}
fn admin_router() -> Router {
let config = GovernorConfigBuilder::default()
.per_second(4)
.burst_size(2)
.finish()
.unwrap();
Router::new().route("/admin", get(admin)).layer(GovernorLayer::new(config))
}
pub fn app() -> Router {
Router::new().merge(public_router()).merge(admin_router())
}
The admin router allows a burst of two and refills one request every four seconds. That is the same shape as the crate's GovernorConfig::secure() preset, which is designed for exactly this: login and token endpoints where a slow drip is a feature. Checked live, the public route answers 200 five times and then 429, while the admin route answers 200 twice and then 429:
public: 200 200 200 200 200 429
admin: 200 200 429
Merging keeps the two limits independent, because each router carries its own layer and its own map of buckets. A client that exhausts the admin budget can still use the public route, and the other way round.
Presets Save Thinking:
GovernorConfig::default() allows a burst of eight with a 500 millisecond refill, which suits most read endpoints. GovernorConfig::secure() allows a burst of two with a four second refill, which suits login and password reset endpoints. Start from a preset and adjust one number, rather than inventing both numbers from nothing.
Keying by Header When Behind a Proxy
The peer IP is the address of the machine that connected to the server. Behind a reverse proxy, that machine is always the proxy, so every client looks like one client, and one budget covers the whole internet. The fix is to read the address from the headers the proxy sets, using SmartIpKeyExtractor, which checks X-Forwarded-For, X-Real-IP, and Forwarded, in that order, and falls back to the peer IP when none are present.
use tower_governor::{
GovernorLayer,
governor::GovernorConfigBuilder,
key_extractor::SmartIpKeyExtractor,
};
let governor_conf = GovernorConfigBuilder::default()
.per_second(2)
.burst_size(5)
.key_extractor(SmartIpKeyExtractor)
.finish()
.unwrap();
Only the builder call changes. The layer and the serve call stay the same. The warning that comes with it is real: those headers are set by whoever sends the request, so they can only be trusted when the proxy is the one setting them and the server only accepts connections from that proxy. A client that can reach the server directly can write any address into X-Forwarded-For and get a fresh budget for every request. Use the header extractor only behind a proxy you control, and make sure the proxy overwrites the header rather than appending to it.
Keying by API Key Instead
Some APIs identify clients by a key in a header, not by address. A custom key extractor reads that header and returns it as the key. The trait needs three things: a key type that can be cloned, hashed, and compared, and an extract function that returns the key or a GovernorError.
use axum::http::Request;
use tower_governor::{errors::GovernorError, key_extractor::KeyExtractor};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct ApiKeyExtractor;
impl KeyExtractor for ApiKeyExtractor {
type Key = String;
fn extract<T>(&self, req: &Request<T>) -> Result<Self::Key, GovernorError> {
req.headers()
.get("x-api-key")
.and_then(|value| value.to_str().ok())
.map(|value| value.to_string())
.ok_or(GovernorError::UnableToExtractKey)
}
}
Register it the same way as the smart IP extractor:
let governor_conf = GovernorConfigBuilder::default()
.per_second(2)
.burst_size(5)
.key_extractor(ApiKeyExtractor)
.finish()
.unwrap();
A request without the header gets the Unable To Extract Key error, which the layer turns into a 500 response. That is the honest behaviour for a missing key on an endpoint that requires one, but it is a rough edge: a 500 for a missing API key reads like a server bug. In practice the API key check belongs in authentication, and the rate limiter sits behind it, so the requests that reach the limiter already carry a key. The extractor is the mechanism; authentication is the gatekeeper.
A 500 for a Missing Key Is Not a Limit:
When the extractor cannot find a key, the layer answers 500, not 429. A flood of 500s in the logs after adding a custom extractor usually means clients are calling without the header, not that the limit is too strict. Read the error before tuning the numbers.
Limiting Only Some Methods
A read heavy API may want to limit POSTs but leave GETs alone, or the other way round. The builder takes a list of methods, and requests with other methods pass through untouched.
use axum::http::Method;
let governor_conf = GovernorConfigBuilder::default()
.per_second(2)
.burst_size(5)
.methods(vec![Method::POST])
.finish()
.unwrap();
A GET to a route behind this layer is never counted and never refused. A POST is counted against the same per-client bucket. This is useful for expensive writes, and it is a reminder that the layer sees the method before anything else, so method based limits are cheap to apply and easy to explain.
What the Flow Looks Like
Request arrives with a peer IP
|
v
GovernorLayer asks the key extractor for the key
|
+----+----------------+
| key found? |
+----+----------------+
| no | yes
v v
500 Unable To Look up the bucket
Extract Key for that key
|
+----+----+
| token? |
+----+----+
| yes | no
v v
Take token, 429 Too Many
call handler Requests
retry-after header
The handler only runs on the yes path. Everything else is answered by the layer itself.
Testing It
Testing a limiter through the router has one trap, and it is the same trap as the serve call: a test request built by hand has no connection information, so the peer IP extractor finds nothing and the layer answers 500. The fix is to insert the connection information into the request extensions by hand, the way Axum would have done it for a real connection.
use axum::{
body::Body,
extract::ConnectInfo,
http::{Request, StatusCode},
};
use rate_limit_api::app;
use std::net::SocketAddr;
use tower::ServiceExt;
#[tokio::test]
async fn five_requests_pass_and_the_sixth_is_limited() {
let app = app();
let mut statuses = Vec::new();
for _ in 0..7 {
let mut request = Request::builder().uri("/").body(Body::empty()).unwrap();
request.extensions_mut().insert(ConnectInfo(SocketAddr::from((
[127, 0, 0, 1],
40000,
))));
let response = app.clone().oneshot(request).await.unwrap();
statuses.push(response.status());
}
assert_eq!(
statuses,
vec![
StatusCode::OK,
StatusCode::OK,
StatusCode::OK,
StatusCode::OK,
StatusCode::OK,
StatusCode::TOO_MANY_REQUESTS,
StatusCode::TOO_MANY_REQUESTS,
]
);
}
The test needs tower as a dev dependency:
[dev-dependencies]
tower = { version = "0.5", features = ["util"] }
The test sends seven requests from the same fake address, 127.0.0.1, and checks the exact sequence: five 200s and two 429s. The router is cloned per request, because oneshot consumes the service, and the clone shares the same limiter state. Without the ConnectInfo insert, the same test would get seven 500s, and that failure is itself worth knowing: it proves the test exercises the real extractor path, not a stub.
Common Beginner Mistakes
Forgetting into_make_service_with_connect_info
// Wrong - the layer cannot find the peer IP, every request answers 500
axum::serve(listener, app()).await.unwrap();
The fix is the serve call shown in the smallest version. This is the mistake to check first whenever a limited server answers 500 to everything, because everything else can be right and this one call still breaks it.
Expecting the limiter to delay instead of refuse
Tower's own RateLimitLayer delays requests until budget returns. tower_governor refuses them with 429. The two behaviours look similar in a config file and are opposites in practice. A delayed request eventually succeeds, slowly. A refused request fails fast, and the client decides whether to retry. Choose the refusal when the client can back off, and choose the delay when the work must happen eventually. Do not tune one expecting the other.
Setting the burst to the steady rate
A burst of two with a two second refill allows two requests at once, then one every two seconds. A burst of fifty with the same refill allows fifty at once, then one every two seconds. The burst is not the rate. Raising the burst to fix a slow steady rate changes nothing after the first burst. Lowering the refill period is what raises the steady rate.
Rate limiting the health check
A health check route that is limited will start failing under load, and the load balancer will conclude the server is dead and stop sending it traffic, which is the opposite of what the limit was for. Keep health and readiness routes outside the limited router, or give them their own generous budget. The limiter protects the work. The health check is how the world knows the work is still possible.
A Limit on the Wrong Key Punishes Everyone:
A limiter keyed by peer IP behind a proxy without header extraction gives the whole internet one shared budget. A limiter keyed by API key on a route that does not require a key answers 500 to every anonymous request. The numbers can be perfect and the key can still be wrong. Check what the key actually is for a real request before trusting the limit.
Final Complete Example
Here is everything from the page put together: the public and admin routers with their own quotas, the server with its connect info, and the test that proves the exact sequence of statuses.
use axum::{Router, routing::get};
use tower_governor::{GovernorLayer, governor::GovernorConfigBuilder};
async fn hello() -> &'static str {
"hello"
}
async fn admin() -> &'static str {
"admin area"
}
fn public_router() -> Router {
let config = GovernorConfigBuilder::default()
.per_second(2)
.burst_size(5)
.finish()
.unwrap();
Router::new().route("/", get(hello)).layer(GovernorLayer::new(config))
}
fn admin_router() -> Router {
let config = GovernorConfigBuilder::default()
.per_second(4)
.burst_size(2)
.finish()
.unwrap();
Router::new().route("/admin", get(admin)).layer(GovernorLayer::new(config))
}
pub fn app() -> Router {
Router::new().merge(public_router()).merge(admin_router())
}
use rate_limit_api::app;
use std::net::SocketAddr;
#[tokio::main]
async fn main() {
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
println!("Listening on http://127.0.0.1:3000");
axum::serve(listener, app().into_make_service_with_connect_info::<SocketAddr>())
.await
.unwrap();
}
[package]
name = "rate-limit-api"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
tower_governor = "0.8"
[dev-dependencies]
tower = { version = "0.5", features = ["util"] }
Run the server with cargo run, send six fast requests to / and watch the sixth answer 429, then send three to /admin and watch the third answer 429. Run the test with cargo test and watch the exact sequence pass.
Summary
The single most important insight is that a per-client limit is three decisions, not one: the quota, the key, and the answer. The quota is the burst and the refill, and the two numbers mean different things. The key is what makes the limit per client, and the wrong key quietly turns it into a global limit or a 500 factory. The answer is a fast 429 with a retry hint, which lets a good client back off and a bad client fail loudly. Get the key right and the numbers honest, and the limiter is a quiet guard that only speaks when it has to.
The decision framework follows from that. Limit per client when one client must not be able to hurt the rest. Key by peer IP for direct traffic, by trusted headers behind a proxy you control, and by API key when identity already exists. Keep the health check outside the limit, keep the secure preset on the login route, and test the exact sequence of statuses, because a limiter that is never observed refusing a request is a limiter that has never been proven to work.