SWEPrep
HomeBlogStart free
System DesignHard• 10 min read• Updated 2026-11-24

Designing a Real-Time Chat System: WebSockets at Scale

Most candidates start drawing boxes for chat by creating a database table and polling it every second. That is an immediate red flag. Real-time messaging requires stateful connections, distributed session routing, and crystal clear delivery semantics. Here is how I evaluate a chat architecture on the whiteboard.

1. Why HTTP Polling Fails and WebSockets Win

Traditional HTTP request-response fails for chat at scale. Short polling floods your web servers with empty requests. Long polling holds HTTP connections open, but rebuilding TLS handshakes on every message adds 100ms of unnecessary latency.

WebSockets provide full-duplex, bidirectional communication over a single persistent TCP connection. After an initial HTTP 101 Upgrade handshake, message frames travel with only 2 to 6 bytes of overhead instead of full HTTP headers.

2. Connection Management for 50 Million Sockets

You cannot hold 50 million concurrent TCP sockets on one machine. A tuned Linux instance running epoll can handle roughly 1 million idle connections before running out of file descriptors and memory.

Each TCP socket requires send and receive buffers, usually consuming between 10KB and 40KB of kernel memory. One million idle connections consume around 20GB of RAM.

We deploy a dedicated WebSocket Gateway fleet of 60 to 80 nodes behind Layer 4 Network Load Balancers. The gateways hold socket connections and translate incoming frames into internal events.

The Stateful Challenge
Unlike stateless API servers, you cannot round-robin requests between chat nodes. Once Alice connects to Gateway Node 14, every message sent to Alice must route specifically to Gateway Node 14.
Live Technical Interview Practice
Practice this topic on the interactive AI whiteboard

Do not just read the solution. Test your architecture under realistic interview pressure with an AI interviewer probing bottlenecks in real time.

Want to practice this in a real interview? Start free →

3. Routing Messages Between Disconnected Servers

Suppose Alice is connected to Gateway 14, and Bob is connected to Gateway 52. Alice sends a message to Bob. How does Gateway 14 route it to Gateway 52?

We maintain a distributed Session Registry in a Redis cluster or distributed hash table. The registry maps user_id to gateway_server_id.

When Gateway 14 receives the message, it checks the registry for Bob. Seeing Bob is on Gateway 52, it publishes the payload to Gateway 52 via a message bus (such as Apache Pulsar, Kafka, or Redis Pub/Sub). Gateway 52 receives the payload and pushes it down the active WebSocket connection to Bob.

4. Delivery Guarantees and Offline Storage

What happens if Bob is on a subway train with no cell signal?

We use an at-least-once delivery model. When Alice sends a message, her client assigns it a client-generated UUID. The server persists the message to a write-optimized database like Apache Cassandra or ScyllaDB before sending an ACK back to Alice.

If Bob is offline, the message remains stored with status delivered = false. When Bob reconnects, his client sends its last known message sequence ID. The gateway fetches all unread messages in order and streams them to his device.

Bob device uses the message UUID to deduplicate any messages sent twice during connection drops.

CREATE TABLE messages (
    conversation_id uuid,
    message_id timeuuid,
    sender_id uuid,
    content text,
    created_at timestamp,
    PRIMARY KEY (conversation_id, message_id)
) WITH CLUSTERING ORDER BY (message_id ASC);

5. The Presence Trap: Heartbeats vs Fan-Out

Presence (who is online, who is away) is an exponential fan-out problem.

If a user with 500 contacts logs in, broadcasting that event to 500 people generates 500 socket writes. If 100,000 users connect during a peak hour, that produces 50 million broadcast messages.

To solve this, do not broadcast raw TCP connect events. Clients send a lightweight heartbeat every 30 seconds to refresh a key in Redis with a 45-second TTL. Presence is fetched on-demand when opening an active chat thread, rather than globally broadcast to every dormant contact.

Key Architecture Decisions & Trade-offs

Decision AreaOptions EvaluatedRecommendation
Transport ProtocolWebSockets vs Server-Sent Events (SSE)WebSockets. Chat requires bidirectional low-latency communication. SSE only pushes server to client.
Database EngineCassandra/ScyllaDB vs PostgreSQLCassandra. Sequential write throughput and time-series clustering order match chat conversation access patterns.
Fan-Out ModelGlobal presence broadcast vs On-demand queryOn-demand query plus batched active subscriptions. Eliminates quadratic presence fan-out storms.

Frequently Asked Interview Follow-ups

How do you handle end-to-end encryption in this architecture?
Use the Signal Protocol. The server acts only as an untrusted ciphertext relay and public key bundle distributor. Message contents are encrypted and decrypted strictly on user devices.
How do group chats differ from 1-on-1 chats?
For small groups (under 200 members), fan-out on write into each member inbox works well. For massive public channels (10,000+ members), switch to fan-out on read from a single shared channel log.
How do you guarantee strict message ordering?
Use monotonic message sequence numbers generated by the conversation shard, or a combination of millisecond timestamps and Cassandra TimeUUID clustering.
Ready for the interview loop?

Test your design under real pressure

Simulate a full 45-minute technical session on SWEPrep. Diagram architecture on the canvas, justify your trade-offs, and receive instant rubric feedback.

Want to practice this in a real interview? Start free →

Keep practicing

View all guides →