Full answer
Decompression bombs: 10 MB of zeros compresses to about 10 KB. A request with Content-Encoding: gzip, an uploaded archive or a gzipped log can therefore expand a thousand times or more. If the server inflates it in memory without a limit, a single request can exhaust memory.
Defences:
- Sync and callback APIs accept { maxOutputLength: bytes }. When the limit is exceeded, they throw ERR_BUFFER_TOO_LARGE.
- With streams, count the bytes that leave the decompressor in a Transform and destroy the pipeline when the total goes over the limit.
- Limit the compressed input size too, and the compression ratio you accept.
- Run with time limits and, for archives, limit the number of entries and the nesting depth.
Compressing HTTP responses:
- Read req.headers['accept-encoding'] (for example 'gzip, deflate, br').
- Pick an encoding you support. Prefer br for static text, gzip as the common fallback.
- Set Content-Encoding to the choice and Vary: Accept-Encoding, so caches store the variants separately. Remove Content-Length (the compressed length is not known up front) or use chunked transfer.
- Pipe the body through zlib.createGzip() (or createBrotliCompress with a moderate quality) into res. Use pipeline for error handling.
- Do not compress small bodies (under about 1 KB) or types that are already compressed (images, video, zip, woff2).
- For dynamic responses use a lower level or quality to save CPU. Pre-compress static assets at build time or let a reverse proxy or CDN do it.
Security note: compressing secrets together with attacker-controlled text in the same response can leak the secret by response size (the BREACH attack). Avoid reflecting user input next to tokens in compressed pages, and use per-request token masking.
const zlib = require('node:zlib');
const http = require('node:http');
// 1. A small file that expands a lot: 20 MB of zeros.
const bomb = zlib.gzipSync(Buffer.alloc(20 * 1024 * 1024));
console.log('compressed size is under 100 KB:', bomb.length < 100 * 1024);
try {
zlib.gunzipSync(bomb, { maxOutputLength: 1024 * 1024 }); // allow at most 1 MB
} catch (err) {
console.log('decompression stopped:', err.code); // (error on purpose)
}
console.log('with a high enough limit it works:', zlib.gunzipSync(bomb, { maxOutputLength: 32 * 1024 * 1024 }).length);
// 2. Content negotiation for an HTTP response.
const body = Buffer.from('<li>Student record</li>'.repeat(2000));
const server = http.createServer((req, res) => {
const accepted = String(req.headers['accept-encoding'] || '');
res.setHeader('Content-Type', 'text/html');
res.setHeader('Vary', 'Accept-Encoding');
if (accepted.includes('gzip')) {
res.setHeader('Content-Encoding', 'gzip');
res.end(zlib.gzipSync(body)); // for big or dynamic bodies use streams with pipeline
} else {
res.end(body);
}
});
server.listen(0, '127.0.0.1', async () => {
const base = 'http://127.0.0.1:' + server.address().port;
// Use the raw http module so the response bytes are not decompressed for us.
const get = (headers) => new Promise((resolve) => {
http.get(base, { headers }, (res) => {
const chunks = [];
res.on('data', (c) => chunks.push(c));
res.on('end', () => resolve({ encoding: res.headers['content-encoding'] || 'none', vary: res.headers.vary, size: Buffer.concat(chunks).length }));
});
});
const plain = await get({ 'Accept-Encoding': 'identity' });
const packed = await get({ 'Accept-Encoding': 'gzip, deflate' });
console.log('without gzip:', plain.encoding, '| same size as the body:', plain.size === body.length);
console.log('with gzip:', packed.encoding, '| vary:', packed.vary, '| much smaller:', packed.size < body.length / 10);
server.close();
});The first limit check fails on purpose (error on purpose) to show ERR_BUFFER_TOO_LARGE. The HTTP part uses the raw http client so the compressed bytes can be measured. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, same on two runs): compressed size is under 100 KB: true decompression stopped: ERR_BUFFER_TOO_LARGE with a high enough limit it works: 20971520 without gzip: none | same size as the body: true with gzip: gzip | vary: Accept-Encoding | much smaller: true
Key points
- maxOutputLength stops decompression bombs.
- Count bytes in streams and abort on excess.
- Content-Encoding plus Vary: Accept-Encoding for responses.
- Skip small and already compressed content.
- Pre-compress static files or use a proxy.
Common mistakes
- Inflating uploaded or request data with no output limit.
- Forgetting the Vary header, so a cache serves gzip to a client that cannot read it.
- Compressing small or already compressed responses.
- Compressing responses that mix secrets and user-controlled text.
Follow-ups
- How would you limit decompression in a stream?
- What does the BREACH attack exploit?
- Where should compression happen: Node, a proxy or a CDN?
Tips
- Say 'maxOutputLength' for the bomb question.
- List the response steps: negotiate, headers, stream.
- Mention that proxies and CDNs usually compress static assets better.