RequestBodyLimitLayer - Limiting Request Body Size in Axum

Learn how RequestBodyLimitLayer caps request body size in Axum, how it works with the built in 2 MB default limit, and how to set different limits per route

A web server reads data that strangers send it. Most of that data is small, a login form or a short JSON object. Some of it is not. A single request can carry a body of hundreds of megabytes, and if your handler reads that body into memory without a cap, the process can run out of memory and die. RequestBodyLimitLayer is the tower-http middleware that stops that from happening. It watches the size of each request body and answers with 413 Payload Too Large when the body passes a limit you choose, before your handler ever sees the data.

This page works through the layer from the ground up. You will see the limit Axum already applies without any layer, the smallest working example, how the layer makes its decision, how to pick sizes and apply different limits to different routes, and the mistakes that catch beginners most often.

What RequestBodyLimitLayer Does

RequestBodyLimitLayer is a layer from the tower-http crate. A layer is a wrapper that sits around your handler and gets a chance to look at each request on the way in and each response on the way out. This particular layer looks at one thing only, the size of the request body in bytes. The request body is the part of an HTTP request that comes after the headers, the JSON document, the form fields, or the uploaded file.

When you add the layer with a limit, say 1 megabyte, every request that passes through it is measured. A body of 1 megabyte or less goes through to the handler untouched. A body larger than the limit is stopped. The client receives a 413 Payload Too Large response, and the handler never runs. That last point matters. The protection happens before your code allocates memory for the body, not after.

Think of the layer as a gate at the entrance to a building that checks the size of each parcel. A parcel that fits goes in. A parcel that is too large is turned away at the gate. Nobody inside has to lift it first.

The limit counts bytes of the body only. Headers are not counted. Two requests of 1 megabyte each are fine under a 1 megabyte limit, because the limit applies to each request on its own, not to all requests added together.

A layer is not a handler:

A handler produces the response for a route. A layer wraps the handler and can inspect or reject a request before the handler runs. RequestBodyLimitLayer never produces a normal response of its own. It either passes the request along unchanged or answers with a 413.

The 2 MB Limit Axum Already Applies

Before adding anything, it helps to know that Axum already has a body limit of its own. It is called DefaultBodyLimit, and it applies to extractors built on Bytes. An extractor is the piece of a handler signature that pulls a value out of the request, such as Json, String, Form, or Bytes itself. Each of these reads the whole body, and each refuses bodies larger than 2 megabytes by default.

That means a handler like the one below already rejects a 3 megabyte JSON document with a 413, even with no layer added at all. A live run of this program sent a 3 megabyte JSON body to a plain router and got back status 413.

src/main.rs
use axum::{routing::post, Json, Router};
use serde_json::{json, Value};

async fn echo(Json(body): Json<Value>) -> Json<Value> {
    Json(json!({ "received": body }))
}

#[tokio::main]
async fn main() {
    let app = Router::new().route("/echo", post(echo));

    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    println!("Server running on http://127.0.0.1:3000");
    axum::serve(listener, app).await.unwrap();
}

This program has no Cargo.toml entries beyond the usual ones, because the 2 megabyte limit is part of Axum itself. Run it and send a small JSON body, and the handler echoes it back. Send a body larger than 2 megabytes, and Axum answers 413 before the handler runs. The handler never sees the oversized body.

The default limit has two gaps, and those gaps are exactly what RequestBodyLimitLayer closes. First, the default only applies to extractors built on Bytes. A handler that reads the raw body stream itself, or that uses an extractor from another crate, gets no protection from it. Second, 2 megabytes is one fixed number for every route. An endpoint that accepts profile pictures may need 10 megabytes, while an endpoint that accepts a short settings object may need only 100 kilobytes. The layer lets you set the number yourself, per router or per route, and it applies no matter how the body is read.

Do not assume every body is capped:

The 2 megabyte default covers Bytes, String, Json, and Form. It does not cover a handler that reads the body stream directly, and it does not cover extractors from other crates. If your handler touches the raw stream, add RequestBodyLimitLayer or you have no limit at all.

Your First Example With RequestBodyLimitLayer

Start with a small echo server and cap its body at 1 megabyte. The layer lives in the limit module of tower-http, and it is only available when the limit feature is turned on. That feature name is easy to get wrong, so check it carefully in the Cargo.toml below.

Cargo.toml
[package]
name = "body-limit-demo"
version = "0.1.0"
edition = "2021"

