Sticky session e routing WebSocket
Configuri i load balancer per instradare correttamente le connessioni WebSocket stateful usando sticky session e impari quando un broker condiviso renda superflua questa configurazione.
Sticky session e routing WebSocket è una lezione WebSockets & Real-Time Systems with Spring gratuita su CoddyKit. Questa è la lezione 4 di 4. Puoi leggere la lezione completa qui gratuitamente — poi esercitati direttamente nel browser con un editor di codice integrato e un tutor IA disponibile 24/7. Fa parte del percorso di apprendimento WebSockets & Real-Time Systems with Spring, e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso WebSockets & Real-Time Systems with Spring include 4 lezioni in totale.
Parti di questa lezione non sono ancora state tradotte e vengono mostrate in inglese.
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 = 86400Forwarding 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 = 300Health 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
Upgradeheader and tolerate idle WebSockets - Use connection draining on deploys
- A shared broker removes the routing need; affinity then becomes an optimization
Impara WebSockets & Real-Time Systems with Spring con un tutor IA — gratis
Scrivi ed esegui vero codice nel tuo browser, ricevi aiuto istantaneo da un tutor IA disponibile 24/7, e riprendi da dove hai lasciato sul web o nell'app.
- Corsi
- 12
- Lezioni
- 48
Domande Frequenti
La lezione «Sticky session e routing WebSocket» è gratuita?
Sì — il testo completo di «Sticky session e routing WebSocket» è gratuito qui sul web. Per esercitarvi in modo interattivo (un editor di codice integrato e un tutor IA 24/7) e sbloccare il resto del corso WebSockets & Real-Time Systems with Spring, passa a CoddyKit PRO. Il corso WebSockets & Real-Time Systems with Spring include 4 lezioni in totale.
Cosa imparerò in «Sticky session e routing WebSocket»?
Configuri i load balancer per instradare correttamente le connessioni WebSocket stateful usando sticky session e impari quando un broker condiviso renda superflua questa configurazione. Eserciti WebSockets & Real-Time Systems with Spring con codice pratico che esegui direttamente nel browser, e un tutor IA 24/7 risponde alle tue domande mentre lavori sulla lezione.
Ho bisogno di esperienza per iniziare WebSockets & Real-Time Systems with Spring?
Non è richiesta alcuna esperienza precedente. WebSockets & Real-Time Systems with Spring su CoddyKit è strutturato per principianti e studenti avanzati, quindi puoi iniziare da qui o dall'inizio e procedere al tuo ritmo. Questa è la lezione 4 di 4.
Quanto tempo richiede la lezione «Sticky session e routing WebSocket»?
La maggior parte delle lezioni CoddyKit richiede circa 5–10 minuti. Ogni lezione è breve e interattiva, quindi fai progressi costanti e riprendi esattamente da dove hai lasciato su web e app.
Posso scrivere ed eseguire codice in questa lezione WebSockets & Real-Time Systems with Spring?
Sì. Ogni lezione WebSockets & Real-Time Systems with Spring include un editor di codice integrato, quindi scrivi ed esegui codice reale direttamente nel tuo browser e ricevi feedback istantaneo dall'IA — nessuna configurazione locale necessaria.
Tutte le lezioni di questo corso
- WebSockets nelle architetture a microservizi
- Strategie di deploy sul cloud (AWS/GCP)
- Bilanciamento del carico e alta disponibilità
- Sticky session e routing WebSocket