Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 2 of 5 · Concept · 20 min · revision 1

Real-time transports and connection gateways

Choose between long polling, server-sent events and WebSocket for chat traffic using RFC 6202 and RFC 6455, then design a gateway tier: a session registry with leases, what the load balancer does and does not do, and how to contain a reconnect storm.

Contentsand lesson path

What you will learn

  • Choose a real-time transport (WebSocket, server-sent events, long polling) and design a connection gateway tier that scales to millions of concurrent connections.

Prerequisites: Messaging & Event Streaming

01. Why it matters

Lesson 1 ended with about 8 million connections at peak, held by 136 gateway servers. Which protocol should those connections speak? And when Ana messages Ben, how does the service find the one machine out of 136 that holds his phone's connection?

A stateless web tier never had to answer the second question; a gateway can push a message only into sockets it holds itself. This lesson chooses a transport, then designs the gateway tier around that fact.

02. Three transports, judged by chat traffic

The delivery channel lesson compares them in general. Chat traffic has a particular shape: short messages in both directions, long idle stretches, and a steady upstream trickle of receipts and typing events.

Long polling, covered in that lesson, is the fair starting point: it runs on any HTTP path, and any server can answer a poll if the client says what it already has. RFC 6202 §2.2 adds a cost that matters for chat: while the client is between polls the server cannot send, so the worst-case latency is more than three network transits (response, next request, response). For a prototype, a small audience or a fallback, it is often enough.

Server-sent events plus POST: the server streams events into one long HTTP response, as in the SSE lesson, and the client sends with ordinary requests. This fits clients that mostly listen; in a chat, every sent message, receipt and typing event becomes its own request.

WebSocket starts as an HTTP request with an Upgrade: websocket header. The server answers 101 Switching Protocols, and from then on each side sends whenever it likes (RFC 6455 §1.2). A frame header is 2 bytes for payloads up to 125 bytes, plus a 4-byte masking key on frames from the client (§5.2, §5.3), so a 100-byte message costs 102 bytes down and 106 up. The price is a stateful connection that every proxy must allow and that a server restart or crash breaks. RFC 6455 §1.5 is explicit: Other than that, WebSocket adds nothing. Acknowledgements, message IDs, ordering across reconnects and resuming after a drop are the application's job, which is lesson 3.

Per-message cost and requirements · RFC 6202 §2.2, RFC 6455 §5.2, SSE format
                   long polling          SSE + POST             WebSocket
server -> client   full HTTP response    data: line per event   2-byte frame header
client -> server   full HTTP request     full HTTP request      6-byte frame header
held per client    1 connection and      1 connection and       1 connection
                   1 pending request     1 open response
passes through     any HTTP path         HTTP paths that do     paths that allow
                                         not buffer responses   the upgrade

For a chat client that sends often, WebSocket is the usual primary transport, with long polling or SSE plus POST as a fallback where the upgrade is blocked. It is not the only reasonable choice: a feed where people rarely reply is simpler on SSE plus POST, and a small internal tool may be cheaper on long polling.

03. A gateway tier and a session registry

The gateway tier
devices            load balancer       gateways         services
phone  --wss-->    places each   -->   gw A  <----->   chat service --> message store
laptop --wss-->    connection    -->   gw B  <----->        |
phone  --wss-->    once          -->   gw C  <----->   session registry
                                                       user -> (device, gateway)

A gateway does as little as possible: it checks the user's token during the handshake, holds the sockets, answers pings, passes client frames to the chat service and writes frames into its own sockets. Message logic lives in services behind it, which can restart without dropping anyone's socket. Slack's 2023 write-up describes this kind of split: gateway servers hold the websockets, in front of channel servers that are themselves stateful, in-memory owners of channels.

The session registry answers who is connected where. When a device connects, its gateway writes user -> (device, gateway) and deletes it on a clean close. To deliver a message, the chat service looks up each recipient and sends one copy to each gateway holding one of their devices, and to no other.

