Sub topic 10
Compression and smaller payloads
This chapter assumes you know how AWS prices data transfer out to the internet, and that you can read HTTP headers and run Python 3.
Why payload size matters
Most transfer charges are per gigabyte, so fewer bytes on the wire means a lower bill. Compression reduces the bytes without changing what the user sees. It works on traffic you pay for in any direction: internet egress, cross-region replication, and NAT gateway data processing.
Text formats compress well. JSON, HTML, CSS, JavaScript, XML, and CSV often shrink by 70 to 90 percent. Images, video, and archives such as JPEG, MP4, and ZIP are already compressed, so gzip gains almost nothing on them.
Measure the saving first
This script compresses a repetitive JSON payload and prints the size reduction. Real API responses are usually less repetitive than this one, so expect smaller savings.
import gzip
import json
records = [
{"id": i, "status": "active", "region": "us-east-1", "tags": ["a", "b"]}
for i in range(2000)
]
raw = json.dumps(records).encode("utf-8")
packed = gzip.compress(raw, compresslevel=6)
print(f"raw: {len(raw):>8} bytes")
print(f"compressed: {len(packed):>8} bytes")
print(f"saved: {100 * (1 - len(packed) / len(raw)):.1f}%")Run it against a sample of your own responses before you change any infrastructure.
Where to compress
How a client asks for compressed content is the same everywhere: it sends Accept-Encoding: gzip, br, and the server replies with Content-Encoding: gzip or br.
flowchart LRThe diagram below shows the negotiation.
Choose the layer based on where the bytes are billed:
| Layer | How | Notes |
|---|---|---|
| CloudFront | Enable gzip and Brotli in the cache policy | Compresses at the edge. Applies to objects from 1,000 bytes to 10 MB in compressible content types. |
| Application or web server | gzip middleware, nginx `gzip on` | Covers traffic that does not use a CDN, such as service-to-service calls. |
| S3 objects | Store gzip files with `Content-Encoding: gzip` | Reduces storage and egress. Clients must be able to decode them. |
| Data formats | Parquet, Avro, Protobuf instead of JSON or CSV | Smaller before compression and faster to parse. |
Common errors
- Compressing twice. If the origin already compresses, CloudFront does not compress again. If you enable both, check that the origin does not send an unexpected
Content-Encoding. - Cache policy not forwarding encoding. CloudFront compresses only when the cache policy enables
Accept-Encodinghandling for gzip or Brotli. Without that setting, it ignores the header. - Compressing incompressible files. Gzipping JPEG or MP4 files costs CPU and saves almost nothing. Compress by content type.
- Wrong
Content-Type. A JSON response labelledapplication/octet-streammay not be compressed by the CDN. - CPU cost on small instances. High compression levels slow responses. Level 4 to 6 is a common balance.
Other ways to shrink payloads
- Return only the fields the client needs. Pagination and field selection often save more than compression.
- Serve responsive images and modern formats such as WebP or AVIF.
- Minify JavaScript and CSS before compressing them.
- Use conditional requests (
ETag,If-None-Match) so unchanged content returns a 304 with no body. - Compress data before cross-region replication or batch transfers, for example by writing gzip or Parquet files.
Exercise
A CloudFront distribution serves large JPEG photos and JSON API responses. You enable gzip and Brotli in the cache policy. Which traffic is likely to shrink, and why?
Show answer
The JSON responses shrink, because text compresses well. The JPEG photos barely change, because they are already compressed. To cut photo egress, resize them or convert them to a format such as WebP or AVIF.