Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Response Compression

Reduce bandwidth with automatic response compression.

Enabling Compression

use grpc_graphql_gateway::{Gateway, CompressionConfig, CompressionLevel};

let gateway = Gateway::builder()
    .with_descriptor_set_bytes(DESCRIPTORS)
    .with_compression(CompressionConfig {
        enabled: true,
        level: CompressionLevel::Default,
        min_size_bytes: 1024,  // Only compress responses > 1KB
        algorithms: vec!["br".into(), "gzip".into()],
    })
    .build()?;

Preset Configurations

// Fast compression for low latency
Gateway::builder().with_compression(CompressionConfig::fast())

// Best compression for bandwidth savings
Gateway::builder().with_compression(CompressionConfig::best())

// Default balanced configuration
Gateway::builder().with_compression(CompressionConfig::default())

// Disable compression
Gateway::builder().with_compression(CompressionConfig::disabled())

Supported Algorithms

AlgorithmAccept-EncodingCompression RatioSpeed
BrotlibrBestSlower
GzipgzipGoodFast
DeflatedeflateGoodFast
ZstdzstdExcellentFast

Algorithm Selection

The gateway selects the best algorithm based on client Accept-Encoding:

Accept-Encoding: br, gzip, deflate

Priority order matches your algorithms configuration.

Compression Levels

LevelDescriptionUse Case
FastMinimal compression, fastLow latency APIs
DefaultBalancedMost applications
BestMaximum compressionBandwidth-constrained

Configuration Options

OptionTypeDescription
enabledboolEnable/disable compression
levelCompressionLevelCompression speed vs ratio
min_size_bytesusizeSkip compression for small responses
algorithmsVec<String>Enabled algorithms in priority order

Testing Compression

# Request with brotli
curl -H "Accept-Encoding: br" \
  -X POST http://localhost:8888/graphql \
  -H "Content-Type: application/json" \
  -d '{"query": "{ users { id name email } }"}' \
  --compressed -v

# Check Content-Encoding header in response
< Content-Encoding: br

Performance Considerations

  • JSON responses typically compress 50-90%
  • Set min_size_bytes to skip small responses
  • Use CompressionLevel::Fast for latency-sensitive apps
  • Balance CPU cost vs. bandwidth savings