Chat System System Design
A Slack / Discord-style real-time messaging service
By Ankur NayakReviewed
Deliver messages between users and channels in well under a second, keep every message forever, and show who is online. Built on persistent WebSocket connections, a channel fan-out layer and a message store partitioned by channel and time.
Open in Studio· edit a copy- Users
- 50M daily active users
- Throughput
- ~1M messages/s at peak
- Storage
- Trillions of messages
- Concurrent connections
- Tens of millions
- Delivery target
- < 500 ms
Requirements
Functional
- One-to-one and group/channel messaging
- Real-time delivery to every online member
- Message history with infinite scroll
- Online presence and typing indicators
- Push notifications for offline users; attachments
Non-functional
- End-to-end delivery under 500 ms for online users
- Messages are never lost once acknowledged, and appear in order per channel
- Highly available; tolerate gateway and storage node failures
- Store history indefinitely at low cost
In depth
Two very different paths
A chat system has a real-time path (getting a message to everyone online within half a second) and a storage path (keeping trillions of messages and serving history quickly). They have different shapes, so they are built separately and joined at the chat service.
Real time: keep the connection open
Polling every few seconds wastes requests and still feels slow. Instead each client holds a WebSocket to a gateway server. Gateways are deliberately dumb: they authenticate the connection, hold it open and relay frames.
The routing intelligence sits one layer in. Slack describes channel servers that each own a slice of channels, assigned with consistent hashing, and gateway servers that hold users' subscriptions. When a message arrives, the owning channel server knows which gateways have members online and sends one copy to each gateway, which then writes it to every local member's socket. Because one server owns each channel, ordering and fan-out happen in one place.
Storage: partition by channel and time
History is read as "the latest 50 messages in this channel" and written far more than it is edited. A wide-column store partitioned by channel fits perfectly, but a busy channel would grow one partition forever. Discord solved this by adding a time bucket to the partition key, and by giving messages Snowflake IDs so they sort by time.
In 2023 Discord described migrating trillions of messages from 177 Cassandra nodes to 72 ScyllaDB nodes, with Rust data services in front that coalesce concurrent reads of the same hot channel. Historical reads dropped to about 15 ms at p99.
Acknowledge after durability
The sender's "sent" tick should mean the message is safely stored. So the chat service writes to the replicated store first and only then acknowledges and fans out. Clients attach an idempotency key, so a retry after a dropped connection doesn't create a duplicate, and after reconnecting they ask for everything after the last message ID they saw.
What interviewers look for
- Persistent connections and how a message finds the recipient's server
- Storage model and partition key, and the hot-partition problem
- Ordering, idempotency and resync after reconnect
- Offline delivery via push notifications
- Presence as cheap, eventually consistent state
Components
Desktop / Mobile App
Client. Keeps one WebSocket open while active; fetches history over HTTPS.
Edge Load Balancer
L4 / TLSLoad balancer. Routes new connections to the nearest region and a gateway with capacity.
Building block: Load Balancer
WebSocket Gateway
Realtime gateway. Holds clients' persistent connections, authenticates them and relays events in both directions.
Why: A dedicated stateful tier keeps millions of mostly idle sockets away from business logic.
Building block: WebSockets & Persistent Connections
Chat Service
Service. Validates, stores and routes each message; serves history queries.
Building block: Unique ID Generation
Validate & Authorize
Service. Checks membership, permissions and message size.
Dedupe Cache
Cache. Recent client message IDs, so a retried send isn't stored twice.
Snowflake ID
Service. Assigns a 64-bit, time-ordered message ID.
Building block: Unique ID Generation
Persist
Service. Writes to the message store; the sender is acknowledged after this.
Publish
Service. Hands the message to the channel's fan-out server and the event stream.
Channel Servers
Service. In-memory fan-out: each channel is owned by one server, which knows which gateways have members online.
Why: Consistent hashing gives every channel a single owner, so ordering and fan-out happen in one place.
Building block: Consistent Hashing, Fan-out on Write vs. Read
Session & Presence
In-memory / RedisCache. Which users are online and which gateway holds each user's connection.
Building block: Cache
Message Store
ScyllaDB / CassandraNoSQL database. Messages partitioned by channel plus a time bucket, clustered by message ID, replicated 3×.
Why: Write-heavy, append-only, and read by 'latest N in a channel': exactly what a wide-column store partitioned by channel does well.
Building block: Database Sharding, Replication, CAP Theorem
Event Stream
KafkaStream. Every stored message is published for push notifications, search indexing and analytics.
Building block: Message Queue & Event Log
Push Notifier
Service. Notifies members who are offline or have the app in the background.
APNs / FCM
External API. Apple and Google push services that wake the device.
Search Index
ElasticsearchinferredSearch index. Full-text message search per workspace.
Attachments
Object storage + CDNObject storage. Files are uploaded directly with pre-signed URLs; messages only carry the object key.
Building block: Object Storage, CDN
Request flows
Send a message to an online channel
- Alice types a message; it travels over her already-open WebSocket.
- Her gateway server receives the frame with a client-generated idempotency key.
- The gateway forwards it to the chat service, which checks she is a member of the channel.
- The message gets a Snowflake ID and is written to the store (replicated 3×).
- Only now is Alice's client acknowledged, so a 'sent' tick means durable.
- The channel's owning server receives the message.
- It knows which members are online and which gateways hold their connections.
- It sends one copy per gateway, which writes it to each member's socket.
Notify an offline member
- Every stored message is also published to the event stream.
- The push notifier sees Bob has no live connection and mentions are enabled.
- It asks APNs or FCM to show a notification on Bob's phone.
Failure scenarios
What if: a gateway server crashes?
Every connection on that server drops. Clients reconnect with jittered backoff to another gateway and ask for messages after the last ID they saw, so nothing is lost; presence briefly shows them offline.
User impact: A few seconds of 'reconnecting…' for users on that server.
- Jittered reconnect to avoid a thundering herd
- Resume from the last seen message ID
- Drain servers gradually during deploys
What if: a message store node fails?
Each partition has three replicas, so reads and writes continue on the remaining two at quorum while the node is replaced; only hot partitions on the failed node see higher latency.
- Replication factor 3 across zones
- Quorum reads and writes
- Request coalescing for hot channels
Trade-offs
Wide-column store vs. relational database
A wide-column store (Cassandra, ScyllaDB) partitioned by channel and time bucket.
- Pros
- Very high write throughput
- 'Latest N messages in a channel' is one partition read
- Linear horizontal scaling
- Cons
- No joins or ad-hoc queries
- Hot channels concentrate load on one partition
- Deletes create tombstones that slow reads
Alternatives: Sharded MySQL/PostgreSQL keyed by channel; HBase/Bigtable
Server push vs. polling
Persistent WebSockets while the app is open, platform push when it isn't.
- Pros
- Sub-second delivery
- No wasted polling requests
- Cons
- Stateful gateway tier to operate
- Reconnect storms after outages
Store once per channel vs. once per recipient
Store each message once per channel and fan out only in memory.
- Pros
- No write amplification for large channels
- Cons
- Unread counts and per-user state must be tracked separately
Alternatives: Per-user inboxes (simpler reads, but N writes per message)
Frequently asked questions
How does a chat app deliver messages in real time?
Each client keeps a persistent WebSocket open to a gateway server. When a message is stored, the server that owns the channel looks up which members are online and on which gateway, and pushes the message down those open connections. Offline users get a mobile push notification instead.
Which database is best for storing chat messages?
Chat history is append-heavy and read as 'the latest messages in a channel', which suits wide-column stores partitioned by channel. Discord moved from Cassandra to ScyllaDB in 2022, going from 177 nodes to 72 and cutting p99 history reads to about 15 ms.
How do you keep messages in order?
Give every message a time-ordered ID (for example a Snowflake ID) and let a single server own each channel's fan-out, so messages in a channel are sequenced in one place. Clients sort by ID and can request anything after the last ID they saw.
How is presence (online status) implemented?
Gateways report connects, disconnects and periodic heartbeats to a presence service that keeps state in memory. Presence is broadcast only to users who need it (for example, people viewing the same channel) and is allowed to be slightly stale.
Building blocks used
Sources
- How Discord Stores Trillions of Messages · Discord Engineering
- How Discord Stores Billions of Messages · Discord Engineering
- Real-time Messaging · Engineering at Slack
- RFC 6455: The WebSocket Protocol · IETF