The demo below routes across two gateways. It needs Python 3.12 and the websockets package, checked with version 17.4: run python3.12 -m venv .venv and .venv/bin/pip install websockets==17.4, then save the file as gateway_demo.py. It listens only on 127.0.0.1, ports 18101 and 18102.

Python · gateway_demo.py
"""Two chat gateways and a session registry in one process (websockets 17.4)."""
import asyncio
import json

from websockets.asyncio.client import connect
from websockets.asyncio.server import serve

REGISTRY: dict[str, str] = {}  # user -> gateway; stands in for a shared store
INBOX: dict[str, asyncio.Queue] = {}  # gateway -> queue; stands in for a channel each
OFFLINE: list[dict] = []  # messages for users with no live connection


class Gateway:
    def __init__(self, name: str, port: int):
        self.name, self.port = name, port
        self.sockets = {}  # user -> the socket THIS gateway holds
        INBOX[name] = asyncio.Queue()

    async def handler(self, ws):
        user = ws.request.path.strip("/")  # demo only: real gateways authenticate
        self.sockets[user] = ws
        REGISTRY[user] = self.name
        print(f"[{self.name}] {user} connected, registry {REGISTRY}")
        try:
            async for raw in ws:
                await route(self.name, json.loads(raw))
        finally:
            del self.sockets[user]
            if REGISTRY.get(user) == self.name:
                del REGISTRY[user]
            print(f"[{self.name}] {user} left, registry {REGISTRY}")

    async def deliver(self):
        while True:
            msg = await INBOX[self.name].get()
            ws = self.sockets.get(msg["to"])
            if ws is None:  # the user left between lookup and delivery
                OFFLINE.append(msg)
                continue
            await ws.send(json.dumps(msg))


async def route(via: str, msg: dict):
    target = REGISTRY.get(msg["to"])
    if target is None:
        print(f"[{via}] {msg['to']} is offline: store it and send a push")
        OFFLINE.append(msg)
        return
    print(f"[{via}] {msg['frm']} -> {msg['to']}: registry says {target}")
    await INBOX[target].put(msg)


async def until(check):  # wait for the server side to catch up, without sleeps
    while not check():
        await asyncio.sleep(0.01)


async def main():
    gws = [Gateway("gw-a", 18101), Gateway("gw-b", 18102)]
    servers = [await serve(g.handler, "127.0.0.1", g.port) for g in gws]
    workers = [asyncio.create_task(g.deliver()) for g in gws]
    clients = {}
    for user, port in [("alice", 18101), ("bob", 18102), ("carol", 18101)]:
        clients[user] = await connect(f"ws://127.0.0.1:{port}/{user}")
        await until(lambda: user in REGISTRY)

    for to, text in [("bob", "lunch at noon?"), ("carol", "you too?")]:
        msg = {"frm": "alice", "to": to, "text": text}
        await clients["alice"].send(json.dumps(msg))
        print(f"{to} received {json.loads(await clients[to].recv())['text']!r}")

    await clients["bob"].close()
    await until(lambda: "bob" not in REGISTRY)
    msg = {"frm": "alice", "to": "bob", "text": "ok?"}
    await clients["alice"].send(json.dumps(msg))
    await until(lambda: OFFLINE)
    print("waiting for bob:", [m["text"] for m in OFFLINE])

    for ws in (clients["alice"], clients["carol"]):
        await ws.close()
    for t in workers:
        t.cancel()
    for s in servers:
        s.close()
        await s.wait_closed()


asyncio.run(main())
Terminal
.venv/bin/python gateway_demo.py
Expected output
[gw-a] alice connected, registry {'alice': 'gw-a'}
[gw-b] bob connected, registry {'alice': 'gw-a', 'bob': 'gw-b'}
[gw-a] carol connected, registry {'alice': 'gw-a', 'bob': 'gw-b', 'carol': 'gw-a'}
[gw-a] alice -> bob: registry says gw-b
bob received 'lunch at noon?'
[gw-a] alice -> carol: registry says gw-a
carol received 'you too?'
[gw-b] bob left, registry {'alice': 'gw-a', 'carol': 'gw-a'}
[gw-a] bob is offline: store it and send a push
waiting for bob: ['ok?']
[gw-a] alice left, registry {'carol': 'gw-a'}
[gw-a] carol left, registry {}

