Implementing Compression

1. Enabling gzip Compression

Example: Per-call gzip

import _ "google.golang.org/grpc/encoding/gzip"
res, err := client.GetUser(ctx, req, grpc.UseCompressor("gzip"))
StepDetail
Import side-effectRegisters compressor
ServerDecompresses automatically if registered

2. Setting Compression Level

LibraryDetail
Built-in gzipFixed default level
Custom compressorImplement encoding.Compressor for tuned level

3. Registering Custom Compressor

Example: Custom compressor registration

type zstdCompressor struct{}
func (zstdCompressor) Name() string { return "zstd" }
func (zstdCompressor) Compress(w io.Writer) (io.WriteCloser, error) { ... }
func (zstdCompressor) Decompress(r io.Reader) (io.Reader, error)   { ... }
func init() { encoding.RegisterCompressor(zstdCompressor{}) }

4. Configuring Client Compression

APIUse
grpc.UseCompressor("gzip")Per-call
grpc.WithDefaultCallOptions(grpc.UseCompressor("gzip"))All calls

5. Configuring Server Compression

NoteDetail
DecompressAutomatic if compressor registered (via import)
Compress responsesHonors grpc-accept-encoding from client

6. Detecting Compression Support

HeaderPurpose
grpc-encodingCompressor used on this message
grpc-accept-encodingAlgorithms client can decode

7. Disabling Compression

NeedAction
Pre-compressed bytesDon't set compressor; payload already small
Latency-critical small msgCompression CPU may exceed savings

8. Implementing Custom Compression

AlgorithmUse
gzipDefault, widely supported
zstdBetter ratio + speed; needs both ends
snappy / lz4Faster, weaker compression

9. Setting Compression Threshold

GuidelineDetail
< 1 KBOften not worth compressing
> 4 KBUsually beneficial
Built-inNo threshold — applied to all messages

10. Measuring Compression Efficiency

MetricDetail
Ratiocompressed / original
CPU timeProfile compress/decompress
Latency impactp50/p99 before vs after