Halloween DealsAmazon USHalloween week deals: useful picks before month-endAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PCHalloween DealsAmazon USOctober picks are moving - compare before checkoutAmazon US: current deals, useful picks and tech finds.See Picks×
FREEDOM251

Freedom251 › Blog › Apache

How to configure reverse proxies and gateways to limit decompression-based attacks

By Freedom251 Team · · 11 min read

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Some links on this page are affiliate links: if you buy through them we may earn a commission, at no extra cost to you.

Protect the decoded stream, not just the bytes on the wire. A reverse proxy should accept compressed request bodies only on routes that need them, decode them incrementally, enforce a maximum decompressed size and an expansion-ratio ceiling, and stop reading as soon as either limit is exceeded. Apply the same policy to every enabled codec, then normalize headers and emit telemetry for both encoded and decoded bytes. A 150 KB gzip payload that expands to 150 MB (about 1,029×) can otherwise exhaust memory before an upstream application sees a request.

What is a decompression-based attack?

A decompression bomb is a deliberately small encoded body that expands into a much larger byte stream when a proxy, gateway, or client decodes it. The attacker sends inexpensive wire traffic, while the decoder allocates memory, consumes CPU, and forwards a body that may exceed every downstream assumption. The 2026 httplib2 security advisory describes unbounded gzip/deflate response handling that can cause memory exhaustion when no decoded-size or ratio guard is present.

As an Amazon Associate I earn from qualifying purchases.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The risk exists anywhere attacker-controlled content is decoded automatically: an API gateway accepting Content-Encoding: gzip, a service mesh filter, an HTTP client following compressed responses, or a transformation layer that decompresses before inspection. It is a denial-of-service problem even when the application itself has a request limit, because an unbounded proxy can run out of memory first.

Why is the compressed Content-Length header unsafe?

Content-Length describes the encoded bytes received from the client. It does not tell you how many bytes a decoder will produce. Apache’s mod_deflate documentation states that “The Content-Length header reflects the length of the incoming data from the client and not the byte count of the decompressed data stream.” A 1 MB limit applied only to that header therefore permits a tiny body to expand far beyond the limit.

#1 Best Overall
Sale
TOZO A1 Wireless Earbuds Bluetooth 5.3 Light Weight in Ear Headphones | IPX5 Waterproof,2 Mics for AI Calls,Immersive Premium Sound Bass Headset with Charging Case,32 EQ via App Black
  • [Ultra-Lightweight Ear Buds Designed for Small Ears] Each earbud weighs only 3.7g and features a compact, ergonomic in-ear design made especially for small ears. Secure, low-profile, and comfortable for workouts, all-day wear or overnight sleeping.The ultra-slim profile sits flush in your ear with no hard edges poking or rubbing, so you can even sleep on your side without discomfort.
  • [Immersive Stereo Sound with TOZO OrigX Technology] TOZO OrigX tuning delivers clear vocals, balanced mids, and natural stereo sound for music, podcasts, and videos.
  • [Long Battery Life for Daily Use] Get up to 7 hours of playtime on a single charge, with up to 32 hours total using the charging case—ideal for workdays, commuting, and extended listening sessions.
  • [Bluetooth 5.3 & Stable Connection] Bluetooth 5.3 provides fast pairing, stable wireless performance, and reduced dropouts as you move around home or office.
  • [Deep Bass with Clear Vocals] High-performance drivers produce punchy bass while keeping vocals clean and detailed for everyday listening.

Treat encoded length and decoded length as separate values. Count bytes as the decoder emits them, and make the decoded count authoritative for memory and application limits. If a proxy transforms the body, downstream components must not continue trusting the original encoded length.

How should a gateway handle compressed requests safely?

Use a route-scoped, streaming policy. The sequence below keeps decoding out of routes that do not need it and ensures that an oversized expansion is rejected before it can fill an unbounded buffer.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

1. Make request decompression opt-in

Enable a request decompressor only on endpoints that explicitly accept compressed uploads or API payloads. Keep it off for ordinary JSON, form, and file routes unless there is a measured requirement. Reject an unsupported Content-Encoding with 415 Unsupported Media Type before invoking any decoder.

Do not silently accept an encoding chain such as gzip, br unless the route has a defined order of operations and a limit for the fully decoded result. A simple default is to reject chained or duplicate encodings and allow one known codec per route. Envoy exposes request-direction enablement separately from response decompression; Apache requires an explicit input filter for gzip request bodies.

