CompressionLayer for Automatic Response Compression in Axum

Learn how to compress HTTP response bodies in Axum using tower-http CompressionLayer, including gzip, brotli, deflate, and zstd configuration

A typical HTML page or JSON API response can easily be tens of kilobytes. Every one of those bytes travels across the network from your server to the browser that requested it. On a fast home connection that might not feel like much, but for mobile users on limited data plans, people in areas with slower infrastructure, or applications serving thousands of requests per second, those bytes add up quickly. Compression shrinks the response body before it leaves your server. Text formats like HTML, JSON, CSS, and JavaScript compress well because they contain lots of repeated patterns, words, indentation, keys in a JSON object, or repeated CSS properties. The browser decompresses the response automatically before your JavaScript code ever sees it, so the whole process is invisible to the end user. Axum does not build compression into the framework itself. It uses the tower-http crate, which provides a ready made piece of middleware called CompressionLayer. This page covers everything you need to add compression to an Axum application, from the simplest setup to custom compression rules.

A Complete Gzip Example

You already know how to add a layer to a router. The pattern for CompressionLayer is the same as any other tower-http layer. You create it with new(), configure it if you want, and pass it to .layer(). Start by adding the dependency to Cargo.toml. The key detail is the feature flag. Tower-http ships compression support behind cargo features, so you must enable at least one. The most common choice is gzip.

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

[dependencies]
axum = "=0.8.9"
tokio = { version = "=1.54.1", features = ["full"] }
tower-http = { version = "=0.7.1", features = ["compression-gzip"] }

Now build the application, in src/main.rs.

src/main.rs
use axum::{routing::get, Router};
use tower_http::compression::CompressionLayer;

#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/", get(handler))
        .layer(CompressionLayer::new());

    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

async fn handler() -> String {
    "Hello, World! ".repeat(1000)
}

This handler returns a string of about 14,000 bytes, the phrase Hello, World! repeated 1000 times. That size is deliberate. A response of only a few bytes is too small for compression to make sense, and CompressionLayer skips it. A large repetitive string shows the effect clearly. When you run this with cargo run and visit http://127.0.0.1:3000 in a browser, the page displays the repeated greeting. Behind the scenes, the browser sends a header telling your server it can accept compressed responses, your server compresses the string, and the browser decompresses it before rendering. You notice nothing because the process is completely transparent.

No feature, no compression:

If you forget to add the compression-gzip feature to tower-http, the code will not compile. The CompressionLayer type itself only exists when at least one compression feature is enabled. This is a compile time error, which is helpful. You notice immediately rather than discovering at runtime that nothing was compressed.

Verifying Compression Works

A browser hides the compression details from you, which is good for users but unhelpful when you are learning. To see compression happening, use curl from the command line. The Accept-Encoding header is how a client tells the server which compression formats it can undo.

curl -i -H "Accept-Encoding: gzip" http://127.0.0.1:3000/

The -i flag prints the response headers as well as the body. The response includes a line like this.

content-encoding: gzip

That content-encoding header is the server way of saying it compressed this response using gzip. Without the Accept-Encoding: gzip header, or if you request a format the server does not support, the response will not include content-encoding at all, and the body arrives uncompressed.

You can also compare the actual byte counts. The numbers below were measured by running the example program above with a test client. The uncompressed response is 14,000 bytes. With gzip it comes back as 81 bytes. The first number is the raw size, the second is the compressed size, and the difference is why compression matters for repetitive text.

You are up and running:

If you see content-encoding: gzip in the response headers and the downloaded byte count is smaller with the Accept-Encoding header than without it, your compression setup is working correctly. This is the confirmation point for the basic example. If there is no content-encoding header, check the feature flag first, then check that the response is large enough to pass the 32 byte minimum.

How Accept-Encoding Negotiation Works

When you add CompressionLayer to a router, you are inserting a step between your handler response and the network. Before the response leaves your server, the middleware checks whether the client asked for compression and whether the response is a good candidate for it.

The negotiation happens through two HTTP headers. The request header Accept-Encoding is sent by the client and lists the compression formats it understands, each optionally with a quality value, written as q=, stating how much the client prefers it. A browser might send Accept-Encoding: gzip, deflate, br, zstd, meaning it can decompress gzip, deflate, brotli, or zstd. The response header Content-Encoding is then set by the server to say which format it actually used.

