FAQ - Help and questions

How do I compress responses with gzip in axum?

#axum#compression#tower-http#performancepublished 0 replies0 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail

Short answer

Add tower-http CompressionLayer with the compression-gzip feature. It compresses a response only when the request sends Accept-Encoding with gzip, and it sets Content-Encoding. Text such as HTML and JSON usually shrinks; images and archives that are already compressed gain little.

Checked with rustc 1.93.0, axum 0.8.9, tokio 1.54.1, tower 0.5.3, Windows 11; handlers called in-process with tower's oneshot; tower-http 0.6.11

Frequently asked question, written and answered by the Ruststudio team. Replies are open: corrections are welcome.

#1

Answer#

CompressionLayer::new() negotiates with the client through the standard Accept-Encoding header, so clients that do not ask for gzip still get the plain body.

src/main.rsrust
use axum::{body::{to_bytes, Body}, http::{header, Request}, routing::get, Router};
use tower::ServiceExt;
use tower_http::compression::CompressionLayer;

async fn page() -> String { "<p>hello compression</p>".repeat(100) }

#[tokio::main]
async fn main() {
    let app = Router::new().route("/", get(page)).layer(CompressionLayer::new());
    for accept in [None, Some("gzip")] {
        let mut b = Request::get("/");
        if let Some(a) = accept { b = b.header(header::ACCEPT_ENCODING, a); }
        let res = app.clone().oneshot(b.body(Body::empty()).unwrap()).await.unwrap();
        let enc = res.headers().get(header::CONTENT_ENCODING).cloned();
        let vary = res.headers().get(header::VARY).cloned();
        let body = to_bytes(res.into_body(), usize::MAX).await.unwrap();
        println!("accept-encoding {accept:?} -> content-encoding {enc:?}, vary {vary:?}, {} body bytes", body.len());
    }
}
text
accept-encoding None -> content-encoding None, vary Some("accept-encoding"), 2400 body bytes
accept-encoding Some("gzip") -> content-encoding Some("gzip"), vary Some("accept-encoding"), 67 body bytes

The page is 2400 bytes of repeated text, so it compresses extremely well here; real pages shrink by less. The numbers are from this one repeated string only and say nothing about your pages: measure your own responses.

Cargo.tomltoml
tower-http = { version = "0.6.11", features = ["compression-gzip"] }

Vary: accept-encoding is in the response so that caches keep the plain and compressed versions apart.

Common mistakes#

  • Compressing files that are already compressed (JPEG, PNG, ZIP): CPU spent for little gain.
  • Forgetting to enable the feature of the algorithm you want; without it the layer has nothing to offer.

Does the layer compress static files from ServeDir?#

Both are tower services, so the layer can be added around them; the thread on static files shows the file service.

Sources#

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    No replies yet