[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
serde_json = "1"
tower-http = { version = "0.7", features = ["limit"] }
src/main.rs
use axum::{routing::post, Json, Router};
use serde_json::{json, Value};
use tower_http::limit::RequestBodyLimitLayer;

async fn echo(Json(body): Json<Value>) -> Json<Value> {
    Json(json!({ "received": body }))
}

#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/echo", post(echo))
        .layer(RequestBodyLimitLayer::new(1024 * 1024));

    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    println!("Server running on http://127.0.0.1:3000");
    axum::serve(listener, app).await.unwrap();
}

RequestBodyLimitLayer::new takes one argument, the maximum body size in bytes. 1024 * 1024 is 1,048,576 bytes, which is 1 megabyte. The .layer() call attaches the layer to the whole router, so every route in this router is protected. The handler itself is unchanged from the earlier program. Nothing inside the handler checks the size, because the check happens outside it.

Run the server with cargo run, then send a small request from another terminal.

curl -X POST http://127.0.0.1:3000/echo \
  -H "Content-Type: application/json" \
  -d '{"message": "hello"}'

The response is the echoed JSON, with status 200. Now send a body larger than 1 megabyte. The command below builds a JSON document with a long string inside it.

python3 -c "import json; print(json.dumps({'data': 'x' * 2000000}))" > big.json
curl -X POST http://127.0.0.1:3000/echo \
  -H "Content-Type: application/json" \
  --data-binary @big.json -i

The response is HTTP/1.1 413 Payload Too Large with the body text length limit exceeded. The handler never ran, so no echo was produced and no large allocation happened. A live run of this program confirmed the same result, a 2 megabyte body against this 1 megabyte layer returned 413, while a small body returned 200.

The feature is called limit, not request-body-limit:

There is no request-body-limit feature in tower-http. A Cargo.toml that asks for it fails to resolve, and the error mentions that the feature does not exist. The correct line is tower-http = { version = "0.7", features = ["limit"] }. If you copy a Cargo.toml from an older page and the build fails on feature resolution, check this name first.

A 413 on an oversized body means the layer works:

If a body just above your limit returns 413 Payload Too Large and a body just below it returns 200, the layer is wired up correctly. That pair of results is the fastest check you can run after adding it.

How the Layer Makes Its Decision

The layer decides in two different ways, depending on what the request says about its own size. Understanding both helps you predict what happens with ordinary requests and with streamed ones.

When the request carries a Content-Length header, the layer can see the declared size before reading anything. Content-Length is a header that states how many bytes the body holds. If that number is larger than your limit, the layer answers 413 at once. The inner service is not called at all, and not one byte of the body is read. Most requests from curl, browsers, and HTTP clients carry this header, so this is the path you will see most often.

When the request has no Content-Length, the body is usually sent in chunks. A chunked body is one where the client sends the data in pieces without announcing the total size first. The layer cannot know the size up front, so it wraps the body in a size-limited stream and counts bytes as they are read. The moment the count passes the limit, the read fails and the request is turned into a 413. Your handler is still not called with the full body, because the body it would read is the wrapped one that stops at the limit.

Either way, the 413 is produced by the layer itself. No other piece of the stack converts anything for it. The handler is skipped in both cases, and the client gets a clear status code instead of a dropped connection.

One more detail is worth knowing. The layer checks size while the body is being read, so it works with streaming bodies too. A handler that reads a file upload piece by piece still goes through the wrapped body, and the read that crosses the limit fails. The layer does not need to buffer the whole body first, which is what keeps its overhead low.

Choosing a Size for Your Limit

The limit is a plain number of bytes, written as a usize. You can write it as a literal or as an expression. A few sizes that come up often are 1 kilobyte (1024), 1 megabyte (1024 * 1024), and 10 megabytes (10 * 1024 * 1024). Writing the multiplication out makes the size readable at a glance, which matters when someone else reads your code months later.

Named constants make the choice even clearer, and they give you one place to change the number.

src/main.rs
use axum::{routing::post, Json, Router};
use serde_json::{json, Value};
use tower_http::limit::RequestBodyLimitLayer;

const MAX_JSON_BODY: usize = 1024 * 1024;

async fn echo(Json(body): Json<Value>) -> Json<Value> {
    Json(json!({ "received": body }))
}

#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/echo", post(echo))
        .layer(RequestBodyLimitLayer::new(MAX_JSON_BODY));

    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    println!("Server running on http://127.0.0.1:3000");
    axum::serve(listener, app).await.unwrap();
}

This program behaves exactly like the first example. The only change is that the number has a name, MAX_JSON_BODY, so a reader knows what it is for without doing the arithmetic. When the limit needs to change, you edit one line.