Alice's message for Bob goes from gw-a to gw-b, as the registry says. Once Bob has left, the lookup finds nothing, so the message waits in storage and a push goes out.

The demo simplifies two things. Its registry and inboxes live in one process, with one gateway per user, enough for one device each; a production registry is a shared, replicated store, so lookups can be stale. And a demo disconnect always runs the finally block, while a crashed gateway runs nothing. Registries therefore attach a lease to each entry: the gateway renews its entries every few seconds, and entries it stops renewing expire. A stale entry then delays a message rather than losing it, if each message is stored before delivery.

04. Why a registry and not a channel per conversation?

The WebSocket cluster lab routes differently. It keeps one pub/sub channel per room: a worker subscribes to room:<id> when the first local member of that room joins and unsubscribes when the last one leaves. Messages reach only workers with members, and no registry is needed. A third option, one channel that every gateway subscribes to, sends every message to every gateway. fanout_compare.py prices the three at lesson 1's peak, assuming each user belongs to 200 conversations, one-to-one chats included (a guess; Python 3.12, standard library only):

Python · fanout_compare.py
"""Three ways to get a message to the right gateways, priced (Python 3.12)."""
CONNS, GATEWAYS = 8_125_000, 136  # peak connections and gateways (lesson 1)
SENDS, RECIPS = 23_148, 4.0  # peak messages per second, recipients per message
DEVICES = 55_093 / SENDS  # recipient and echo devices online per message (lesson 1)
CONVS = 200  # conversations a user belongs to, one-to-one chats included: a guess
STORM = 2_748_162  # devices that reconnect when the largest zone fails (lesson 1)

# (subscriptions held, calls per device connect, gateways reached per message,
#  registry lookups per message); per conversation counts are upper bounds
DESIGNS = {
    "shared": (GATEWAYS, 0, GATEWAYS, 0),
    "per conversation": (CONNS * CONVS, CONVS, DEVICES + 1, 0),  # +1: sender's own
    "per gateway": (GATEWAYS, 1, DEVICES, RECIPS + 1),  # +1: sender's echo
}
ROWS = [
    ("subscriptions the broker holds", lambda d: d[0], ",.0f"),
    ("calls per device connect", lambda d: d[1], ",.0f"),
    ("calls when a zone reconnects", lambda d: d[1] * STORM, ",.0f"),
    ("gateways reached per message", lambda d: d[2], ",.1f"),
    ("gateway receives per s, peak", lambda d: d[2] * SENDS, ",.0f"),
    ("registry lookups per s, peak", lambda d: d[3] * SENDS, ",.0f"),
]
print(f"{'channel':<31}" + "".join(f"{name:>19}" for name in DESIGNS))
for label, cost, fmt in ROWS:
    cells = "".join(f"{format(cost(d), fmt):>19}" for d in DESIGNS.values())
    print(f"{label:<31}{cells}")
Terminal
python3.12 fanout_compare.py
Expected output
channel                                     shared   per conversation        per gateway
subscriptions the broker holds                 136      1,625,000,000                136
calls per device connect                         0                200                  1
calls when a zone reconnects                     0        549,632,400          2,748,162
gateways reached per message                 136.0                3.4                2.4
gateway receives per s, peak             3,148,128             78,241             55,093
registry lookups per s, peak                     0                  0            115,740

