Multipart size limits

Learn the 2 MB default body limit on Axum uploads, how to raise or lower it with DefaultBodyLimit, and how RequestBodyLimitLayer answers oversized uploads with 413

A server that accepts uploads accepts data from strangers, and strangers can send a lot of it. Without a size limit, one request can carry a body large enough to fill the server's memory and stop it. Axum protects against that by default. Every multipart upload is capped at 2 megabytes unless the handler says otherwise, and the cap is enforced while the body is being read, before the handler has a chance to hold it all. This page explains that cap, how to change it, and what the client sees when an upload crosses it.

Where This Fits

The previous page ended with a warning that bytes() holds a whole field in memory. This page is the guard that keeps that hold small. The limit is already active in every handler written so far, and this page makes it visible, shows how to set it per route, and shows how to turn its plain error into the app's own JSON error shape.

Think of the limit as a bouncer with a measuring tape at the door. Every upload is measured as it comes in. One that fits walks through. One that does not is turned away at the door, before anyone inside has to lift it. The handler never sees an oversized upload, because the bouncer stops it first.

The Smallest Working Version

The default limit needs no code at all. This handler is the same field reporter from the earlier pages, with nothing added:

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

async fn upload(mut multipart: Multipart) -> Json<Value> {
    let mut fields = Vec::new();
    while let Some(field) = multipart.next_field().await.unwrap() {
        let name = field.name().map(|s| s.to_string());
        let data = field.bytes().await.unwrap();
        fields.push(json!({
            "name": name,
            "size": data.len(),
        }));
    }
    Json(json!({ "fields": fields }))
}

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

    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();
}

Send a small file first:

curl -X POST http://127.0.0.1:3000/upload \
  -F "file=@photo.png;type=image/png"

The response is status 200 with the field and its size. Now send a 3 megabyte file:

python3 -c "open('/tmp/three-mb.bin','wb').write(b'x'*3000000)"
curl -i -X POST http://127.0.0.1:3000/upload \
  -F "file=@/tmp/three-mb.bin;type=application/octet-stream"

The response is status 413 with this body:

Request payload is too large

A live run of this exact program returned that status and body for the 3 megabyte file, and status 200 for the small one. The status 413 means "Payload Too Large", and the body is the plain text message the multipart error carries. The handler never ran for the large file, because the read failed while the body was being measured, before the handler could hold it.

A 413 on a 3 MB upload means the limit works:

If a small file returns 200 and a 3 megabyte file returns 413 with the body Request payload is too large, the default limit is working. That pair of results is the fastest check on this page.

What the Default Limit Counts

The limit is 2 megabytes, which is 2,097,152 bytes. It counts the whole request body, not just the file inside it. A multipart body holds the file bytes plus the boundary markers, the field headers, and the line endings that separate the parts. All of those count toward the 2 megabytes.

That detail has a sharp edge. A file of exactly 2,097,152 bytes inside a multipart body is already over the limit, because the wrappers around it add bytes of their own. A live run confirmed it. A file of exactly 2,097,152 bytes sent as a multipart field was rejected with status 413, and a file of 2,097,000 bytes was rejected too, because the boundary and headers add a few hundred bytes on top of the file. A file of 2,096,800 bytes went through with status 200. The largest file that fits is a little under 2 megabytes, and the exact room left depends on the length of the field name, the file name, and the boundary string.

The limit is applied by the extractor itself. The Multipart extractor builds its reader on a body that Axum has already wrapped with the limit, so every byte the handler reads through next_field(), bytes(), or chunk() is counted. The count is on the body as it is read, not on the declared size. A client that lies about the size in its headers is still measured by the bytes that actually arrive.

Where the Limit Lives

The default limit is called DefaultBodyLimit, and it lives in axum::extract. It is a layer, which means it can be attached to a router with .layer(), like any middleware. Attaching it changes the cap for the routes it wraps. There are three settings, and each is one call:

use axum::extract::DefaultBodyLimit;

// Raise the cap to 10 megabytes
DefaultBodyLimit::max(10 * 1024 * 1024)

// Remove the cap entirely
DefaultBodyLimit::disable()

