Reducción del ancho de banda con compresión de mensajes
Reduzca el ancho de banda de WebSocket mediante la extensión permessage-deflate y un diseño inteligente de los payloads, y comprenda sus compromisos de CPU y memoria.
Reducción del ancho de banda con compresión de mensajes es una lección gratuita de WebSockets & Real-Time Systems with Spring en CoddyKit. Esta es la lección 4 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de WebSockets & Real-Time Systems with Spring, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de WebSockets & Real-Time Systems with Spring incluye 4 lecciones en total.
Partes de esta lección aún no han sido traducidas y se muestran en inglés.
Bandwidth Is a Bottleneck
Real-time apps can push thousands of frames per second. On mobile and high-fan-out systems, raw bytes on the wire become a real cost in latency, data charges, and egress bills.
The permessage-deflate Extension
WebSocket defines an extension, permessage-deflate, that compresses each message with DEFLATE (the same algorithm as gzip) before it is sent and decompresses it on arrival.
Negotiated in the Handshake
Compression is negotiated via the Sec-WebSocket-Extensions header during the upgrade. If both peers agree, frames are compressed transparently afterward.
Sec-WebSocket-Extensions: permessage-deflate; client_max_window_bitsWhere Compression Wins
Compression helps most with text and JSON, which are highly repetitive. A 4 KB JSON payload can shrink to under 1 KB.
Already-compressed data (images, video, gzip) barely shrinks and just wastes CPU.
The CPU Trade-off
Compression is not free. Every message costs CPU on both sides. Under very high message rates the CPU spent compressing can outweigh the bandwidth saved.
The Context-Takeover Memory Cost
DEFLATE keeps a sliding-window dictionary per connection (context takeover). With many connections this is significant memory. Disabling takeover saves RAM but lowers the compression ratio.
Enabling in Spring (Tomcat)
Spring delegates to the servlet container. On Tomcat you tune the WebSocket compression via container properties or a customizer.
server.tomcat.use-relative-redirects=false
# Tomcat enables permessage-deflate when the client offers it;
# tune limits via WsServerContainer / @Bean customizerPer-Message Skip for Small Frames
Compressing tiny frames adds overhead with little gain. Many stacks skip compression below a threshold (e.g. messages under 256 bytes). Keep this in mind when designing payload sizes.
Application-Level Alternatives
Before reaching for transport compression, shrink the payload itself:
- Send deltas, not full snapshots
- Use short field names or a binary format (Protobuf, MessagePack)
- Batch many small updates into one frame
Measuring the Benefit
Always measure. Compare bytes-on-wire and CPU before and after enabling compression for your real traffic mix; do not assume it is always a win.
# Compare with monitoring metrics
websocket.bytes.sent (deflate on vs off)
process.cpu.usageChoosing a Strategy
Rules of thumb:
- High-volume JSON, bandwidth-bound → enable permessage-deflate
- Many idle connections, memory-bound → disable context takeover
- CPU-bound, small frames → prefer application-level payload shrinking
Quick Check
Test your compression knowledge.
Recap
You optimized bandwidth:
- permessage-deflate compresses each message, negotiated in the handshake
- Best for repetitive text/JSON; useless for already-compressed data
- It trades CPU and per-connection memory (context takeover) for fewer bytes
- Application-level deltas, binary formats, and batching are complementary
- Always measure before and after for your real traffic
Preguntas frecuentes
¿La lección «Reducción del ancho de banda con compresión de mensajes» es gratis?
Sí — el texto completo de «Reducción del ancho de banda con compresión de mensajes» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de WebSockets & Real-Time Systems with Spring, actualiza a CoddyKit PRO. El curso de WebSockets & Real-Time Systems with Spring incluye 4 lecciones en total.
¿Qué aprenderé en «Reducción del ancho de banda con compresión de mensajes»?
Reduzca el ancho de banda de WebSocket mediante la extensión permessage-deflate y un diseño inteligente de los payloads, y comprenda sus compromisos de CPU y memoria. Practicas WebSockets & Real-Time Systems with Spring con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.
¿Necesito experiencia previa para empezar WebSockets & Real-Time Systems with Spring?
No se requiere experiencia previa. WebSockets & Real-Time Systems with Spring en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 4 de 4.
¿Cuánto tiempo toma la lección «Reducción del ancho de banda con compresión de mensajes»?
La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.
¿Puedo escribir y ejecutar código en esta lección de WebSockets & Real-Time Systems with Spring?
Sí. Cada lección de WebSockets & Real-Time Systems with Spring incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.
Todas las lecciones de este curso
- Evaluación comparativa del rendimiento de WebSocket
- Supervisión de conexiones WebSocket
- Ajuste de la configuración de Spring WebSocket
- Reducción del ancho de banda con compresión de mensajes