Per message, a channel per conversation costs about what the registry does: 3.4 gateways reached against 2.4, while one shared channel delivers to all 136. The difference is the state: the broker holds a subscription for every conversation of every connected device, up to 1.6 billion here (two members on one gateway share one), and each device that connects costs up to 200 subscribe calls, so lesson 1's zone failure becomes up to 550 million calls during a reconnect storm. A channel per gateway holds 136 subscriptions and one registry write per connect, but needs about 115,700 batchable lookups a second at peak. Per-room channels fit when rooms are large and each user is in a few; they cost broker state and reconnect churn when users hold hundreds of small conversations. Slack's 2023 write-up describes interest-based subscription at scale: its gateways subscribe to the channel servers, found by consistent hashing, that hold a user's channels.

05. What the load balancer does, and does not do

The load balancer places connections; it does not route messages. After the handshake every frame on a connection reaches the same gateway, because it is one TCP connection, so there is nothing to balance per message, and sticky sessions (see the load-balancing lesson) add nothing to an open WebSocket. Stickiness matters for transports built from many requests, such as long polling, if servers keep per-client state; sending the client's last position with every poll removes that need.

Placement happens once per connection, so balance on open connections at connect time; a gateway added at 2 p.m. receives only new connections. Idle connections also need traffic, because balancers, proxies and NAT devices close silent connections, so heartbeats must come more often than the shortest idle timeout on the path (see the proxies and deploys lesson). The Python websockets 17.4 server sends a Ping every 20 s by default and closes the connection if no Pong arrives within 20 s.

06. Reconnect storms

In lesson 1, losing one zone sent about 2.7 million clients to 90 surviving gateways. Each reconnect costs a TLS handshake, a token check, a registry write and a catch-up read; if all arrive within seconds, survivors burn their CPU and the failure spreads. RFC 6455 §7.2.3 names this risk, what amounts to a denial-of-service attack, and asks clients to delay the first attempt by a random amount (0 to 5 seconds is called reasonable) and to wait longer after each failure. Servers also need protection from clients that ignore this:

  • Admission control. Each gateway accepts only so many new handshakes per second and turns the rest away cheaply, with an HTTP 503 before the upgrade. Native clients can honour a Retry-After header; browsers see only a failed connection, so their randomised backoff must do the spreading.
  • Cheap catch-up. A reconnecting device sends its position and gets only what it missed (lessons 3 and 4).
  • Headroom. Lesson 1's 60% target lets survivors hold the moved connections.

Planned restarts are gentler: the gateway closes sockets in batches with code 1001, going away (see the deploys lesson). A crash sends no close frame; clients report 1006, reserved by RFC 6455 §7.4.1 for that case.

When is this too much? A registry earns its keep with dozens of gateways and many small conversations. If connections fit on a few machines, or conversations are large rooms, the per-room channels of the cluster lab are simpler.

07. Check your understanding

Practice check · 3 questions

Transports and gateways

Three situations from running a gateway tier.

Q1. The session registry stores one entry per user, overwritten on each connect. Bob's phone connects to gw-b, then his laptop connects to gw-c. What happens to new messages for Bob?
Q2. At one company, chat never connects from the office network: a proxy there rejects WebSocket upgrade requests, but ordinary HTTPS works. What should the client do?
Q3. A long-polling server has just answered a poll with message 1. Message 2 reaches the server 5 ms later. Why can message 2 take noticeably longer than message 1 to reach the client?
Practice only: not graded, not saved, not evidence.

08. Apply it

Start this skill's practice prototype by replacing the demo's in-process parts:

  1. Run each gateway as its own process, with the registry in a shared store such as Redis, keyed by user and device.
  2. Give each gateway its own pub/sub channel, such as gw:<name>, and publish each message only to the recipient's gateway.
  3. Renew entries every 10 s with a 30 s expiry; kill -9 one gateway and show its entries expire.

In your design doc, count the registry lookups and pub/sub messages of one message to a 500-member group.

09. Review prompt

Without looking back, answer in your own words:

  1. Compare long polling, SSE plus POST and WebSocket for chat on cost, latency and network needs.
  2. What does RFC 6455 leave to the application, and why does it matter?
  3. How does a registry route a message, and when would per-room channels be better?
  4. Walk through a reconnect storm after a zone failure and three measures that contain it.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check