Pick the size from the largest legitimate payload the endpoint accepts, with a little room above it. A settings endpoint that expects a few hundred bytes can use a limit of 100 kilobytes. An image upload endpoint may need 10 megabytes. A limit that is too tight rejects real users, and a limit that is too loose gives up the protection. Measure real payloads in development before choosing, and test with a body just below and just above the limit, as the earlier curl example does.

Different Limits for Different Routes

One limit for the whole application is rarely right. An endpoint that accepts a short JSON object and an endpoint that accepts a file upload have very different needs. Axum gives you two ways to give them different limits, and they behave differently, so it helps to see both.

The first way is route_layer. It applies a layer to the routes that were added to the router before the call. The example below gives /small a 1 megabyte limit and /large a 50 megabyte limit.

src/main.rs
use axum::{routing::post, Json, Router};
use serde_json::{json, Value};
use tower_http::limit::RequestBodyLimitLayer;

async fn small_handler(Json(body): Json<Value>) -> Json<Value> {
    Json(json!({ "small": body }))
}

async fn large_handler(Json(body): Json<Value>) -> Json<Value> {
    Json(json!({ "large": body }))
}

#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/small", post(small_handler))
        .route_layer(RequestBodyLimitLayer::new(1024 * 1024))
        .route("/large", post(large_handler))
        .route_layer(RequestBodyLimitLayer::new(50 * 1024 * 1024));

    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    println!("Server running on http://127.0.0.1:3000");
    axum::serve(listener, app).await.unwrap();
}

There is a subtlety here that trips people up. The second route_layer call wraps everything added before it, not just /large. That means /small ends up with two layers, the 1 megabyte one and the 50 megabyte one, and the smaller limit wins for that route. The outcome matches the labels, a 2 megabyte body is rejected on /small and accepted on /large, but the mechanism is two stacked layers on /small, not one layer per route. Keep that in mind if you later add a third route, because each new route_layer wraps all the routes above it.

The second way is to build a separate router per group of routes and merge them. Each router carries its own layer, and the layers never stack on each other.

src/main.rs
use axum::{routing::post, Json, Router};
use serde_json::{json, Value};
use tower_http::limit::RequestBodyLimitLayer;

async fn small_handler(Json(body): Json<Value>) -> Json<Value> {
    Json(json!({ "small": body }))
}

async fn large_handler(Json(body): Json<Value>) -> Json<Value> {
    Json(json!({ "large": body }))
}

#[tokio::main]
async fn main() {
    let small_routes = Router::new()
        .route("/small", post(small_handler))
        .layer(RequestBodyLimitLayer::new(1024 * 1024));

    let large_routes = Router::new()
        .route("/large", post(large_handler))
        .layer(RequestBodyLimitLayer::new(50 * 1024 * 1024));

    let app = small_routes.merge(large_routes);

    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    println!("Server running on http://127.0.0.1:3000");
    axum::serve(listener, app).await.unwrap();
}

Merging two routers is more code, but each route gets exactly one limit and nothing stacks by accident. Use route_layer when the stacking is harmless, which it usually is when the limits get looser as you go down the list, and use separate merged routers when you want each group to carry exactly one limit and nothing else.

A route added after the layer call is not covered:

Both .layer() and .route_layer() only wrap the routes that already exist in the router at the time of the call. A route added after the call sits outside the layer. Add all routes first, then add the layer, or the new route will have no limit at all.

Combining the Layer With the Built In Default Limit

The layer and the built in default limit can both be present at once, and they do not conflict. They check at different places. The layer wraps the body for every request. The default limit applies inside the Bytes-based extractors. When both are present, the smaller of the two wins for those extractors, because whichever check is hit first rejects the body.

That gives you a useful combination. If an endpoint needs to accept bodies larger than 2 megabytes through Json, the default limit would reject them before your layer gets a say. You can switch the default off for that router and let your layer be the only limit.

src/main.rs
use axum::{extract::DefaultBodyLimit, routing::post, Json, Router};
use serde_json::{json, Value};
use tower_http::limit::RequestBodyLimitLayer;

async fn echo(Json(body): Json<Value>) -> Json<Value> {
    Json(json!({ "received": body }))
}

#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/echo", post(echo))
        .layer(DefaultBodyLimit::disable())
        .layer(RequestBodyLimitLayer::new(50 * 1024 * 1024));

    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    println!("Server running on http://127.0.0.1:3000");
    axum::serve(listener, app).await.unwrap();
}

