Message Compression
socket-serve automatically compresses large messages to reduce bandwidth usage and improve performance. This happens transparently - you don’t need to do anything special.Installation
Compression utilities are included in the main socket-serve package:Automatic Compression
Compression is enabled by default for messages over 1KB:Configuration
Manual Compression
You can manually compress and decompress data:How It Works
- Client → Server: Messages are compressed before sending if they exceed the threshold
- Server → Client: Server automatically compresses large responses
- Transparent: Compression/decompression happens automatically
- Headers: Compressed messages include a
compressed: trueflag
Compression Algorithms
socket-serve uses gzip compression by default for broad compatibility:Performance Considerations
API Reference
compress(data, algorithm?)
Compress a string or buffer.
Parameters:
data: string | Buffer- Data to compressalgorithm?: 'gzip' | 'deflate' | 'br'- Compression algorithm (default: ‘gzip’)
Promise<Buffer> - Compressed data
Example:
decompress(data, algorithm?)
Decompress a buffer back to string.
Parameters:
data: Buffer- Compressed dataalgorithm?: 'gzip' | 'deflate' | 'br'- Compression algorithm (default: ‘gzip’)
Promise<string> - Decompressed data
Example:
shouldCompress(data, threshold?)
Check if data should be compressed based on size.
Parameters:
data: string | Buffer- Data to checkthreshold?: number- Size threshold in bytes (default: 1024)
boolean - Whether data should be compressed
Example:
Client-Side Compression
The client automatically handles compression:Example: Streaming Large Data
Compression Strategies
For Chat Messages
For File Transfers
For Real-time Updates
Benchmarks
Typical compression ratios for different data types:| Data Type | Original Size | Compressed Size | Ratio |
|---|---|---|---|
| JSON | 10 KB | 2 KB | 80% |
| Text | 100 KB | 15 KB | 85% |
| Already Compressed | 1 MB | 1 MB | 0% |
Best Practices
- Enable compression for bandwidth-constrained environments
- Adjust threshold based on your message sizes
- Don’t compress already-compressed data (images, videos)
- Monitor compression ratios in production
- Use brotli for static content, gzip for dynamic
- Test performance impact on your specific use case