// Put the default back, 2 megabytes
DefaultBodyLimit::default()

max takes a size in bytes as a usize. Writing the size as a multiplication, 10 * 1024 * 1024, makes the number readable at a glance. disable() removes the cap, which means the extractors accept bodies of any size. default() restores the 2 megabyte cap, which is useful when a router has disabled it and a smaller group of routes needs it back.

Here is a route that accepts uploads up to 10 megabytes, built by layering the new limit onto a small router:

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

async fn upload(mut multipart: Multipart) -> Json<Value> {
    let mut fields = Vec::new();
    while let Some(field) = multipart.next_field().await.unwrap() {
        let name = field.name().map(|s| s.to_string());
        let data = field.bytes().await.unwrap();
        fields.push(json!({
            "name": name,
            "size": data.len(),
        }));
    }
    Json(json!({ "fields": fields }))
}

#[tokio::main]
async fn main() {
    let large_uploads = Router::new()
        .route("/upload", post(upload))
        .layer(DefaultBodyLimit::max(10 * 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, large_uploads).await.unwrap();
}

A 3 megabyte file now returns 200, because the cap is 10 megabytes. A 12 megabyte file still returns 413. The handler is unchanged. Only the layer around it changed, which is the point of a layer: the limit is a property of the route, not of the handler code.

Disable only with a replacement cap:

DefaultBodyLimit::disable() removes the only cap on the extractors. If you disable it and add nothing else, a client can send a body of any size and the handler will try to read it. Always pair a disable with a layer that sets the cap you actually want, as the next section shows.

RequestBodyLimitLayer, the Layer That Caps Everything

The default limit guards the extractors that read the body through Axum's own types. RequestBodyLimitLayer, from the tower-http crate, guards the whole router, no matter how the body is read. It wraps the body stream itself, so every byte that passes through it is counted, including bytes read by a handler that touches the raw stream directly.

The layer lives in the limit module of tower-http, and it needs the limit feature turned on:

Cargo.toml
[dependencies]
axum = { version = "0.8", features = ["multipart"] }
tokio = { version = "1", features = ["full"] }
serde_json = "1"
tower-http = { version = "0.7", features = ["limit"] }

Here is the same upload route capped at 1 megabyte by the layer:

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

async fn upload(mut multipart: Multipart) -> Json<Value> {
    let mut fields = Vec::new();
    while let Some(field) = multipart.next_field().await.unwrap() {
        let name = field.name().map(|s| s.to_string());
        let data = field.bytes().await.unwrap();
        fields.push(json!({
            "name": name,
            "size": data.len(),
        }));
    }
    Json(json!({ "fields": fields }))
}

#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/upload", post(upload))
        .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();
}

Send a 5,000 byte file and the response is 200. Send a 2 megabyte file and the response is 413, but with a different body text than the default limit produced:

length limit exceeded

A live run of this exact program returned status 413 with that body for a 5,000 byte file against a 1 kilobyte layer, and the handler was never called. The two limits produce two different messages because they are two different pieces of code. The default limit, reached through the multipart extractor, answers with Request payload is too large. The layer answers with length limit exceeded. Both mean the same thing, the body was too large, and the status is 413 in both cases. The body text is the only difference, and a client should check the status, not the text, to know what happened.

The layer also decides earlier than the default limit in one case. When the request carries a Content-Length header stating the body's size, the layer sees the declared size before reading anything and answers 413 at once, without reading a single byte. When the header is missing, the layer counts bytes as they are read and answers 413 the moment the count passes the limit. Either way the handler never runs.

The Two Limits Side by Side

The default limit and the layer overlap, and a route can carry both. When both are present, the smaller one wins, because whichever check is hit first rejects the body. That gives a useful combination for uploads larger than 2 megabytes. The default limit would reject a 5 megabyte upload before the layer gets a say, so the route disables the default and lets the layer be the only cap:

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

async fn upload(mut multipart: Multipart) -> Json<Value> {
    let mut fields = Vec::new();
    while let Some(field) = multipart.next_field().await.unwrap() {
        let name = field.name().map(|s| s.to_string());
        let data = field.bytes().await.unwrap();
        fields.push(json!({
            "name": name,
            "size": data.len(),
        }));
    }
    Json(json!({ "fields": fields }))
}