2. Decode as a stream and count output

Feed bounded input chunks to the decoder and immediately write each output chunk to a bounded sink or downstream stream. Maintain counters for encoded bytes received and decoded bytes produced. Abort the read when the decoded counter would cross the route’s maximum; do not finish decoding merely to discover the final size.

Never copy the entire compressed body into memory and then call a one-shot decompression function. A streaming design limits peak memory to fixed buffers plus the amount intentionally held for application processing. Microsoft’s ASP.NET Core guidance applies the request-body limit to bytes read from the decompressed stream and stops further reads when that limit is exceeded.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #2
Smart Watch for Men Women Compatible with iPhone Samsung Android Phone 1.69 inch Full Touch Screen IP68 Waterproof Bluetooh Fitness Tracker Heart Rate/Sleep Monitor (Black)
  • 【IP68 Waterproof Multifunctinal Smart Watch】Torjalph fitness activity tracker smart watch is IP68 waterproof technology ,you can wear it when swimming,handwashing,it's rain-proof which means that you perform multiple exercise modes outside without worrying about sweat or rain corroding your fitness smart watch,and this watch equipped with a 230 mAh large capacity battery magnetic charging ,and this sports activity tracker watch can be used 5-7 days If fully charged.
  • 【Larger 1.83'' Full Screen Watch & Multi-dial Selection】1.83 inch full HD color touch screen smart watch for men / women provides excellent 240*284 resolution image quality ,This Bluetooth smart watch offers a better touch experience and remarkable immersion and ,more than 200 watch faces for you to choose from App"Da Fit ", you can change the dial style according to your mood to wear keeping the world on your wrist
  • 【Accurate Activity Tracker Smart Watch 】sports watch activity tracker uses sweat and dust resistant breathable silicone strap, our Fitness Tracker Smart Watch for Android iOS Phones supports 12 sports modes,walking,running,bicycle,swimming,badminton,basketball,football,rope skipping. This bluetooth calls smart watch for men women is lightweight and stylish, bringing more convenient and relaxing sports experience while also providing more protection.
  • 【Your 24 Hour Personal Daily Health Monitor】Fitness watch for women men full touch screen IP67 waterproof bluetooth smartwatch for Android iOS Phones with heart rate blood pressure monitor multifunction Andriod smart watch with steps counter sleep monitor sports fitness watch, monitoring blood oxygen saturation allows you to understand your physical condition in real time to track fitness progress ,to know your health status in time.
  • 【More Functions Bluetooth Call Smart Watch】This fitness activity smart watch full screen for iPhone and Android phones includes a bunch of new features including:The bluetooth smart watch can hang up the phone, receive and display WhatsAPP /Text /Facebook /Twitter /Messenger reminder.Support sedentary reminder, alarm clock, stopwatch, timer,weather information,music control, remote camera control compatible with Android 5.0 and above or iOS 9.0 and above smartphones.

3. Enforce two independent ceilings

Set an absolute decoded-size ceiling for each route and an expansion-ratio ceiling calculated as decoded bytes divided by encoded bytes. The absolute ceiling protects the route, process, and downstream service from large legitimate uploads. The ratio ceiling catches extreme amplification even when the encoded body is small.

Check both values during streaming. For example, if a route allows 8 MiB decoded and a 100:1 ratio, a 90 KB request must be stopped at the earlier boundary: either 8 MiB decoded or 9 MB decoded (100 times 90 KB), whichever comes first. The values in this example are illustrative policy choices, not universal defaults; choose them from the route contract and memory budget.

4. Apply limits to every accepted codec

Gzip, deflate, Brotli, Zstandard, and Snappy must all pass through equivalent decoded-size and ratio checks. Do not assume a global allocator setting covers every decoder. A 2026 Netty advisory documents a bypass in which maxAllocation protected gzip/deflate while Brotli, Zstandard, and Snappy were not subject to it.

Keep a codec allow-list with an owner and a test fixture for each entry. When a new codec is enabled, verify its streaming API, memory behavior, error handling, and limit enforcement before deploying it to production.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

5. Normalize headers after decoding