The middleware reads the Accept-Encoding header, checks whether any of the enabled algorithms appear in it, and if so, wraps the response body in a compressing stream. The original body streams through the compressor chunk by chunk, so your entire response does not need to be buffered in memory first. The Content-Encoding header is set to the chosen algorithm, and the compressed body replaces the original on its way out. If the client does not send an Accept-Encoding header at all, or none of your enabled algorithms are listed, the middleware passes the response through completely untouched. No header is added, and the body is sent as it is.

How the Encoding Is Chosen

The choice of encoding follows two rules, and the order matters. The q-value comes first. An encoding with a higher q-value wins over one with a lower q-value, no matter where each appears in the header. When two encodings have the same q-value, tower-http breaks the tie with its own built-in preference order, zstd first, then brotli, then gzip, then deflate. The order the client listed them in does not matter. That was verified at runtime with the 14,000 byte response and all four algorithms enabled.

Accept-Encoding sentEncoding chosenCompressed size
gzipgzip81 bytes
deflate, gzipgzip81 bytes
gzip, brbr28 bytes
gzip;q=0.5, deflate;q=0.9deflate69 bytes
zstd, gzipzstd31 bytes
identitynone14,000 bytes

The second row is the surprising one. Deflate is listed first and gzip second, and gzip still wins, because the tie is broken by tower-http preference, not by client order. The fourth row shows the q-value rule. Gzip is listed first but with q=0.5, while deflate has q=0.9, so deflate wins. The last row shows that identity, which means no compression, is respected as a real choice. A client that only accepts identity receives the full 14,000 bytes.

Enabling Brotli, Deflate, and Zstd

Gzip is the usual starting point because it is universally supported and fast enough for most use cases. But it is not the only option. Each compression algorithm trades off speed, compression ratio, and client support differently. Brotli often produces smaller files than gzip for text content, at the cost of being slower to compress. It is widely supported by modern browsers. Deflate is the raw DEFLATE format that gzip itself is built on, gzip is DEFLATE plus a header and checksum, so the two compress near identically, and gzip is simply the one browsers universally advertise. Zstd is a newer algorithm that can achieve better ratios and faster decompression, though browser support is less universal than gzip or brotli.

To enable multiple algorithms, add the corresponding features to Cargo.toml. Each algorithm has its own feature flag.

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

[dependencies]
axum = "=0.8.9"
tokio = { version = "=1.54.1", features = ["full"] }
tower-http = { version = "=0.7.1", features = [
    "compression-gzip",
    "compression-br",
    "compression-deflate",
    "compression-zstd",
] }

Then use the plain layer. No extra calls are needed to switch the algorithms on. Every algorithm whose feature flag is enabled is on by default, so with all four features enabled, CompressionLayer::new() already compresses with gzip, brotli, deflate, and zstd.

src/main.rs
use axum::{routing::get, Router};
use tower_http::compression::CompressionLayer;

#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/", get(handler))
        .layer(CompressionLayer::new());

    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

async fn handler() -> String {
    "Hello, World! ".repeat(1000)
}

When a request arrives with Accept-Encoding: br, the middleware picks brotli. When several enabled algorithms are offered, the choice follows the q-value and preference rules from the previous section. The feature flag is what makes an algorithm available, and it is also what turns it on. The .br(true), .deflate(true), and .zstd(true) calls exist to switch an algorithm back on after you turned it off, or to make the choice explicit in code. They are not needed to enable an algorithm for the first time. Each of those calls only exists when the matching feature flag is enabled in Cargo.toml. Calling .br(true) without the compression-br feature is a compile error, because the method itself is not compiled in, which is the same helpful failure as the missing feature flag.

You can also disable gzip entirely if you prefer brotli as the only option. Replace the layer construction in the program above with this one.

src/main.rs
let layer = CompressionLayer::new().gzip(false);

The .gzip(false) call switches gzip off, and brotli stays on because its feature flag enables it. This approach is useful when you control both the server and all its clients, for example an internal API consumed only by your own mobile app, where you know brotli support is guaranteed. For a public facing API, keep gzip enabled alongside brotli so every browser gets some form of compression. A client that does not send Accept-Encoding: br receives uncompressed responses if gzip is off, and that is a silent loss of the benefit.

Shorthand with compression-full:

Instead of listing each algorithm individually, you can use the compression-full feature to enable all four at once, with features = ["compression-full"]. This is convenient for development but may pull in dependencies you do not need in production. With compression-full, CompressionLayer::new() alone enables all four algorithms. No .br(true), .deflate(true), or .zstd(true) calls are needed.

