Sub topic 4
High-level architecture: stateless APIs and stateful chat servers
This chapter assumes you know basic HTTP, what a persistent connection is, and how key-value stores and databases differ. It builds on the earlier choice of WebSocket for real-time delivery.
Two kinds of servers
A chat system has two traffic patterns, and they need different servers.
- Request/response traffic covers login, profile edits, group creation, and fetching history. Each request is independent, so any server can answer it.
- Real-time traffic is the stream of messages pushed over long-lived WebSocket connections. The server must remember which user is connected to it.
The first kind belongs on stateless API servers. They keep no per-user memory between requests, so you can put them behind a load balancer and add or remove machines freely. The second kind belongs on stateful chat servers. Each one holds thousands of open connections and knows which users are attached to it.
The components
| Component | Role | State |
|---|---|---|
| Load balancer | Spreads HTTP requests and WebSocket upgrades | None |
| API servers | Auth, profiles, groups, history reads | None |
| Chat servers | Hold WebSocket connections, forward messages | Connection table in memory |
| Session registry | Maps each user to the chat server holding their connection | Key-value store, with TTL |
| Message store | Durable chat history | Persistent database |
| Push service | Notifies users who are offline | Queue-backed |
The session registry is the piece that makes stateful servers workable. Without it, a server that receives a message for Bob cannot know whether Bob is connected, or where.
How the pieces cooperate
- A client calls an API server to log in and receives a token and the address of a chat server.
- The client opens a WebSocket to that chat server and authenticates with the token.
- The chat server writes
user_id -> server_idinto the session registry. - When Alice sends a message, her chat server stores it, then looks up Bob in the registry.
- If Bob is on another chat server, the message is forwarded server to server. If Bob has no entry, the push service handles it.
Here is the registry logic in Python:
import time
REGISTRY_TTL = 60
registry = {}
def register(user_id, server_id, now=None):
now = now if now is not None else time.time()
registry[user_id] = (server_id, now + REGISTRY_TTL)
def locate(user_id, now=None):
now = now if now is not None else time.time()
entry = registry.get(user_id)
if entry is None or entry[1] < now:
return None
return entry[0]
register("bob", "chat-2", now=100)
assert locate("bob", now=120) == "chat-2"
assert locate("bob", now=200) is NoneA real registry would be a shared store such as Redis, with the same expiry idea.
Trade-offs and common errors
- Stateful servers are harder to operate. Deploying a new version drops connections, so clients must reconnect with backoff. Otherwise a restart causes a reconnect storm.
- Stale registry entries. If a chat server crashes, its entries linger until the TTL expires. Treat a failed forward as "user offline" and fall back to push, rather than losing the message.
- Keeping state off the API tier. Teams sometimes cache session data in API server memory. This breaks the moment the load balancer sends the next request elsewhere.
- Sending messages through the API. Sending over HTTP is possible, but it adds a request per message. Using the existing WebSocket is cheaper.
Exercise
Why must the session registry be a shared store instead of a dictionary inside each chat server?
Show answer
A chat server receiving a message for Bob must find out which server holds Bob's connection. A private dictionary only knows about its own connections, so it cannot route to users attached to other servers. A shared store gives every chat server the same view.