DefaultBodyLimit::disable() is itself a layer. It removes the 2 megabyte cap from the Bytes-based extractors on this router. The RequestBodyLimitLayer beside it caps every body at 50 megabytes, no matter how it is read. A live run of this program confirmed it, a 3 megabyte JSON body returned 200 against this router, where the same body returned 413 with the default limit alone. The 50 megabyte layer is now the only cap, and it is a real cap, so a 60 megabyte body would still be rejected.

Only disable the default when you have a layer to take its place. Disabling it with no layer leaves Json and Bytes extractors with no limit at all, which brings back the original problem.

You can also raise the default instead of disabling it. DefaultBodyLimit::max(10 * 1024 * 1024) sets the extractor limit to 10 megabytes. That is the right tool when the only readers are Bytes-based extractors and you want a bigger cap for them alone. The layer is the right tool when the body might be read any other way, or when you want one cap for the whole router.

Getting a Friendlier Error Response

By default, the 413 response carries the body text length limit exceeded. That is fine for a machine client that only checks the status code, but a human reading an API error may want a short JSON message explaining what happened. RequestBodyLimitLayer itself offers no hook to change its response. It returns the 413 directly, so there is no error for an error-handling layer to catch and convert.

One helper is often looked for in the wrong place here, so it is worth getting its address right. HandleErrorLayer is the layer that converts a fallible layer's error into a response of your choosing, and it lives in Axum itself, at axum::error_handling::HandleErrorLayer. There is no HandleErrorLayer in tower-http, and there is no error module in tower-http at all. It is the right tool for layers that fail with an error, such as a timeout layer, but it does not help with this layer, because this layer never fails with an error. It answers the 413 itself.

If you genuinely need a JSON body on a 413, write a small piece of middleware that checks the declared Content-Length before the handler runs and returns your JSON error when it is over the limit.

src/main.rs
use axum::{
    extract::Request,
    http::{header::CONTENT_LENGTH, StatusCode},
    middleware::{self, Next},
    response::{IntoResponse, Response},
    routing::post,
    Json, Router,
};
use serde_json::{json, Value};
use tower_http::limit::RequestBodyLimitLayer;

const MAX_BODY: u64 = 1024 * 1024;

async fn friendly_limit(req: Request, next: Next) -> Response {
    let too_large = req
        .headers()
        .get(CONTENT_LENGTH)
        .and_then(|value| value.to_str().ok())
        .and_then(|text| text.parse::<u64>().ok())
        .map(|length| length > MAX_BODY)
        .unwrap_or(false);

    if too_large {
        return (
            StatusCode::PAYLOAD_TOO_LARGE,
            Json(json!({ "error": "request body too large" })),
        )
            .into_response();
    }

    next.run(req).await
}

async fn echo(Json(body): Json<Value>) -> Json<Value> {
    Json(json!({ "received": body }))
}

#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/echo", post(echo))
        .layer(RequestBodyLimitLayer::new(MAX_BODY as usize))
        .layer(middleware::from_fn(friendly_limit));

    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    println!("Server running on http://127.0.0.1:3000");
    axum::serve(listener, app).await.unwrap();
}

The middleware reads the Content-Length header, parses it as a number, and compares it with the limit. When the declared size is over the limit, it returns a 413 with a JSON body instead of calling the handler. When the header is missing or the size is within the limit, it passes the request on. With repeated .layer() calls the last call is outermost, so friendly_limit runs first and gets the first chance to answer, and the RequestBodyLimitLayer underneath still guards everything the middleware cannot see.

That last point is the honest limit of this trick. The middleware only sees the declared size. A chunked body carries no Content-Length, so the middleware passes it through, and the layer underneath catches it when the bytes actually cross the limit. In that case the client gets the layer's plain 413, whose body is the text length limit exceeded, not the JSON one. Keep both pieces in place: the middleware for a friendly message on the common path, and the layer for real enforcement on every path.

Uploads, Multipart Bodies, and Streaming

A file upload usually arrives as a multipart body. Multipart is a format where one request body holds several parts, such as a text field and a file, separated by a boundary marker. Axum's Multipart extractor reads those parts one at a time instead of loading the whole body at once. The layer still applies, because it wraps the underlying body stream, so every byte the extractor reads is counted toward the same limit. The moment the total bytes read pass the limit, the next read fails and the request becomes a 413.

That multipart path was run live while writing this page. A 5 kilobyte multipart upload against a 1 kilobyte layer returned 413, and the handler was never called, so no part was read at all. The Json and Bytes paths were run live as well, and they behaved as described above.