What CompressionLayer Skips by Default

Not every response benefits from compression. Compressing a tiny response can actually make it larger, because the compressed output still needs a header and a checksum. Compressing already compressed content like JPEG images wastes CPU time for almost no size reduction, because those formats are already dense. CompressionLayer uses a built-in set of rules called the DefaultPredicate to decide whether a response should be compressed. A predicate is simply a rule, a function that looks at a response and returns yes, compress this, or no, skip it.

The default predicate is exactly three checks combined.

  • Size. The response body must be at least 32 bytes. A response of exactly 32 bytes is compressed, because the check is size greater than or equal to 32, not greater than 32. Smaller responses pass through uncompressed, because compression overhead would erase any benefit. That boundary was verified at runtime. A 32 byte response came back with content-encoding: gzip and a compressed size of 23 bytes, while a 31 byte response came back with no content-encoding header at all.
  • Not gRPC. Responses with Content-Type: application/grpc are skipped, because gRPC has its own compression scheme.
  • Not images or server-sent events. Responses with an image content type, except image/svg+xml, which is text and compresses well, and responses with Content-Type: text/event-stream are skipped.

Note what is not in that list. Video, audio, and ZIP archives are not skipped by default. An already compressed format only escapes compression if it happens to be an image, gRPC, or a server-sent event stream. If you serve video or ZIP files through CompressionLayer, check whether they are actually shrinking before assuming the middleware handles it.

Two checks you might expect to find in the predicate live elsewhere, because the predicate only ever sees the response. Its should_compress method receives a reference to the response and cannot see the request at all. The already encoded check, never recompress a response that already has a Content-Encoding header, and likewise responses with a Content-Range header, lives in the Compression service itself. Accept-Encoding negotiation happens separately, when the encoding is chosen. Both still protect you. They are just not predicate rules, and no custom predicate can remove them.

Raising the Compression Threshold with SizeAbove

The default 32 byte minimum is sensible for most applications, but sometimes you want more control. If your API mostly returns small JSON objects and you only want compression for large payloads, you can raise the threshold. Tower-http provides a built-in predicate called SizeAbove for exactly this purpose. But be careful about what it replaces. SizeAbove is a standalone, size only check. Calling .compress_when(SizeAbove::new(256)) swaps out the entire DefaultPredicate, and with it the gRPC, image, and server-sent event exclusions. They do not survive inside SizeAbove.

src/main.rs
use axum::{routing::get, Router};
use tower_http::compression::{predicate::SizeAbove, CompressionLayer};

#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/", get(handler))
        .layer(
            CompressionLayer::new()
                .compress_when(SizeAbove::new(256)),
        );

    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

async fn handler() -> String {
    "Hello, World! ".repeat(1000)
}

The .compress_when() method replaces the entire predicate, not just one rule. SizeAbove::new(256) means only compress responses of at least 256 bytes. That sounds like a small change, and it is, but the side effect is real. It was verified at runtime that a large image response, which the default predicate skips, is compressed once SizeAbove replaces the predicate. The default layer answered the image request with no content-encoding header, and the SizeAbove layer answered the same request with content-encoding: gzip. The image exclusion was lost the moment the predicate was swapped.

To raise the threshold and keep the default exclusions, re-add them explicitly with .and(). This is the pattern tower-http own documentation shows. The .and() method combines two predicates so that a response must pass both to be compressed. Use this layer in place of the .compress_when(SizeAbove::new(256)) line in the program above.

src/main.rs
use tower_http::compression::predicate::{NotForContentType, Predicate, SizeAbove};

let predicate = SizeAbove::new(256)
    .and(NotForContentType::GRPC)
    .and(NotForContentType::IMAGES)
    .and(NotForContentType::SSE);

let layer = CompressionLayer::new().compress_when(predicate);

NotForContentType is a predicate that refuses to compress responses with a given content type. Its three constants are GRPC for application/grpc, IMAGES for any image type, and SSE for text/event-stream. You can also build your own with NotForContentType::new("application/json") or the const form NotForContentType::const_new("application/json"), which refuses JSON responses. The already encoded and Accept-Encoding protections are not lost by this swap. As noted above, they live in the Compression service and in encoding negotiation, not in the predicate.

Replacing the predicate replaces everything:

When you call .compress_when(), you are swapping out the full set of default rules for whatever predicate you provide. SizeAbove does not preserve the default checks internally, it is size only. If you write your own predicate from scratch, you are responsible for everything the default predicate did, including the size floor and the gRPC, image, and server-sent event exclusions. The .and() combination shown above is how you keep them.

Writing a Custom Predicate

Built-in predicates like SizeAbove cover common needs, but there are situations where you want a rule the library does not ship. For example, you might want to compress only responses with a specific content type, regardless of size. Writing a custom predicate gives you that control.

A predicate in tower-http is any type that implements the Predicate trait. That trait has a single method, should_compress, which receives a reference to the response and returns a boolean, true for compress and false for skip. Here is a predicate that compresses only JSON responses.

src/main.rs
use axum::{routing::get, Router};
use axum::http::{header::CONTENT_TYPE, Response};
use tower_http::compression::{CompressionLayer, Predicate};

#[derive(Clone)]
struct CompressJsonOnly;

impl Predicate for CompressJsonOnly {
    fn should_compress<B>(&self, response: &Response<B>) -> bool {
        response
            .headers()
            .get(CONTENT_TYPE)
            .and_then(|value| value.to_str().ok())
            .map(|content_type| content_type.starts_with("application/json"))
            .unwrap_or(false)
    }
}

#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/", get(handler))
        .layer(
            CompressionLayer::new()
                .compress_when(CompressJsonOnly),
        );

    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

async fn handler() -> String {
    "Hello, World! ".repeat(1000)
}

The should_compress method reads the Content-Type header from the response. If the header value starts with application/json, it returns true. Otherwise it returns false. The .unwrap_or(false) handles the case where the header is missing or contains characters that are not valid text. In both cases, the response is not compressed. Note the imports. The Response type and the CONTENT_TYPE constant come from axum::http, which re-exports the http crate types. Writing use http::... instead would fail to compile unless your project declares http as its own dependency, and there is no reason to add it when axum already provides the same types.

This custom predicate does not check the response size or the content type beyond JSON. The compression middleware itself still checks Accept-Encoding and the existing Content-Encoding header before calling the predicate, so those protections remain. They live outside the predicate and no custom predicate can bypass them. But the size floor and the gRPC, image, and server-sent event exclusions are now entirely your responsibility. If you want those too, add them explicitly to your predicate, for example by combining it with SizeAbove and NotForContentType using .and().

The #[derive(Clone)] on the struct is required because the layer needs to be cloned when it wraps each route. A predicate that cannot be cloned cannot be used as a layer, and the compiler will say so.

Choosing a Compression Level

Compression involves a trade-off. More aggressive compression produces smaller output but takes more CPU time. Less aggressive compression is faster but leaves the response larger. If your server is under heavy CPU load and serving huge volumes of traffic, switching to a faster compression level can reduce latency. If you serve mostly static content to users on slow connections, a higher compression level shrinks bandwidth costs.

CompressionLayer exposes a .quality() method that controls this trade-off. The level type is tower-http own tower_http::compression::CompressionLevel, a small enum with the variants Fastest, Best, Default, and Precise(i32). It is not the Level type from the async-compression crate, and no async-compression dependency is needed to use it. Passing an async_compression::Level fails to compile with a type mismatch, which is the error the old documentation ran into. Set the level on the layer.

src/main.rs
use axum::{routing::get, Router};
use tower_http::compression::{CompressionLayer, CompressionLevel};

#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/", get(handler))
        .layer(
            CompressionLayer::new()
                .quality(CompressionLevel::Fastest),
        );

    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

async fn handler() -> String {
    "Hello, World! ".repeat(1000)
}

CompressionLevel::Fastest uses the fastest compression setting, producing larger output but consuming less CPU. CompressionLevel::Best does the opposite, maximum compression ratio at the cost of speed. The default is CompressionLevel::Default, which sits in the middle and is defined by the selected algorithm. There is also CompressionLevel::Precise(i32) for fine-grained control, where the meaning of the number depends on the algorithm, and values are clamped to the algorithm maximum.

For most Axum applications, the default level is a good starting point. Adjust it only if you have a specific reason, a server under heavy CPU load, a target audience on very slow connections, or a measured bandwidth cost that justifies the trade-off. Changing the level without measuring is guessing, and the default is the setting the library authors chose for the common case.

What Compression Does Not Do

