WebSockets & Real-Time Systems with Spring · Aula

Sessões persistentes e roteamento de WebSocket

Configure balanceadores de carga para direcionar corretamente conexões WebSocket com estado usando sessões persistentes e aprenda quando um intermediário compartilhado elimina essa necessidade.

Aula 4 de 413 etapas

Sessões persistentes e roteamento de WebSocket é uma aula grátis de WebSockets & Real-Time Systems with Spring no CoddyKit. Esta é a aula 4 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de WebSockets & Real-Time Systems with Spring, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de WebSockets & Real-Time Systems with Spring inclui 4 aulas no total.

Partes desta aula ainda não foram traduzidas e aparecem em 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
Grátis para começar

Aprenda WebSockets & Real-Time Systems with Spring com um tutor de IA — grátis

Escreva e execute código real no seu navegador, obtenha ajuda instantânea de um tutor de IA 24/7 e continue de onde parou na web ou no app.

Cursos
12
Aulas
48

Perguntas Frequentes

A aula “Sessões persistentes e roteamento de WebSocket” é grátis?

Sim — o texto completo de “Sessões persistentes e roteamento de WebSocket” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de WebSockets & Real-Time Systems with Spring, atualize para CoddyKit PRO. O curso de WebSockets & Real-Time Systems with Spring inclui 4 aulas no total.

O que vou aprender em “Sessões persistentes e roteamento de WebSocket”?

Configure balanceadores de carga para direcionar corretamente conexões WebSocket com estado usando sessões persistentes e aprenda quando um intermediário compartilhado elimina essa necessidade. Você pratica WebSockets & Real-Time Systems with Spring com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.

Preciso ter experiência prévia para começar WebSockets & Real-Time Systems with Spring?

Nenhuma experiência prévia é necessária. WebSockets & Real-Time Systems with Spring no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 4 de 4.

Quanto tempo leva a aula “Sessões persistentes e roteamento de WebSocket”?

A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.

Posso escrever e executar código nesta aula de WebSockets & Real-Time Systems with Spring?

Sim. Cada aula de WebSockets & Real-Time Systems with Spring inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.

Todas as aulas deste curso

  1. WebSockets em arquiteturas de microsserviços
  2. Estratégias de implementação na nuvem (AWS/GCP)
  3. Balanceamento de carga e elevada disponibilidade
  4. Sessões persistentes e roteamento de WebSocket
← Voltar para WebSockets & Real-Time Systems with Spring