The same reasoning covers any streaming reader. If your handler reads the body in chunks and writes them to disk, the layer caps the total, so a client cannot fill your disk with one request. The cap is on the whole body, not on each chunk, which is what makes it useful for uploads.

Using the Layer Alongside Other Middleware

A real application rarely has one layer. You may also want logging, CORS, and compression. Tower provides ServiceBuilder to compose several layers into one, and the layer works inside it like any other. The example below needs two more dependencies beyond the first Cargo.toml on this page, the tower crate and two more tower-http features, trace for the logger and compression-gzip for compression.

Cargo.toml
[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
serde_json = "1"
tower = "0.5"
tower-http = { version = "0.7", features = ["limit", "trace", "compression-gzip"] }
src/main.rs
use axum::{routing::post, Json, Router};
use serde_json::{json, Value};
use tower::ServiceBuilder;
use tower_http::{
    compression::CompressionLayer, limit::RequestBodyLimitLayer, trace::TraceLayer,
};

async fn echo(Json(body): Json<Value>) -> Json<Value> {
    Json(json!({ "received": body }))
}

#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/echo", post(echo))
        .layer(
            ServiceBuilder::new()
                .layer(TraceLayer::new_for_http())
                .layer(CompressionLayer::new())
                .layer(RequestBodyLimitLayer::new(5 * 1024 * 1024)),
        );

    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    println!("Server running on http://127.0.0.1:3000");
    axum::serve(listener, app).await.unwrap();
}

Inside a ServiceBuilder, the first layer listed is the outermost and runs first, which is the opposite of repeated .layer() calls. Here TraceLayer logs the request first, then CompressionLayer, then the body limit, then the handler. The body limit is about request bodies, while compression is about response bodies, so their order relative to each other does not change much. The order that does matter is against any layer that reads the request body. The limit must run before such a layer, or the body could be read without the cap.

Common Mistakes

Checking the size inside the handler

The most common mistake is to read the body in the handler and check its length afterwards. By then the body is already in memory, which is the outcome the limit exists to prevent. Enforce the limit at the middleware level, where the request is stopped before the handler runs.

Forgetting the limit feature

Without features = ["limit"] on the tower-http dependency, tower_http::limit::RequestBodyLimitLayer does not exist and the compiler reports that the module is not found. Add the feature and the type appears.

Setting the limit too low for real requests

A 1 kilobyte limit on an endpoint whose clients send 2 kilobyte JSON documents rejects every real request. Measure the payloads your clients actually send and leave room above the largest legitimate one.

Placing the limit after a layer that reads the body

If another layer reads or decompresses the request body before the limit layer runs, that layer can consume the whole body without a cap. A compressed payload that expands to far more than your limit is the classic case. Put the limit layer before any layer that reads the body.

Confusing the body limit with a header limit

This layer limits the body only. The size of the headers is governed elsewhere, at the HTTP server level, and this layer does nothing about oversized headers. Do not expect it to protect against those.

Leaving a route outside the layer

A route added after the .layer() call is not wrapped by it. If you add routes in several steps, check that the layer call comes after the last route it should cover, or the new route will accept unlimited bodies.

Never disable the default limit without a replacement:

DefaultBodyLimit::disable() removes the only cap on Json, String, Form, and Bytes. If you disable it and forget to add RequestBodyLimitLayer, those extractors accept bodies of any size. Always pair the disable call with a layer that sets the cap you actually want.

Where This Layer Fits in Real Applications

Public APIs use this layer on every route that accepts a body. An API that accepts small configuration objects might set 100 kilobytes. An API that accepts image uploads might set 10 megabytes. A file storage endpoint might set 100 megabytes. The number follows the endpoint, not the application, which is why the per-route patterns above matter.

The limit is often read from configuration rather than written as a literal, so it can change without recompiling. A constant at the top of main.rs is a good start. An environment variable read at startup is the next step, and it lets the same binary run with a stricter limit in one deployment and a looser one in another.

Summary

The single most useful way to think about body limits is that there are two of them, and they guard different doors. The built in 2 megabyte default guards the Bytes-based extractors and nothing else. RequestBodyLimitLayer guards the whole router, no matter how the body is read, with a limit you choose. Use the default on its own when every reader is a Bytes-based extractor and 2 megabytes is the right number. Reach for the layer when you need a different number, a different number per route, or protection for raw and streamed readers. And when you raise or disable the default to make room for larger bodies, make the layer the replacement cap, never leave the door without one. A limit that is tested with a body just below and just above it is a limit you can trust, and it costs a handful of lines to add.