CompressionLayer only acts on responses, and only on the body. It does not compress request bodies. If a client sends you a large compressed request body, that is the job of DecompressionLayer, a separate layer behind the decompression feature flags. It also does not make a slow handler fast. A handler that waits five seconds on a database still waits five seconds. Compression only shrinks the bytes that leave the server afterwards.

The body streams through the compressor chunk by chunk, which means the response is not buffered in memory first. That is good for large responses, and it has a consequence worth knowing. A timeout layer measures the time until the inner service produces a response, meaning the status line and headers. Compression happens afterwards, as the body streams out. Neither order of timeout and compression layers times the body streaming, because the timeout has already finished its measurement by then. If a slow body stream needs a limit, tower-http provides separate response body timeout layers for that job.

Compression also never recompresses a response that already has a Content-Encoding header. That check lives in the Compression service itself, not in the predicate, so no custom predicate can remove or bypass it. If another middleware or your own handler sets a Content-Encoding header and you then apply CompressionLayer on top, the layer sees the existing header and passes the response through untouched. The protection is always on. What a custom predicate can break is the size floor and the content-type exclusions, which are yours to re-add.

A custom predicate can compress already compressed content:

The already encoded check protects you, but the content-type exclusions do not survive a predicate swap. If your custom predicate compresses image or video responses, the result is a slight size increase and wasted server CPU, because those formats are already dense. Always combine a custom predicate with SizeAbove and NotForContentType using .and() unless you have a specific reason to compress everything the predicate allows.

Common CompressionLayer Mistakes

Forgetting to enable the cargo feature is the most immediate mistake. The code does not compile without at least one of compression-gzip, compression-br, compression-deflate, or compression-zstd. The error message will say something about CompressionLayer not being found, which can confuse beginners who assume the type is always available. The fix is the feature flag in Cargo.toml.

Testing with a tiny response is another frequent source of confusion. If your handler returns a short string like OK, CompressionLayer skips it because the 32 byte threshold is not met. You will see no content-encoding header and conclude compression is broken, when in reality everything is working as designed. Always test with a response at least a few hundred bytes long.

Expecting images or other binary files to shrink is a misunderstanding of how compression works. A JPEG or PNG file is already compressed, and running it through gzip again wastes CPU without making it meaningfully smaller. The default predicate skips images, except SVG, for that reason. But only images. Video, audio, and ZIP responses are not skipped by default, so if you serve those through CompressionLayer, check whether they are actually shrinking before assuming the middleware handles it.

Using the wrong level type is a compile error that looks confusing. The .quality() method takes tower_http::compression::CompressionLevel, not async_compression::Level. If the compiler reports a type mismatch on .quality(), check the import. The correct import is use tower_http::compression::CompressionLevel, and no extra dependency is needed.

Assuming all clients support brotli is a trap. If you disable gzip and enable only brotli, then a client that does not send Accept-Encoding: br receives uncompressed responses. For public facing APIs, keep gzip enabled alongside brotli so every browser gets some form of compression.

Applying CompressionLayer after other middleware that read the response body can also cause subtle problems. Middleware layers in Axum run in a specific order, and the outermost layer sees the response first on the way out. If a logging layer inspects the response body, it might observe the compressed version rather than the original. The exact behaviour depends on layer ordering, so when you combine compression with other layers, test the full pipeline end to end rather than testing each layer alone.

Summary

Compression is one of the simplest and highest impact optimisations you can add to an Axum application. The amount of code you write is minimal, one dependency, one feature flag, and one .layer() call. The understanding that makes it work well is knowing where each rule lives. The predicate decides only whether the response is big enough, at least 32 bytes by default, and whether it is gRPC, an image, or a server-sent event. Whether the client supports the algorithm is decided during Accept-Encoding negotiation, by q-value first and by tower-http built-in preference second. Whether the response is already encoded is checked by the Compression service itself, and no predicate can change that.

The decision framework to carry forward is small. Start with CompressionLayer::new() and the gzip feature, and test with a large text response. Add brotli and zstd when your clients support them, keeping gzip on for everyone else. Raise the size threshold with SizeAbove only when you re-add the default exclusions with .and(). Write a custom predicate only when the built-in ones cannot express your rule, and combine it with the defaults the same way. And leave the quality at Default until you have measured a reason to change it. Compression rewards the application that enables it early and tunes it late, not the one that configures every option before the first request.