After a body is decompressed, remove or rewrite Content-Encoding. Do not forward the client’s encoded Content-Length as though it described the decoded body. Envoy removes content-length when decompression occurs and exposes compressed and uncompressed byte statistics. If a gateway has fully buffered the decoded body and knows its exact size, it can set a new length; otherwise use streaming transfer semantics and ensure downstream code reads to the transformed stream.

Return a clear status when a limit is crossed. 413 Payload Too Large is appropriate for a decoded-size or ratio violation; 415 Unsupported Media Type is appropriate for an encoding the route does not accept. Close or drain the connection according to the proxy’s HTTP implementation so an attacker cannot keep a rejected stream consuming resources.

Rank #3
Sale
New Bee Guitar Cable 10ft Electric Instrument Bass AMP Cord | 6.35mm Jack, Durable Design, Stage and Home Studio Use, Low Noise Shielded Electric Cord for Bass, Keyboard, Amp, Mixer
  • [Low Noise High Fidelity] New bee guitar cord with 22AWG oxygen-free-copper center conductors provides enhanced signal transfer, the PVC insulation material and the high-density stranded copper double shield provide noise rejection for quiet operation
  • [Ideal for Choice] New bee 1/4 straight and right angle metal connectors, ensures a secure connection in any instrument, pedal, or amp jack. L shape great fro on stage guitar stands
  • [Wide Compatible] Suitable for mixer, power amplifier, microphone, effector, decoder, equalizer, electoronic organ, electric guitar, electric bass and other electronic equipments. Widely used in the installation of smart home, karaoke speaker, professional stage audio, etc
  • [Easy Disassemble] Making incidental repairs quick and easy! Very nice, flexible cable
  • [Dont Hesite to Order] 24 hours customer services and professional technology team are standing by

What values should you choose for decoded-size and ratio limits?

There is no vendor-prescribed universal byte or ratio value. Set a per-route limit from the largest valid payload, the application’s own parser limit, and the memory available to one concurrent request. Add a lower global ceiling so a misconfigured route cannot consume the entire proxy process.

  • Start with the contract: define the largest decoded request the endpoint can legitimately process, including multipart overhead and metadata.
  • Reserve headroom: account for decoder buffers, TLS buffers, logging, and application copies. A 10 MiB decoded limit can require more than 10 MiB of process memory.
  • Choose a ratio ceiling: examine normal traffic by codec, then set a threshold above observed legitimate ratios but far below amplification that would threaten memory. Revisit it when clients or codecs change.
  • Use global backstops: cap concurrent decoding work and total request-body memory in addition to per-route limits.
  • Fail early: enforce limits while bytes are produced, not after buffering or parsing.

The httplib2 advisory’s example—150 KB compressed expanding to 150 MB, approximately 1,029×—illustrates why an absolute limit alone is insufficient. A 150 MB route limit would still permit a very high amplification from a tiny request; a ratio limit catches that pattern earlier.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

How do response-compression settings affect gateway safety?

Response compression is a separate direction from request decompression, but it also consumes CPU and can trigger transformations that complicate caching. Compress only useful content types, skip media that is already compressed, and set a minimum response size so tiny responses do not incur needless work.

  • Envoy Gateway documents a configurable minContentLength; the minimum allowed value is 30 bytes.
  • Cloudflare documents minimum response sizes of 48 bytes for Gzip and 50 bytes for Brotli and Zstandard.
  • Amazon API Gateway’s minimumCompressionSize accepts integers from 0 through 10,485,760 bytes (10 MiB). Set a threshold appropriate to each API rather than enabling compression for every response.

When selecting an encoding from Accept-Encoding, send Vary: Accept-Encoding so caches do not serve one representation to a client that requested another. Dynamic edge transformations may decompress and recompress content; Cloudflare documents that Cache-Control: no-transform can prevent transformations in supported cases. Align origin and edge policies, especially for sensitive or CPU-heavy paths.

Which proxy and gateway products expose the needed controls?

The products below provide different pieces of the pattern. None of the documented response-compression switches should be assumed to enforce a decoded request-body quota.

