Why WebSocket responses disappear in Kubernetes, and how Redis Pub/Sub fixes it

By · · 3 min read

Short answer

A WebSocket connection is pinned to the pod it first connected to, but later HTTP requests can be load-balanced to any pod. The pod that does the work then has no socket to send the result on, so the user waits forever. The fix is Redis Pub/Sub: every pod subscribes to a channel, the pod that handles a request publishes the result, and the pod that holds the user’s socket delivers it. Unlike sticky sessions, this keeps working when pods restart or scale.

Why do WebSocket responses go missing in Kubernetes?

My WebSocket responses were disappearing in Kubernetes. The bug wasn’t in my code.

  1. A user opens a WebSocket and it connects to Pod 1. That connection stays on Pod 1.
  2. The same user sends a request. The load balancer can send it to any pod, and it lands on Pod 3.
  3. Pod 3 does the work, but it can’t send the result back: the user’s socket is on Pod 1.
  4. The user just keeps waiting.

With one replica you never see it. Scale to two or more and it starts failing some of the time, which makes it look like a flaky bug rather than an architecture problem.

How does Redis Pub/Sub fix it?

  • Every pod subscribes to a Redis channel when it starts.
  • The pod that handles the request publishes the result to Redis, tagged with the user it belongs to.
  • The pod that holds that user’s socket picks it up and pushes it to the user. The other pods ignore it.

Now it doesn’t matter which pod handles the request. The response always reaches the right socket.

What does the code look like?

A minimal version in Python with redis.asyncio. Each pod keeps a map of the sockets it holds, listens on one channel, and only sends messages for users it actually has:

import json
import redis.asyncio as redis

r = redis.from_url(REDIS_URL)
sockets = {}  # user_id -> WebSocket held by THIS pod

async def listen():
    """Runs once per pod, started at boot."""
    pubsub = r.pubsub()
    await pubsub.subscribe("ws-results")
    async for msg in pubsub.listen():
        if msg["type"] != "message":
            continue
        data = json.loads(msg["data"])
        ws = sockets.get(data["user_id"])
        if ws:  # only the pod holding the socket sends it
            await ws.send_json(data["payload"])

async def publish_result(user_id, payload):
    """Any pod, after it finishes the work."""
    await r.publish("ws-results", json.dumps({"user_id": user_id, "payload": payload}))

Why not just use sticky sessions?

Sticky sessions route a user’s requests back to the same pod, and they can help. But they break when pods restart or scale: the pod a user was stuck to disappears, or new pods take traffic the old routing doesn’t know about. Pub/Sub works however many pods you’re running.

Sticky sessionsRedis Pub/Sub
Pod restartsUser loses their podUnaffected
Scaling up or downRouting goes staleUnaffected
Load spreadCan get unevenAny pod can take any request
Extra infrastructureNoneA Redis instance

What are the limits of this approach?

  • Redis Pub/Sub is fire-and-forget. If the user disconnected and no pod holds their socket, the message is dropped. If results must survive a reconnect, store them (for example in a Redis Stream or the database) and replay on reconnect.
  • Every pod receives every message on the channel. That is fine for most apps; at very high volume, use one channel per user or shard channels across pods.

Frequently asked questions

Why does my WebSocket work locally but not in Kubernetes?
Locally there is one server process, so the request and the socket are always in the same place. In Kubernetes with several replicas, the request can land on a different pod from the one holding the socket.
Do sticky sessions fix WebSockets in Kubernetes?
Partly. They keep a user on one pod, but they break when that pod restarts or the deployment scales. A shared message bus such as Redis Pub/Sub works regardless of pod count.
Is Redis Pub/Sub reliable enough for WebSocket messages?
It delivers to whoever is subscribed at that moment and keeps nothing. For results that must not be lost, combine it with storage such as Redis Streams and replay missed messages when the client reconnects.

More articles