Sub topic 4
High-level architecture: stateless APIs and stateful chat servers
This chapter assumes you know basic client-server and HTTP concepts, have used databases and key-value stores, and understand that a TCP connection can stay open. It also assumes you can read short JavaScript and Python snippets. Earlier chapters set the requirements, the traffic estimates, and the choice of WebSocket for real-time delivery. This chapter turns those decisions into a service layout.
The core idea: split by state
A chat system has two kinds of work with different needs.
- Request/response work. Examples are logging in, loading a profile, creating a group, and fetching old messages. Each request is independent. Any server can answer it.
- Real-time work. Examples are pushing a new message to a recipient and reporting that a user is typing. This work needs a long-lived connection, and the server that holds the connection must remember who is on the other end.
The first kind fits stateless services. A stateless service keeps no per-user data between requests. It reads what it needs from a database or cache on every call. The second kind needs a stateful service. A stateful service keeps data in memory that is tied to specific clients, such as an open socket and the user ID attached to it.
Splitting the system along this line lets you scale and fail each half in the way that suits it.
Components
| Component | State | Role |
|---|---|---|
| Load balancer | Stateless | Spreads HTTP requests and WebSocket upgrades across servers |
| API servers | Stateless | Login, profiles, groups, history fetch, settings |
| Chat servers | Stateful | Hold WebSocket connections, accept sends, push messages out |
| Service discovery | Shared state | Tells a client which chat server to connect to |
| Presence service | Shared state | Tracks who is online, using heartbeats |
| Message store | Durable state | Persists messages and conversations |
| Session registry | Shared state | Maps each user to the chat server holding their connection |
| Message queue or pub/sub | Transient state | Moves messages between chat servers |
| Push notification service | Stateless | Notifies offline users through the mobile platform |
Two things make the layout work. The chat servers never rely on their own memory for anything that must survive a crash. The shared state lives in the stores and registries listed above.
Stateless API servers
API servers handle the ordinary web traffic. Because they hold nothing between requests, you can:
- Add or remove servers at any time and let the load balancer adjust.
- Replace a crashed server without any user noticing, since the next request goes elsewhere.
- Deploy new versions by rolling them out a few servers at a time.
Authentication fits this model if you use signed tokens or look sessions up in a shared store. The server checks the token on every request and needs no local session.
Typical endpoints:
POST /loginreturns a token and the address of a chat server.GET /chatslists a user's conversations.GET /chats/{id}/messages?before=...returns a page of history.POST /groupscreates a group.
History fetch uses plain HTTP on purpose. Pagination, caching, and retries are well understood there, and a client with no live connection can still load old messages.
Stateful chat servers
A chat server accepts WebSocket connections and keeps an in-memory table from user (or device) to open socket. When a message arrives for a user, the server finds the socket in this table and writes to it. This is the part that cannot be stateless, because the socket exists only on the machine that accepted it.
Consequences of holding state:
- A connection is pinned to one server for as long as it lasts. The load balancer picks the server once, at connection time.
- Draining takes care. To retire a server, stop accepting new connections, ask clients to reconnect elsewhere, and wait for the table to empty.
- A crash drops every connection on that server. Clients must reconnect with backoff, and they must resend anything unacknowledged. Chapter material on acknowledgements and idempotent writes covers that in detail.
- Memory and file descriptors limit capacity. Each connection costs memory and an open socket. The estimates from the earlier chapter tell you how many servers you need.
How a client connects
- The client logs in over HTTPS through an API server and receives a token.
- The client asks service discovery for a chat server. Discovery picks one using location, current load, or a hash of the user ID.
- The client opens a WebSocket to that server and presents the token.
- The chat server validates the token, registers the connection, and records
user -> this serverin the session registry. - The client sends heartbeats so the presence service knows it is online.
Step 4 matters most for routing. Without the registry, a server that receives a message for Bob has no way to know where Bob's socket lives.
Routing between chat servers
Alice and Bob are often connected to different chat servers. The sending server therefore needs a way to hand a message to Bob's server.
There are two common designs.
- Lookup, then direct forward. The sender's server asks the session registry where Bob is, then sends the message to that server directly.
- Pub/sub per user or per partition. Each chat server subscribes to a channel for the users it holds. The sender's server publishes to Bob's channel and does not need to know his server.
Direct forward has fewer moving parts and lower latency. Pub/sub removes the lookup, so the sender needs no knowledge of Bob's location, but it adds a broker that must scale and stay available. Large systems often use a message queue between chat servers and a partitioning scheme so that all traffic for a given user or chat lands on a predictable consumer.
Here is a minimal sketch of the routing decision in Python. It uses in-memory dictionaries in place of the real registry and network calls, so you can run it as shown.
sessions = {} # user_id -> server_id (session registry)
servers = {} # server_id -> {user_id: list of delivered messages}
def connect(user_id, server_id):
sessions[user_id] = server_id
servers.setdefault(server_id, {})[user_id] = []
def disconnect(user_id):
server_id = sessions.pop(user_id, None)
if server_id:
servers[server_id].pop(user_id, None)
def route(recipient_id, message):
server_id = sessions.get(recipient_id)
if server_id is None:
return "offline" # hand off to push notifications
servers[server_id][recipient_id].append(message)
return f"delivered via {server_id}"
connect("alice", "chat-1")
connect("bob", "chat-2")
print(route("bob", {"from": "alice", "text": "hi"}))
disconnect("bob")
print(route("bob", {"from": "alice", "text": "still there?"}))The first call prints delivered via chat-2. After Bob disconnects, the second prints offline, and a real system would store the message and send a push notification.
Where the message store fits
A chat server should write a message to the durable store before it reports success to the sender. Delivery to the recipient's socket is a separate step. If Bob is offline, the message is already safe and waits for him. When he reconnects, his client asks for everything after the last sequence number it saw.
This order has a cost. A write on the critical path adds latency to every send. The alternative is to acknowledge first and persist later, which is faster but can lose a message if the server crashes in between. Most chat systems choose durability first, because a lost message is a visible failure.
Design trade-offs
| Decision | Option A | Option B | Deciding factor |
|---|---|---|---|
| Send path | Chat server over the open socket | HTTP POST to an API server | Latency and connection reuse favor the socket. HTTP is simpler and retries cleanly. |
| Cross-server routing | Registry lookup, direct forward | Pub/sub broker | Fewer components versus less coupling |
| Connection assignment | Hash of user ID | Least-loaded server | Predictable placement versus even load |
| Service split | One combined service | Separate API and chat tiers | Combined is simpler early. Separate scales and deploys independently. |
Some systems accept sends over HTTP and use the WebSocket only for pushing messages down to clients. This keeps write logic in the stateless tier, and the chat servers shrink to delivery only. It costs an extra network hop, and it is a reasonable choice if your chat servers are hard to deploy.
Common errors
- Sticky state in API servers. Keeping sessions in local memory breaks the moment a second API server appears.
- Stale registry entries. If a chat server crashes, its entries stay in the registry. Give entries a time-to-live and refresh them with heartbeats, or delivery will target a dead server.
- No reconnect storm plan. When a chat server dies, thousands of clients reconnect at once. Use randomized exponential backoff on the client.
- Treating the socket table as the source of truth. A message pushed to a socket may never reach the client. Only an acknowledgement from the client confirms delivery.
- One shared chat server pool for everything. Heavy operations such as history queries compete with real-time pushes. Keep them in the API tier.
Exercise
A user's chat server crashes while three messages sit unacknowledged in the client's pending list. Name the components that must hold the data needed to recover, and say why the chat server's own memory cannot.
Show answer
The message store holds the durable copy of any message already accepted, and the client's pending list holds the unacknowledged ones for resending. The session registry (with a time-to-live) must be updated so other servers stop routing to the dead server, and the client's reconnect creates a new entry. The chat server's memory is lost in the crash, so it cannot be the source of truth for messages or for who is connected.
Exercise
Why is loading chat history served by stateless API servers over HTTP and not by the chat servers over WebSocket?
Show answer
History reads need no persistent connection or per-client memory, so any server can answer them. Keeping them off the chat servers protects real-time delivery from heavy queries, lets you scale the API tier independently, and allows normal HTTP caching, pagination, and retries.