#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/upload", post(upload))
        .layer(DefaultBodyLimit::disable())
        .layer(RequestBodyLimitLayer::new(10 * 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();
}

With repeated .layer() calls, the last call is outermost and runs first. The layer order here does not change the outcome much, because both layers cap the same body, but the pairing is what matters. The disable removes the 2 megabyte cap from the extractors, and the 10 megabyte layer becomes the only cap. A 5 megabyte file now returns 200, and a 12 megabyte file returns 413 with the layer's message, length limit exceeded.

The table sums up the two caps:

CapWhere it livesApplies toOver-limit body
DefaultBodyLimit, 2 MBAxum itselfExtractors built on the body, including MultipartRequest payload is too large
RequestBodyLimitLayer, your sizetower-http, limit featureEvery body read on the router, however it is readlength limit exceeded

Both answer with status 413. The difference is the scope, the message, and who sets the number.

Turning the Plain 413 Into a JSON Error

Both caps answer with a plain text body by default, and neither matches the app's error shape, one JSON object with a single error key. A client that expects JSON gets plain text instead, which is a small inconsistency, and it is easy to fix at the handler level for the default limit.

The multipart error carries its own status and message, through the status() and body_text() methods. A handler that maps the error through those methods keeps the 413 and wraps the message in JSON:

src/main.rs
use axum::{
    extract::{multipart::MultipartError, Multipart},
    response::{IntoResponse, Response},
    routing::post,
    Json, Router,
};
use serde_json::{json, Value};

fn multipart_error_response(err: MultipartError) -> Response {
    (err.status(), Json(json!({ "error": err.body_text() }))).into_response()
}

async fn upload(mut multipart: Multipart) -> Result<Json<Value>, Response> {
    let mut fields = Vec::new();
    while let Some(field) = multipart
        .next_field()
        .await
        .map_err(multipart_error_response)?
    {
        let name = field.name().map(|s| s.to_string());
        let data = field
            .bytes()
            .await
            .map_err(multipart_error_response)?;
        fields.push(json!({
            "name": name,
            "size": data.len(),
        }));
    }
    Ok(Json(json!({ "fields": fields })))
}

Send a 3 megabyte file to this handler and the response is status 413 with this body:

{"error":"Request payload is too large"}

A live run of this exact shape of handler returned that status and body. The status comes from the error itself, and the message is the error's own text, placed inside the app's JSON shape. The handler keeps the information the error already had and only changes the wrapping.

The layer's 413 is harder to reshape, because the layer answers before the handler runs, so no handler code can catch it. The way to get a JSON body for the layer's 413 is a small piece of middleware that checks the declared Content-Length before the handler runs and returns the JSON error itself when the declared size is over the limit:

src/main.rs
use axum::{
    extract::{Multipart, 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 upload(mut multipart: Multipart) -> Json<Value> {
    let mut fields = Vec::new();
    while let Some(field) = multipart.next_field().await.unwrap() {
        let name = field.name().map(|s| s.to_string());
        let data = field.bytes().await.unwrap();
        fields.push(json!({
            "name": name,
            "size": data.len(),
        }));
    }
    Json(json!({ "fields": fields }))
}

#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/upload", post(upload))
        .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. A live run of this exact shape returned 413 with {"error": "request body too large"} for a 3 megabyte upload against the 1 megabyte limit, and 200 for a small file.

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.

The 500 Mistake

The easiest mistake on this page is also the most misleading one. A handler that maps every multipart error to the app's InternalError turns a 413 into a 500:

// Wrong - an oversized upload becomes a 500
async fn upload(mut multipart: Multipart) -> Result<Json<Value>, AppError> {
    while let Some(field) = multipart
        .next_field()
        .await
        .map_err(|_| AppError::InternalError)?
    {
        let data = field.bytes().await.map_err(|_| AppError::InternalError)?;
    }
}

A live run of this shape of handler returned status 500 with {"error": "something went wrong"} for a 3 megabyte file, and the same for a 5,000 byte file over a 1 kilobyte limit. The upload was too large, which is a client problem with status 413, but the client sees a server problem with status 500, and the real cause is hidden. The fix is the helper above, which reads the status off the error instead of replacing it. The map_err(|_| AppError::InternalError) pattern throws away exactly the information that distinguishes a too-large upload from a broken server, and it should never be used on a multipart read.

Do not map every multipart error to InternalError:

Mapping all multipart errors to InternalError turns an oversized upload into a 500 with the message something went wrong. The client cannot tell it sent too much data, and the server looks broken when it is not. Map the error through its own status() and body_text() instead.

Choosing a Size

The limit is a plain number of bytes, and the right number follows the largest legitimate upload the route accepts, with a little room above it. A profile picture route might use 1 megabyte. A document upload route might use 10 megabytes. A route that accepts short text fields and no files at all can use a much smaller number, because its bodies are tiny.

Named constants make the choice readable and give one place to change it:

src/main.rs
const MAX_UPLOAD_BYTES: usize = 5 * 1024 * 1024;

let app = Router::new()
    .route("/upload", post(upload))
    .layer(DefaultBodyLimit::max(MAX_UPLOAD_BYTES));

A limit that is too tight rejects real users, and a limit that is too loose gives up the protection. Measure the payloads real clients send during development, and test with a body just below and just above the limit, as the curl examples on this page do. A limit tested that way is a limit you can trust.

Different routes need different limits. The cleanest way to give them different numbers is to build a separate router per group of routes, put one limit layer on each, and merge the routers, so each route carries exactly one cap and nothing stacks by accident. A smaller group of routes can also be wrapped with route_layer, which applies a layer to the routes added before the call, but each new route_layer call wraps everything above it, so the limits stack on the earlier routes and the smaller one wins.

How the Limit Flows Through a Request

The sequence from the client to the answer fits in a short diagram:

Client sends a multipart body
        |
        v
RequestBodyLimitLayer, if present, checks Content-Length
        |
        v
Declared size over the limit -> 413 length limit exceeded
        |
        v
Body streams in, counted as it is read
        |
        v
Count passes the limit -> 413, handler never runs
        |
        v
Body fits -> extractor reads fields -> handler runs

The default limit sits inside the extractor's read, so its 413 comes from the MultipartError the handler sees. The layer sits outside the extractor, so its 413 comes before the handler starts. Both stop the body before it can fill the server's memory.

Common Beginner Mistakes

Checking the size inside the handler

Reading the whole body in the handler and checking its length afterwards defeats the limit. By then the body is already in memory, which is the outcome the limit exists to prevent. Enforce the limit at the layer, where the request is stopped before the handler runs.

Raising the limit by disabling it

DefaultBodyLimit::disable() without a replacement layer leaves the route with no cap at all. A beginner who disables the default to accept a 5 megabyte file, and forgets the layer, has opened the route to bodies of any size. Disable only when a layer takes over, as the combined example above shows.

Forgetting the limit feature on tower-http

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. The feature name is limit, not request-body-limit, and the error mentions that the feature does not exist. Add the feature and the type appears.

Expecting the limit to count only the file

The limit counts the whole body, including boundaries and field headers. A file just under the limit can still be rejected when the wrappers push the total over it. Test with the real multipart request, not with the file size alone, and leave room above the largest file for the wrappers.

Confusing the two 413 messages

Request payload is too large comes from the multipart extractor and the default limit. length limit exceeded comes from RequestBodyLimitLayer. Both are status 413, and both mean the body was too large. A test that checks for one specific message will fail when the other limit is the one that fires. Check the status, and treat the message as a hint about which limit fired.

Two messages, one status:

The default limit and the layer answer oversized bodies with different text, but the status is 413 in both cases. A client should decide what happened from the status code, and use the body text only to learn which limit fired.

Testing the Limit

A test that sends a body just under the limit and one just over it proves the cap works without a running server. The test needs tower as a dev dependency, and it builds the multipart body by hand, as on the earlier pages. The body below is a single field holding 1,024 bytes of x, sent to a route capped at 1,024 bytes of body, which is over the cap once the boundary and headers are counted:

tests/upload_test.rs
use axum::{
    body::Body,
    extract::{multipart::MultipartError, DefaultBodyLimit, Multipart},
    http::{Request, StatusCode},
    routing::post,
    Json, Router,
};
use serde_json::json;
use tower::ServiceExt;

#[tokio::test]
async fn upload_over_the_limit_is_rejected() {
    let app = Router::new()
        .route(
            "/upload",
            post(|mut multipart: Multipart| async move {
                while let Some(field) = multipart.next_field().await? {
                    let _ = field.bytes().await?;
                }
                Ok::<_, MultipartError>(Json(json!({ "ok": true })))
            }),
        )
        .layer(DefaultBodyLimit::max(1024));
    let mut body = Vec::new();
    body.extend_from_slice(b"--test-boundary\r\n");
    body.extend_from_slice(b"Content-Disposition: form-data; name=\"file\"; filename=\"big.bin\"\r\n");
    body.extend_from_slice(b"Content-Type: application/octet-stream\r\n");
    body.extend_from_slice(b"\r\n");
    body.extend_from_slice(&vec![b'x'; 5000]);
    body.extend_from_slice(b"\r\n--test-boundary--\r\n");
    let response = app
        .oneshot(
            Request::builder()
                .method("POST")
                .uri("/upload")
                .header(
                    "Content-Type",
                    "multipart/form-data; boundary=test-boundary",
                )
                .body(Body::from(body))
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::PAYLOAD_TOO_LARGE);
}

Run it with cargo test. It passes when the 5,000 byte field against a 1,024 byte limit returns 413. The handler returns the MultipartError directly instead of unwrapping it, because an unwrap() on a failed read panics the test rather than producing a response. A live run of this test passed.

Final Complete Example

Here is the whole page in one program, the upload route with a 5 megabyte cap from the layer, the default limit disabled so the layer is the only cap, and the JSON error helper for the extractor's own errors:

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

const MAX_UPLOAD_BYTES: usize = 5 * 1024 * 1024;

fn multipart_error_response(err: MultipartError) -> Response {
    (err.status(), Json(json!({ "error": err.body_text() }))).into_response()
}

async fn upload(mut multipart: Multipart) -> Result<Json<Value>, Response> {
    let mut fields = Vec::new();
    while let Some(field) = multipart
        .next_field()
        .await
        .map_err(multipart_error_response)?
    {
        let name = field.name().map(|s| s.to_string());
        let file_name = field.file_name().map(|s| s.to_string());
        let content_type = field.content_type().map(|s| s.to_string());
        let data = field
            .bytes()
            .await
            .map_err(multipart_error_response)?;
        fields.push(json!({
            "name": name,
            "file_name": file_name,
            "content_type": content_type,
            "size": data.len(),
        }));
    }
    Ok(Json(json!({ "fields": fields })))
}

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

    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();
}
Cargo.toml
[package]
name = "upload-demo"
version = "0.1.0"
edition = "2021"

[dependencies]
axum = { version = "0.8", features = ["multipart"] }
tokio = { version = "1", features = ["full"] }
serde_json = "1"
tower-http = { version = "0.7", features = ["limit"] }

Run it and try three files. A small file returns 200 with its field report. A 3 megabyte file returns 200, because the cap is 5 megabytes. A 6 megabyte file returns 413 with the body length limit exceeded, because the layer is the cap and the layer's message is the one the client sees. The handler never runs for the 6 megabyte file, and no large allocation happens.

Summary

There are two limits, and they guard two different doors, and that split is the whole point of this page. The default 2 megabyte cap guards the extractors, and it answers through the multipart error with a 413 and the message Request payload is too large. The layer guards the whole router, and it answers before the handler with a 413 and the message length limit exceeded. The right setup is rarely one or the other alone. It is the default left in place for small routes, raised or replaced by the layer where a route genuinely needs more room, and never disabled without a replacement. The habit that ties it together is testing the boundary itself, one body just under the limit and one just over it, because a limit that has never been tripped is a limit you are only guessing about. That test, run once per route, is what turns a number in a layer call into a protection you can trust.