Implementation Request decompression Response-compression controls Important limitation or behavior
NGINX The documented gunzip feature decompresses stored gzip responses for clients that do not accept gzip. gzip on, gzip_types, and gzip_min_length. These directives govern response handling; a decompressed request-body quota must be enforced by the application or an upstream gateway with bounded decoding.
Envoy Decompressor filter supports gzip and Brotli and can be enabled independently for requests and responses. Filter-level response handling plus byte statistics. After decompression it removes content-length and exposes compressed/uncompressed byte totals and decompressed/not-decompressed counters.
Envoy Gateway Uses Envoy’s request-direction controls. BackendTrafficPolicy supports Brotli, Gzip, and Zstd with configurable minContentLength. The documented minimum minContentLength is 30 bytes, enforced by Envoy Proxy.
Cloudflare Edge transformations can decompress and recompress when policies require it. Compression Rules can enable, disable, or order codecs based on Accept-Encoding; Brotli, Gzip, and Zstandard are supported for visitor responses. Use rules to disable compression for sensitive or CPU-heavy paths and keep origin and edge transformation behavior consistent.
Amazon API Gateway Can decompress compressed method request payloads before applying mapping templates. minimumCompressionSize ranges from 0 through 10,485,760 bytes (10 MiB). Keep a separate decoded request-size limit upstream or in the integration; the response threshold does not protect request decompression.
Apache HTTP Server mod_deflate can be inserted as an input filter for gzip request bodies. mod_deflate response filters. The incoming Content-Length remains the encoded length, so downstream code or an explicitly post-decompression server limit must count decoded bytes.

How should a streaming decoder report and reject violations?

Keep the decoder’s state machine separate from application parsing. For each chunk, first account for encoded bytes, then decode, then update the decoded counter, ratio, and memory budget. If decoding fails, return a client error without exposing a stack trace or forwarding partial content.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #4
BSIMB 15.6" Digital Family Calendar & Chore Chart, No Subscription Fees
  • Digital Family Calendar: BSIMB digital calendar wall touch screen puts an end to your chaotic life. Designed for busy families, the digital calendar keeps you organised and in step with your family. Assign different colours and tasks to each family member to make family scheduling easier and more intuitive.
  • Easy Setup and Auto-Sync: Plug in, connect to WLAN and auto-syn your electric calendar in minutes. Digital wall calendar compatible with Google calendar, iCloud calendar, Outlook calendar, Cozi calendar and Yahoo calendar. Add events directly on the device or through the ecalendar app. Electronic calendar stays current whether you're at work or traveling—no manual updates needed.
  • All-In-One Home Assistant: Smart calendar builds habits and encourage independence with personalised chores. Display daily meal plan to reduce the daily ‘What's for dinner?’ stress. To-do lists keep track of everything you want. Turning chores into valuable achievements with stars and rewards, making life easier and more enjoyable.
  • Manage Anytime Anywhere: BSIMB electronic calendar for family stay connected with the powerful ecalendar app. Access and manage your digital wall calendar anytime, anywhere with free features like stars & rewards, photo screensaver, chore charts, meals plans, to-do lists etc. Electronic planner paid features like Magic Import tailor advanced tools for users with special needs.
  • Stay in Touch with Loved Ones: Share photos or videos from your phone to electronic wall calendar with app, instantly update your life moment, and keep in touch with your family, especially those who are far away; you can also surprise your smart calendar digital wall by sending him a wish card; it's also great for keeping tech-illiterate elders in touch with the youngsters.
encoded += chunk.length
output = decoder.feed(chunk)
decoded += output.length
if decoded > route.maxDecodedBytes:
    reject(413)
if encoded > 0 and decoded / encoded > route.maxExpansionRatio:
    reject(413)
write_to_bounded_sink(output)

The pseudocode illustrates the order of checks; use the streaming API and error semantics supplied by the codec library. Guard against integer overflow in counters, enforce a finite maximum on chunk sizes, and stop reading from the socket immediately after rejection.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

What should you monitor?

Record encoded bytes, decoded bytes, expansion ratio, codec, decode failures, rejected requests, memory, CPU, and latency as separate fields. Correlate them by route and protocol version so a spike is visible before the proxy is exhausted.

  • Volume: count accepted, rejected, and failed decodes by codec and route.
  • Amplification: histogram decoded-to-encoded ratios; alert on values approaching the configured ceiling.
  • Resources: track process memory, allocator pressure, CPU time spent decoding, and active decoder concurrency.
  • Outcomes: distinguish 413 decoded-limit responses from 415 unsupported-encoding responses and transport resets.
  • Protocol coverage: verify identical policy on HTTP/1.1 and HTTP/2, including request trailers and stream cancellation.

