Video in progress
Where are messages compressed in Kafka, which codec would you pick, and what does `compression.type` on the broker affect?
Compression is done on the producer, per whole batch; the message stays compressed on the broker and on disk, and the consumer decompresses it. I usually pick lz4 or zstd. If compression.type on the broker or topic differs from the producer's, the broker recompresses and burns CPU.
📖 Answer
The bigger the batch, the more effective the compression, which is why compression works together with linger.ms. Small messages sent one by one barely compress.
| Codec | Speed | Compression ratio | When |
|---|---|---|---|
none |
— | — | payload that's already compressed (images, Avro+zstd) |
snappy |
fast | medium | the old default, still common |
lz4 |
very fast | medium | latency matters, a general choice |
zstd |
medium | best | network/disk is expensive, cross-AZ traffic |
gzip |
slow | good | rarely a reason for it today |
spring:
kafka:
producer:
compression-type: zstd
On the broker side, the topic config compression.type defaults to producer, which means "store whatever the producer sent". If a topic is set to gzip and the producer sends lz4, the broker decompresses and recompresses every batch. On one project the broker CPU was high for no obvious reason, and this turned out to be the cause.
Since Kafka 3.8 you can also configure the codec level (for example, compression.zstd.level), but the defaults are often enough.
Measure before you choose: zstd shrinking JSON events 4-6x is common, but the exact number depends on your data. The producer's compression-rate-avg metric shows the real result.
Sign up to mark studied questions and save your progress.