Answer#
A server that accepts any size of body can be made to use all its memory by one client. DefaultBodyLimit sets the ceiling for the extractors that read the body.
use axum::{body::{to_bytes, Body}, extract::DefaultBodyLimit, http::Request, routing::post, Router};
use tower::ServiceExt;
async fn upload(body: String) -> String { format!("received {} bytes", body.len()) }
#[tokio::main]
async fn main() {
let app = Router::new().route("/upload", post(upload)).layer(DefaultBodyLimit::max(1024));
for size in [1000usize, 1024, 1025, 5000] {
let req = Request::post("/upload").body(Body::from("x".repeat(size))).unwrap();
let res = app.clone().oneshot(req).await.unwrap();
let status = res.status().as_u16();
let body = to_bytes(res.into_body(), usize::MAX).await.unwrap();
println!("{size} bytes -> {status} {}", String::from_utf8_lossy(&body));
}
}1000 bytes -> 200 received 1000 bytes
1024 bytes -> 200 received 1024 bytes
1025 bytes -> 413 Failed to buffer the request body: length limit exceeded
5000 bytes -> 413 Failed to buffer the request body: length limit exceededA body of exactly 1024 bytes passed and one byte more was refused with 413. In the axum documentation the default limit for Multipart is 2 MB; set your own limit explicitly so it is visible in the code.
Common mistakes#
- Raising the limit for the whole router because one upload route needs it. Apply a bigger
DefaultBodyLimitto that route only. - Checking only the
Content-Lengthheader yourself. Clients can send a wrong value or none (chunked bodies); the extractor counts the bytes it really reads.
Related questions#
Does the limit apply to file uploads?#
Yes. See the thread on uploads with Multipart, where a 20,000 byte file is refused under a 10,000 byte limit.
Sources#
- axum,
DefaultBodyLimit: https://docs.rs/axum/0.8.9/axum/extract/struct.DefaultBodyLimit.html (read 2026-12-05)