Envoy exposes decompressed/not-decompressed counters and total compressed/uncompressed byte statistics that can feed these dashboards. Preserve the original codec and both byte counts in logs without storing attacker-controlled bodies.

How do you test the limits before production?

  1. Inventory routes: list every endpoint that accepts Content-Encoding, the codecs allowed, and the intended decoded-size contract.
  2. Exercise ordinary traffic: send benign compressed fixtures at the largest valid sizes and record decoded bytes, ratios, CPU, memory, and latency.
  3. Test the exact boundaries: submit payloads one byte below, exactly at, and one byte above both the decoded-size and ratio ceilings. Confirm that the over-limit case stops during streaming and returns 413.
  4. Test codec parity: repeat the boundary cases for gzip, Brotli, Zstandard, and any additional codec enabled in the deployment.
  5. Test malformed input: truncate streams, corrupt headers, send duplicate encodings, and verify fast rejection with no unbounded allocation.
  6. Test headers: confirm that transformed requests do not retain the encoded Content-Length, that Content-Encoding is removed or rewritten, and that responses carry Vary: Accept-Encoding when negotiation is used.
  7. Load-test concurrency: combine many near-limit requests with normal traffic and observe memory, CPU, queueing, and tail latency.
  8. Test both protocols: run the same cases over HTTP/1.1 and HTTP/2, including client cancellation and connection reuse.

Use benign fixtures that reproduce high expansion without distributing a live attack payload. Review proxy, decoder, and gateway release notes before enabling a new codec; a limit that works for gzip may not automatically cover another implementation.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

What operational checklist should teams follow?

  • Inventory every route that accepts Content-Encoding.
  • Reject unsupported or chained encodings unless a documented route requires them.
  • Set per-route decoded-byte ceilings plus a global safety ceiling.
  • Set an expansion-ratio ceiling and abort during streaming decode.
  • Verify equivalent enforcement for gzip, Brotli, Zstandard, and every custom codec.
  • Keep compressed and decompressed lengths in separate telemetry fields.
  • Normalize Content-Encoding, Content-Length, and Vary after transformations.
  • Set response-compression minimums and exclude already-compressed media.
  • Load-test boundary cases while monitoring memory, CPU, latency, and 413/415 responses.
  • Review vendor advisories and release notes before enabling new codecs.

What are the most common configuration mistakes?

Limiting only the wire length

A proxy that checks Content-Length but never counts decoder output is measuring the wrong quantity. Keep the encoded limit for bandwidth control, but enforce a separate decoded limit for memory and application safety.

Buffering before checking

Reading the complete body into a byte array defeats the purpose of a limit. Use incremental decoding and a bounded sink so the first over-limit chunk triggers rejection.

Protecting one codec but not another

Codec-specific filters and libraries often have independent allocation paths. Confirm the same byte and ratio checks execute for every accepted encoding, including Brotli and Zstandard.

Leaving stale headers downstream

Forwarding an encoded Content-Length after decoding can truncate reads, cause request smuggling conditions, or make application accounting wrong. Remove it or replace it with the known decoded length.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Applying response settings to requests

A response minimum such as Envoy Gateway’s 30-byte setting or API Gateway’s 10 MiB maximum threshold controls outbound compression work. It does not cap an inbound decompressed request. Configure request decoding limits independently.

Frequently Asked Questions

Can I safely allow gzip request bodies on every endpoint?

Usually no. Enable decoding only where clients have a documented need, because every enabled route becomes a decompression surface. Keep ordinary JSON and form endpoints uncompressed unless measurements justify the added complexity.

Should a ratio limit be calculated from Content-Length?

Use the actual encoded bytes consumed by the decoder, not an untrusted or missing header. Track the ratio continuously; chunked HTTP/1.1 requests and HTTP/2 streams may not provide a usable Content-Length at all.

What status code should an API return for a decompression bomb?

Return 413 when the decoded-size or expansion policy is exceeded, and 415 when the encoding is unsupported or disallowed on that route. Log the codec and counters internally, but avoid echoing decoder details that help an attacker tune payloads.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Do encrypted connections prevent decompression attacks?

No. TLS hides the wire contents from intermediaries, but the gateway still decrypts and may decode the body. Enforce limits after TLS termination and before buffering or forwarding the decoded stream.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

ApacheAPI GatewayBrotlidecompression bombEnvoyGzipHTTP securityNGINXreverse proxyZstandard

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.