Sub topic 10
Compression and smaller payloads
Data transfer is billed per gigabyte, so sending fewer bytes lowers the bill on every path that charges for it. This chapter covers compressing responses and shrinking what you send. It assumes you know the transfer paths from earlier chapters (internet egress, inter-AZ, cross-region, NAT gateway), basic HTTP headers, and how to use the AWS CLI.
Why bytes matter on every path
Compression is a multiplier on the other fixes in this tutorial. A payload that shrinks by 70% costs 70% less on any path billed by volume:
- Internet egress from EC2, S3, or CloudFront.
- Inter-AZ traffic between services in different Availability Zones.
- Cross-region replication and API calls.
- NAT gateway data processing, which is billed per GB in addition to transfer charges.
Billing counts the bytes on the wire. If a service compresses a response before it leaves AWS, you pay for the compressed size. If it sends the response uncompressed and the client decompresses nothing, you pay for the full size.
Where compression pays off
Compression works well on text-like data with repeated patterns: JSON, XML, HTML, CSS, JavaScript, CSV, logs, and SVG. Typical savings for such content are 60% to 90%.
It does little for formats that are already compressed: JPEG, PNG, WebP, MP4, ZIP, and most PDFs. Compressing them again burns CPU and can make them slightly larger. For those formats, reduce size at the source instead, as described later in this chapter.
You can measure the potential savings on your own data:
import gzip
import json
records = [
{"id": i, "status": "active", "region": "us-east-1", "tags": ["web", "prod"]}
for i in range(1000)
]
raw = json.dumps(records).encode("utf-8")
print(f"raw: {len(raw)} bytes")
for level in (1, 6, 9):
packed = gzip.compress(raw, compresslevel=level)
saving = 100 * (1 - len(packed) / len(raw))
print(f"gzip level {level}: {len(packed)} bytes ({saving:.1f}% smaller)")Repetitive JSON like this shrinks a great deal. Real payloads vary, so run the same test on a sample of your own responses before you estimate savings.
Choosing an algorithm
| Algorithm | Compression ratio | CPU cost | Typical use |
|---|---|---|---|
| gzip | Good | Low to moderate | Default for HTTP responses, supported by every client |
| Brotli | Better than gzip on text | Higher at high levels | Static web assets over HTTPS |
| zstd | Close to or better than gzip | Low, tunable | Data pipelines, Kafka, backups, internal services |
| LZ4 | Lower | Very low | Latency-sensitive streams where CPU is the constraint |
Higher compression levels cost more CPU for diminishing returns. For responses generated per request, a low or middle level is usually the right trade-off. For static files you compress once and serve many times, use the highest level, because the CPU cost is paid once.
Compressing at the CloudFront edge
If you serve content through CloudFront, the simplest option is to let CloudFront compress for you. CloudFront can compress responses with gzip and Brotli based on the viewer's Accept-Encoding header. This lowers CloudFront egress bytes and speeds up page loads.
Conditions for CloudFront compression:
- The cache policy must enable the gzip and Brotli settings. Without them, CloudFront does not compress the response.
- The object must be between 1,000 bytes and 10,000,000 bytes.
- The
Content-Typemust be one of the compressible types that CloudFront supports. - The origin must return a
Content-Lengthheader, and its response must not already carry aContent-Encodingheader. - The response must be a 200, 403, or 404 status.
This CloudFormation template creates a cache policy with both encodings enabled:
AWSTemplateFormatVersion: "2010-09-09"
Resources:
CompressedCachePolicy:
Type: AWS::CloudFront::CachePolicy
Properties:
CachePolicyConfig:
Name: compressed-static-assets
DefaultTTL: 86400
MinTTL: 1
MaxTTL: 31536000
ParametersInCacheKeyAndForwardedToOrigin:
EnableAcceptEncodingGzip: true
EnableAcceptEncodingBrotli: true
HeadersConfig:
HeaderBehavior: none
CookiesConfig:
CookieBehavior: none
QueryStringsConfig:
QueryStringBehavior: noneAttach this policy to the cache behavior that serves your static content. CloudFront then keeps separate cached copies for each encoding it serves, so cache storage grows slightly but origin traffic does not.
You can confirm that compression works with a request that advertises Brotli and gzip:
curl -s -o /dev/null -D - -H "Accept-Encoding: br, gzip" \
https://d111111abcdef8.cloudfront.net/app.js | grep -i content-encodingIf the output is empty, check the cache policy, the file size, the content type, and whether the origin already set Content-Encoding.
Compressing for S3 origins
You have two ways to deliver compressed files from S3.
- Let CloudFront compress them on the fly, as described above. This is the least work, and clients that do not support compression still get a valid response.
- Store pre-compressed objects in S3 and set the metadata so clients decode them correctly.
For the second approach, set Content-Encoding when you upload:
gzip -9 -k app.js
aws s3 cp app.js.gz s3://example-bucket/app.js \
--content-encoding gzip \
--content-type application/javascriptThe object is stored compressed, so you also pay less for S3 storage and for transfer from S3 to CloudFront or to the internet. The drawback is that every client gets the gzip version. Nearly all browsers handle that, but some command-line tools and SDKs do not decode it automatically.
Pre-compressed storage also pays off for logs, exports, and data lake files that are transferred across regions or accounts. Formats such as Parquet apply compression internally, so a Parquet file needs no extra gzip step.
Compressing API responses
Dynamic API responses are often the biggest uncompressed source of transfer, because nobody turned compression on.
- API Gateway REST APIs: set the
minimumCompressionSizefor the API. Responses larger than that threshold are compressed when the client sendsAccept-Encoding. - Application Load Balancer: it does not compress responses itself. Enable compression in your web server or framework (for example
gzip on;in nginx, or compression middleware in your framework). - Services behind CloudFront: you can leave the app uncompressed and let CloudFront compress cacheable responses, but only if the response meets the conditions above.
Choose a minimum size. Compressing a 200-byte response saves almost nothing, and the gzip header overhead can cancel the gain. A threshold of about 1 KB is a common starting point.
Compressing internal traffic
Traffic between your own services is billed too, even when you never see it on a public interface. Inter-AZ traffic is charged in both directions, and cross-region traffic is charged on the sending side.
- Message brokers: set producer-side compression. In Kafka,
compression.typecan begzip,snappy,lz4, orzstd. Producers compress whole batches, so larger batches compress better. Consumers read across AZs and brokers replicate across AZs, so smaller batches reduce both. - Service-to-service calls: enable gRPC compression or HTTP
Content-Encodingfor large request bodies. - Replication and backups: compress database dumps and log shipments before they cross a region boundary.
- Log shipping: agents such as Fluent Bit can gzip payloads before sending them to a collector or to S3.
The trade-off is CPU. On a busy instance, compression moves cost from the data transfer line to the compute line. For most text-heavy traffic the transfer saving is larger, but measure CPU utilization before and after.
Reducing the payload before compressing it
Compression handles redundancy, but the cheapest byte is the one you never send.
- Return only needed fields. Support field selection or use a query layer like GraphQL so clients stop downloading large objects they ignore.
- Paginate. Return pages of results instead of full collections.
- Use conditional requests.
ETagandIf-None-Matchlet the server answer with a small 304 response when nothing changed. - Use efficient formats. Protocol Buffers or similar binary formats are usually smaller than JSON before any compression.
- Optimize images. Convert large JPEG and PNG files to WebP or AVIF, resize to the display size, and serve responsive variants. Images are often the largest share of egress for a website, and gzip does not help them.
- Minify JavaScript and CSS, then compress them.
- Cache with long TTLs. A longer
Cache-Control: max-agekeeps repeat requests off the network altogether.
Common mistakes
- Double compression. If the origin already sets
Content-Encoding: gzip, CloudFront will not compress again, and an extra layer only wastes CPU. Pick one place to compress. - Missing
Content-Length. CloudFront skips compression for origin responses that lack it, such as some chunked responses. - Cache policy without encoding settings. The most frequent cause of "CloudFront is not compressing." Check the policy first.
- Compressing tiny responses. Overhead cancels the gain. Set a minimum size.
- Wrong
Content-Type. A JSON response sent asapplication/octet-streamis not treated as compressible by CloudFront. - Assuming it works. Check response headers and compare bytes in Cost Explorer or CloudFront reports after a change, rather than trusting the configuration alone.
Exercise
A CloudFront distribution serves a 40 KB JSON API response with Content-Type: application/json. The origin sends a Content-Length header and no Content-Encoding, but responses reach viewers uncompressed even though browsers send Accept-Encoding: gzip, br. What should you check first, and why?
Show answer
Check the cache policy attached to the cache behavior. CloudFront compresses only when the policy has the gzip and Brotli settings (EnableAcceptEncodingGzip and EnableAcceptEncodingBrotli) turned on. The size, content type, and Content-Length already meet the conditions, so the cache policy is the most likely cause. If it is correct, next check that the status code is 200, 403, or 404 and that no other layer strips the Accept-Encoding header.
Exercise
Why can enabling zstd compression on a Kafka producer lower inter-AZ transfer charges, and what cost might rise in return?
Show answer
Producers compress each batch before sending it, so the bytes that cross AZ boundaries (producer to broker, broker replication, and broker to consumer) are smaller, and inter-AZ transfer is billed per GB. The cost that may rise is CPU on producers and consumers, which compress and decompress the data, so you should check CPU utilization after the change.