🗜️ Message Compression (Deflate)

CA: BHUxWbRJbSFsRW2JSMzm9zCJQGXkmeKhVxUWDbrHpump

WebSocket Per-Message Deflate Extension

WS-RS supports the permessage-deflate extension as defined in RFC 7692, allowing compression of WebSocket messages to reduce bandwidth usage.

What is Per-Message Deflate?

Per-message deflate is a WebSocket extension that compresses individual messages using the DEFLATE algorithm. This can significantly reduce bandwidth usage, especially for text-heavy applications.

Benefits

  • Reduced Bandwidth - Compress messages by 50-90% for text data
  • Lower Latency - Smaller messages travel faster over the network
  • Cost Savings - Reduce data transfer costs
  • Automatic Negotiation - Enabled during WebSocket handshake

Enabling Deflate Compression

Enable compression in your WS-RS server:

use ws_rs::{WebSocketServer, Config};

#[tokio::main]
async fn main() -> Result<(), Box> {
    let config = Config {
        compression: true,
        compression_level: 6, // 1-9, default is 6
        max_message_size: 10 * 1024 * 1024, // 10MB
        ..Default::default()
    };
    
    let server = WebSocketServer::with_config("127.0.0.1:8080", config);
    
    server.on_message(|client_id, message| {
        println!("Received compressed message from {}", client_id);
        // Message is automatically decompressed
    });
    
    server.start().await?;
    Ok(())
}

Client-Side Support

Modern browsers automatically support deflate compression:

// Browser automatically negotiates compression
const ws = new WebSocket('ws://localhost:8080');

ws.onopen = () => {
    // Messages are automatically compressed if server supports it
    ws.send('This message will be compressed');
};

Compression Parameters

Parameter Description Default
server_no_context_takeover Server resets compression context after each message false
client_no_context_takeover Client resets compression context after each message false
server_max_window_bits Server LZ77 sliding window size (8-15) 15
client_max_window_bits Client LZ77 sliding window size (8-15) 15

Performance Considerations

While compression reduces bandwidth, it adds CPU overhead:

  • Best for Text - Text data compresses well (50-90% reduction)
  • Not for Binary - Pre-compressed data (images, video) won't benefit
  • CPU vs Bandwidth - Trade CPU time for network bandwidth
  • Small Messages - Messages under 1KB may not benefit

Testing Compression

Verify compression is working:

// Check WebSocket extensions in browser console
const ws = new WebSocket('ws://localhost:8080');
ws.onopen = () => {
    console.log('Extensions:', ws.extensions);
    // Should show: "permessage-deflate"
};

Additional Resources