日本語

How to Gzip Responses from Bun.serve

​​Bun​gzip,TypeScript

When you return JSON or HTML from Bun.serve, you can compress it with Bun.gzipSync() and add the Content-Encoding: gzip header. The client (curl, Bun's fetch, and so on) then decompresses it on receipt. This helps reduce the transfer size of API responses and pages, so they display faster even on slow mobile connections.

I tested this in an environment running Ubuntu 24.04 and Bun 1.4.4. I built a server that returns about 150,000 bytes of JSON. With gzip, the response was 17,961 bytes, which is 12.4% of the original size. However, compressing on every request reduced the number of requests the server could handle per second to about one-seventh.

Note

The test environment was Ubuntu 24.04 (x86_64, 4 CPUs) with Bun 1.4.4. Requests were sent with curl, Bun's fetch, and Python's http.client. I did not test rendering in a browser, HTTPS, compression with brotli or zstd, or a setup where a reverse proxy such as nginx handles compression. For the official documentation, I checked the source files at the tag used for testing (bun-v1.4.4) on GitHub, and the links point there.

Bun.serve does not compress by default

First, I checked what happens when you do nothing. I sent a request with Accept-Encoding: gzip to the route /plain, which returns a JSON list of 2,000 products (145,254 bytes) as-is in a Response.

text
$ curl -s -o /dev/null -D - -H 'Accept-Encoding: gzip' localhost:3000/plain
HTTP/1.1 200 OK
Content-Type: application/json
Content-Length: 145254

Even though the client said it could accept gzip, no Content-Encoding header was added, and the full 145,254 bytes came back uncompressed. In the official Bun.serve documentation, the only compression mentioned is for WebSocket messages (perMessageDeflate). I found no setting for compressing HTTP responses. You need to compress HTTP responses in your own code.

Check Accept-Encoding, then compress with gzipSync and return

On the server side, do the following three things:

  • Check whether the request's Accept-Encoding includes gzip.
  • If it does, compress the body with Bun.gzipSync() and add Content-Encoding: gzip.
  • In both cases, add Vary: Accept-Encoding.

Vary: Accept-Encoding tells the client that the response content depends on the request's Accept-Encoding. According to the MDN explanation of Vary, caches store separate responses for each value of the headers listed in Vary. The guidance is that responses for the same URL should carry the same Vary header whether or not they are compressed, so I added it to both.

Below is the part of the server.ts used for testing that relates to /api/items.

ts
import { makeItems } from "./data.ts";

const json = JSON.stringify(makeItems(2000));

// Check whether Accept-Encoding includes gzip without q=0 (meaning "not acceptable")
function acceptsGzip(req: Request): boolean {
  const header = req.headers.get("accept-encoding") ?? "";
  return header.split(",").some((part) => {
    const [name, ...params] = part.split(";").map((s) => s.trim());
    if (name.toLowerCase() !== "gzip") return false;
    const q = params.find((p) => p.startsWith("q="));
    return q === undefined || Number(q.slice(2)) > 0;
  });
}

function gzipResponse(req: Request, body: string, contentType: string): Response {
  const headers = new Headers({
    "Content-Type": contentType,
    "Vary": "Accept-Encoding",
  });
  if (!acceptsGzip(req)) {
    return new Response(body, { headers });
  }
  headers.set("Content-Encoding", "gzip");
  return new Response(Bun.gzipSync(body), { headers });
}

const server = Bun.serve({
  port: 3000,
  routes: {
    "/api/items": (req) => gzipResponse(req, json, "application/json"),
  },
});

Each Accept-Encoding entry can carry a weight (quality value) written as ;q=. The MDN explanation of Accept-Encoding gives identity;q=0 as an example of explicitly forbidding the uncompressed form. So I made the code treat gzip;q=0 as "do not use gzip." If you decide only with header.includes("gzip"), this case would still get compressed. Bun.gzipSync() accepts a string as well as a Uint8Array (type definition).

I started the server with bun server.ts and sent requests while changing Accept-Encoding. (In the output below, the Date header is omitted.)

text
$ curl -s -o /dev/null -D - -H 'Accept-Encoding: gzip' localhost:3000/api/items
HTTP/1.1 200 OK
Content-Type: application/json
Vary: Accept-Encoding
Content-Encoding: gzip
Content-Length: 17961

$ curl -s -o /dev/null -D - localhost:3000/api/items
HTTP/1.1 200 OK
Content-Type: application/json
Vary: Accept-Encoding
Content-Length: 145254

$ curl -s -o /dev/null -D - -H 'Accept-Encoding: gzip;q=0, identity' localhost:3000/api/items
HTTP/1.1 200 OK
Content-Type: application/json
Vary: Accept-Encoding
Content-Length: 145254

The response was compressed to 17,961 bytes only when the client accepted gzip. Bun.serve set Content-Length to the compressed size. When the header was written in uppercase, as in Accept-Encoding: br, GZIP, the response was also compressed.

When you receive the response with curl --compressed, curl decompresses it for you. I also confirmed that the decompressed content has the same SHA-256 hash as /plain, so the content was unchanged.

text
$ curl -s --compressed localhost:3000/api/items | sha256sum
47d12f37328ed6a778851b70f9c2587e8af2d68dc6c7d98dbf253382909f4d7a  -
$ curl -s localhost:3000/plain | sha256sum
47d12f37328ed6a778851b70f9c2587e8af2d68dc6c7d98dbf253382909f4d7a  -

Bun's fetch decompresses automatically

Here is how it looks when you call this server from Bun's fetch, such as in a test. As the official fetch documentation explains, fetch decompresses gzip by default, and passing decompress: false turns that off.

ts
const a = await fetch("http://localhost:3000/api/items");
const textA = await a.text();
console.log("decompress: true  ->", a.headers.get("content-encoding"), a.headers.get("content-length"), textA.length, textA.slice(0, 30));

const b = await fetch("http://localhost:3000/api/items", {
  headers: { "Accept-Encoding": "gzip" },
  decompress: false,
});
const bytesB = new Uint8Array(await b.arrayBuffer());
console.log("decompress: false ->", b.headers.get("content-encoding"), b.headers.get("content-length"), bytesB.length, [...bytesB.slice(0, 3)].map((x) => x.toString(16)).join(" "));
console.log("gunzipSync で戻すと同じ:", new TextDecoder().decode(Bun.gunzipSync(bytesB)) === textA);
text
decompress: true  -> gzip 17961 145254 [{"id":1,"name":"Item 1","colo
decompress: false -> gzip 17961 17961 1f 8b 8
gunzipSync で戻すと同じ: true

With the default settings, the headers still show content-encoding: gzip and content-length: 17961, but the body is decompressed to 145,254 characters. With decompress: false, I received the 17,961 bytes as they were, starting with 1f 8b, which is the gzip magic number.

During testing, when I passed only decompress: false without setting Accept-Encoding, the server returned the uncompressed 145,254 bytes. If you want to receive the compressed data as-is, you also need to set Accept-Encoding: gzip yourself.

Compressing on every request lowers the number of requests you can handle

Compression uses CPU. If the content never changes, you can compress it once at startup and skip compressing on each request. I added a route for this to server.ts.

ts
// If the content never changes, compress it once at startup
const jsonGz = Bun.gzipSync(json);

// inside routes
"/api/items-cached": (req) => {
  if (!acceptsGzip(req)) {
    return new Response(json, {
      headers: { "Content-Type": "application/json", "Vary": "Accept-Encoding" },
    });
  }
  return new Response(jsonGz, {
    headers: {
      "Content-Type": "application/json",
      "Vary": "Accept-Encoding",
      "Content-Encoding": "gzip",
    },
  });
},

From the same machine, I used Bun's fetch to send a total of 5,000 requests, 10 at a time, and measured how many responses per second the server returned. I ran each measurement three times (with Accept-Encoding: gzip and decompress: false).

Requests per second: 7,049 without compression, 1,074 when compressing with gzipSync on every request, and 26,700 when compressing at startup. Size per response: 145,254 bytes uncompressed, and 17,961 bytes for the two compressed versions
Requests per second (median of 3 runs) and size per response
Response method Requests per second (3 runs) Size per response
No compression (/plain) 7,049 / 7,115 / 6,965 145,254 bytes
gzipSync on every request (/api/items) 1,074 / 1,081 / 1,062 17,961 bytes
Compressed at startup (/api/items-cached) 26,700 / 27,547 / 24,170 17,961 bytes

When I compressed with gzipSync on every request, throughput dropped to about one-seventh of the uncompressed case. When I compressed once at startup, the server handled about 3.8 times as many requests as the uncompressed case. Note that these measurements were sent within the same machine, so network speed does not affect the results.

Point

For JSON or files whose content does not change, compress them once at startup (or when they are created), and return the compressed version. Only compress on the fly for content that is generated per request.

Adjust size and time with the compression level

The level option in the second argument of Bun.gzipSync() sets the compression strength, from 0 to 9. If you omit it, the level is 6 (official Bun.gzipSync() documentation). I compressed the same JSON 200 times at each level and measured the results.

ts
import { makeItems } from "./data.ts";
const json = JSON.stringify(makeItems(2000));
const input = new TextEncoder().encode(json);
console.log(`input: ${input.length} bytes`);
const RUNS = 200;
for (const level of [1, 3, 6, 9] as const) {
  for (let i = 0; i < 20; i++) Bun.gzipSync(input, { level }); // warm-up
  const t0 = performance.now();
  let size = 0;
  for (let i = 0; i < RUNS; i++) size = Bun.gzipSync(input, { level }).length;
  const ms = (performance.now() - t0) / RUNS;
  console.log(`level ${level}: ${size} bytes (${((size / input.length) * 100).toFixed(1)}%)  ${ms.toFixed(3)} ms/回`);
}
text
input: 145254 bytes
level 1: 26884 bytes (18.5%)  0.158 ms/回
level 3: 17904 bytes (12.3%)  0.323 ms/回
level 6: 17961 bytes (12.4%)  0.910 ms/回
level 9: 16565 bytes (11.4%)  2.852 ms/回

With this data, level 3 gave almost the same size as the default level 6, and it took about one-third of the time. Level 9 produced about 1,400 bytes less than level 6, but took about three times as long. If you compress on every request, a lower level makes sense. If you compress once at startup, level 9 may be a good choice. These results come from this specific data, so measure with your actual responses before deciding.

Short responses get bigger when compressed

When I returned {"ok":true} (11 bytes) through the same gzipResponse(), the result was 31 bytes.

text
$ curl -s -o /dev/null -D - -H 'Accept-Encoding: gzip' localhost:3000/small
HTTP/1.1 200 OK
Content-Type: application/json
Vary: Accept-Encoding
Content-Encoding: gzip
Content-Length: 31

In the test environment, Bun.gzipSync("") produced 20 bytes even for empty input. For short responses such as {"ok":true}, sending them uncompressed is smaller.

When compressing a stream, flush the output partway

You cannot compress a response that is built and sent piece by piece (a ReadableStream) with gzipSync. Bun supports the Web standard CompressionStream (official compatibility table), so I tried that first. The route writes five lines, one every 100 ms.

ts
"/stream": (req) => {
  const source = new ReadableStream({
    async start(controller) {
      for (let i = 1; i <= 5; i++) {
        controller.enqueue(new TextEncoder().encode(`line ${i}: ${"x".repeat(1000)}\n`));
        await Bun.sleep(100);
      }
      controller.close();
    },
  });
  const headers = new Headers({ "Content-Type": "text/plain", "Vary": "Accept-Encoding" });
  if (!acceptsGzip(req)) return new Response(source, { headers });
  headers.set("Content-Encoding", "gzip");
  return new Response(source.pipeThrough(new CompressionStream("gzip")), { headers });
},

The response was sent with Transfer-Encoding: chunked instead of Content-Length. The uncompressed body was 5,045 bytes, and with gzip it was 76 bytes. However, when I used Python's http.client to record when each piece of compressed data arrived, the result was as follows.

text
$ python3 stream_timing.py /stream
     1 ms  10 bytes
   502 ms  66 bytes

Only 10 bytes arrived first, and the rest arrived all at once 502 ms later, after the server had finished sending all five lines. Even though the server wrote one line every 100 ms, the client received nothing until all five lines had been sent. This is a problem for responses such as Server-Sent Events, where you want to display data as soon as it arrives.

As the MDN explanation of CompressionStream() states, CompressionStream only accepts a compression format and has no option to flush output partway. So I used createGzip() from node:zlib instead. The Node.js zlib documentation explains that flushing a compression stream outputs as much data as is available at that point, though it can reduce the compression ratio. It also notes that the default flush value is Z_NO_FLUSH (no flushing). Here I passed flush: constants.Z_SYNC_FLUSH so that the stream was flushed on each write.

ts
import { createGzip, constants } from "node:zlib";
import { Readable } from "node:stream";

// inside routes
"/stream-flush": (req) => {
  const headers = new Headers({ "Content-Type": "text/plain", "Vary": "Accept-Encoding" });
  if (!acceptsGzip(req)) return new Response("gzip only in this demo\n", { headers });
  const gzip = createGzip({ flush: constants.Z_SYNC_FLUSH });
  (async () => {
    for (let i = 1; i <= 5; i++) {
      gzip.write(`line ${i}: ${"x".repeat(1000)}\n`);
      await Bun.sleep(100);
    }
    gzip.end();
  })();
  headers.set("Content-Encoding", "gzip");
  return new Response(Readable.toWeb(gzip) as ReadableStream, { headers });
},
text
$ python3 stream_timing.py /stream-flush
     1 ms  34 bytes
   101 ms  21 bytes
   202 ms  20 bytes
   302 ms  20 bytes
   402 ms  20 bytes
   503 ms  10 bytes

This time, data arrived about every 100 ms, once for each line written. The final 10 bytes arrived after gzip.end() was called. After decompression, the result matched /stream (the MD5 hashes were the same). This demo does not show how to respond to clients that cannot accept gzip. In real code, return an uncompressed stream in that case, as /stream does.

For how to send Server-Sent Events, see my article on sending Server-Sent Events with Bun.serve.

Warning

If you set Content-Encoding: gzip, the body must be gzip-compressed. When I returned an uncompressed {"ok":true} with only this header added, curl --compressed failed with "incorrect header check" (exit code 61), and Bun's fetch threw a ZlibError and could not read the body.

​Posted by 86