WebSockets & Real-Time Systems with Spring · Lección

Sesiones persistentes y enrutamiento de WebSocket

Configure los balanceadores de carga para enrutar correctamente las conexiones WebSocket con estado mediante sesiones persistentes y aprenda cuándo un broker compartido elimina esa necesidad.

Lección 4 de 413 pasos

Sesiones persistentes y enrutamiento de WebSocket 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.

WebSockets Are Long-Lived

Unlike a stateless HTTP request, a WebSocket is a persistent connection pinned to one server instance for its entire life. This breaks the assumption load balancers make about HTTP.

The Routing Problem

If the in-memory simple broker holds a user's subscriptions on instance A, a message that lands on instance B has nowhere to deliver. The connection state lives only where the socket terminated.

Sticky Sessions (Session Affinity)

Sticky sessions make the load balancer always route a given client to the same backend instance. This keeps the socket and its server-side state co-located.

Affinity by Cookie

Cloud load balancers commonly implement affinity with a cookie they set on the first response and read on later requests.

# AWS ALB target group attribute
stickiness.enabled = true
stickiness.type = lb_cookie
stickiness.lb_cookie.duration_seconds = 86400

Forwarding the Upgrade

The load balancer must support and forward the HTTP Upgrade handshake. Most modern L7 balancers (ALB, GCP HTTPS LB, Nginx) do, but it must be enabled.

# Nginx
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";

Idle Timeouts Bite WebSockets

Load balancers close connections idle beyond a timeout (ALB default 60s). A mostly-quiet WebSocket gets dropped unless you send heartbeats or raise the idle timeout.

idle_timeout.timeout_seconds = 300

Health Checks and Draining

During a deploy, instances are removed. Enable connection draining so in-flight WebSockets finish (or clients reconnect) instead of being cut abruptly.

The Better Answer: Shared Broker

Sticky sessions are a workaround. A cleaner design uses a shared external broker (the STOMP relay): any instance can deliver to any subscriber, so affinity is no longer required for routing.

Combining Both

Even with a shared broker, sticky sessions can still help by keeping a client on one instance to avoid mid-stream reconnects. Use them as an optimization, not a correctness crutch.

Kubernetes Ingress Notes

On Kubernetes, the ingress controller needs WebSocket support and affinity annotations. Nginx ingress, for example, uses cookie-based affinity.

nginx.ingress.kubernetes.io/affinity: cookie
nginx.ingress.kubernetes.io/proxy-read-timeout: "300"

Scaling Out Safely

To add capacity, scale instances behind the balancer and rely on the shared broker for fan-out. Keep sessions evenly spread and use draining on scale-down.

Quick Check

Test your routing knowledge.

Recap

You routed WebSockets correctly:

  • WebSockets are long-lived and pinned to one instance
  • Sticky sessions (cookie affinity) keep a client on its instance
  • The balancer must forward the Upgrade header and tolerate idle WebSockets
  • Use connection draining on deploys
  • A shared broker removes the routing need; affinity then becomes an optimization
Gratis para empezar

Aprende WebSockets & Real-Time Systems with Spring con un tutor de IA — gratis

Escribe y ejecuta código real en tu navegador, obtén ayuda instantánea de un tutor de IA disponible 24/7 y continúa donde lo dejaste en la web o en la aplicación.

Cursos
12
Lecciones
48

Preguntas frecuentes

¿La lección «Sesiones persistentes y enrutamiento de WebSocket» es gratis?

Sí — el texto completo de «Sesiones persistentes y enrutamiento de WebSocket» 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 «Sesiones persistentes y enrutamiento de WebSocket»?

Configure los balanceadores de carga para enrutar correctamente las conexiones WebSocket con estado mediante sesiones persistentes y aprenda cuándo un broker compartido elimina esa necesidad. 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 «Sesiones persistentes y enrutamiento de WebSocket»?

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

  1. WebSockets en arquitecturas de microservicios
  2. Estrategias de despliegue en la nube (AWS/GCP)
  3. Equilibrio de carga y alta disponibilidad
  4. Sesiones persistentes y enrutamiento de WebSocket
← Volver a WebSockets & Real-Time Systems with Spring