Architect a Multi-Tenant Team Chat Service with Live Delivery
System DesignModel answerLast updated
Design a multi-tenant team chat product covering channels, DMs, real-time delivery, history sync, search, and notifications, with per-channel ordering and tenant isolation.
Problem
Design the backend for a team chat product in which organizations (workspaces) have their own members and conversations.
Functional requirements
- Workspaces act as tenants. Each has users and channels, which may be public or private.
- Direct conversations: one-to-one and small group chats.
- Messages are delivered in real time to web and mobile clients.
- Message history is persisted and stays in sync across a user's devices.
- Users can search messages within their own workspace.
- Notifications fire for mentions, direct messages, and (optionally) channel activity.
Non-functional requirements
- High availability and low delivery latency.
- Scales to a very large number of workspaces, and to individual channels with tens of thousands of members.
- Messages within one channel keep a consistent order.
- Strong security and data isolation between workspaces.
What to cover
- High-level architecture
- Key APIs and the data model
- The real-time delivery mechanism
- Storage and sharding strategy
- How search and notifications work
- Major trade-offs and bottlenecks
State your own scale assumptions up front and use them to justify your choices.
Hints
Hint 1
Decide early whether a message is stored once per channel or once per recipient, and see how that choice affects write cost for a 50K-member channel.
Hint 2
Ordering only has to hold inside a channel. Think about what single component can hand out a monotonically increasing sequence number per channel, and how clients can detect and repair gaps.
Hint 3
For fanout, avoid looping over members. Consider having each connection server subscribe to channels, so a message is published once per channel and cost scales with servers, not members.
Hint 4
Use different stores for different needs: relational metadata sharded by tenant, a wide-column store for message history partitioned by channel, and a separate search index fed asynchronously from an event log.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Scope and assumptions
I would state these numbers up front:
- 1M workspaces, 20M daily active users, about 10M concurrent connections at peak.
- Most workspaces have under 100 users, but enterprise tenants reach 100K+ users and some channels have 50K+ members.
- About 100 messages per user per day, so around 2B messages/day. That is roughly 23K writes/s on average and about 100K/s at peak.
- About 1 KB per message with metadata: roughly 2 TB/day raw, about 6 TB/day replicated 3x, with indefinite retention, so petabytes over time.
- Targets: p99 delivery under 200 ms to online recipients, history load under 300 ms.
- Guarantees: total order within a channel, no lost messages, idempotent sends. No cross-channel ordering.
Key insight: store each message once per channel, not once per recipient. Per-user state (read position, notification preferences) is stored separately. Write cost then does not depend on channel size.
2. APIs
Use REST or gRPC for request/response and one WebSocket per device for push.
POST /v1/channels/{id}/messages {client_msg_id, text, thread_root?, attachments?} -> {seq, ts}
GET /v1/channels/{id}/messages?before_seq=&after_seq=&limit=50
PATCH/DELETE /v1/channels/{id}/messages/{seq}
POST /v1/channels {workspace_id, name, is_private, members}
POST /v1/channels/{id}/read {last_read_seq}
GET /v1/sync?cursor=
GET /v1/search?workspace_id=&q=&from=&in=&before=
WS /v1/rtm events: message.new, message.edited, typing, presence, read_marker
client_msg_id is an idempotency key. Retries from flaky mobile networks do not create duplicates, and the client can match its optimistic local copy to the server's copy.
3. Data model
Metadata (relational, sharded by workspace_id, for example Vitess or sharded Postgres):
workspaces,userschannels(id, workspace_id, type {public, private, dm, group_dm}, name, last_seq)channel_members(channel_id, user_id, role, last_read_seq, notif_prefs)plus a reverse index from user to channels
Messages (wide-column, for example Cassandra or ScyllaDB):
- Partition key
(channel_id, time_bucket), clustering keyseq DESC. - Columns: sender, text, thread root, edited_at, deleted flag, client_msg_id.
- Monthly buckets keep partitions bounded for busy channels. A history page is a single-partition range scan.
DMs are just channels of type dm, with an ID derived deterministically from the sorted user IDs. Every feature then works identically for channels and DMs.
4. Architecture
Clients -WS-> Edge/LB -> Gateway fleet (stateful, ~100K conns each)
Clients -REST-> API services -> Message Service -> Kafka (keyed by channel_id)
Kafka consumers: fanout to gateways, search indexer, notification service, unread counters
Metadata DB (by workspace) | Message store (by channel) | Redis (presence, routing, hot cache)
Send path: authenticate, verify channel membership, assign the next seq, persist, ack the sender, then publish to Kafka. Everything downstream is asynchronous, so a slow search index or push provider never blocks sending.
5. Deep dives
Ordering
Each channel needs one sequencer. Options:
- Route all writes for a channel to an owner node using consistent hashing with leases. The owner increments
last_seqin memory and checkpoints it. - Or use an atomic conditional increment on the channel row (simpler, but a per-channel hot row).
(channel_id, seq) is the message identity and order. Partitioning Kafka by channel_id preserves order for consumers. Clients render by seq, and if they see a gap (they receive 105 after 103) they fetch the missing range. That gives effectively exactly-once display on top of at-least-once delivery.
Real-time fanout
Never loop over members per message; that is O(members) and fails at 50K.
- Each gateway subscribes to every channel that at least one of its connected users belongs to.
- A message is published once per channel and reaches only interested gateways, which deliver to local sockets.
- Cost scales with the number of gateways (about 100), not members.
On reconnect, the client sends per-channel cursors to /sync. Small gaps return the missing messages. Large gaps return only unread counts and the latest seq, and history is loaded lazily when the channel is opened.
To survive reconnect storms: jittered exponential backoff on clients, gradual connection draining during deploys, and paginated sync.
Typing and presence are ephemeral, best-effort, rate-limited, and never persisted. In large workspaces, fetch presence only for users currently visible.
Storage and sharding
- Metadata is sharded by
workspace_idfor tenant locality, simple isolation, and per-tenant migration. Oversized tenants get dedicated shards or are sub-sharded by channel. - Messages are partitioned by
channel_id, which spreads load even inside a huge tenant. - Hot announcement channels cause read storms. Cache the latest N messages per channel in Redis, since most reads are recent history.
- Tier old buckets to cheaper storage. Pin each workspace to a region for data residency.
Search
- A Kafka consumer indexes messages, edits, and deletes into Elasticsearch or OpenSearch. Indexing is eventually consistent, typically within seconds.
- Route documents by
workspace_id, giving big tenants their own indices. - Enforce permissions at query time: filter to channels the user can access (public channels plus private channels and DMs they belong to). Cache the user's channel set, and handle membership changes by re-checking at query time.
- Deletes must propagate to the index, including for compliance.
Notifications
A notification consumer reads the event stream and decides per recipient:
- Mentions, DMs, and keyword matches are high priority. General channel activity is opt-in.
- Skip users who are online and actively viewing the channel. Respect do-not-disturb, mute settings, and per-channel preferences.
- Send via APNs/FCM, with email as a delayed fallback if unread after some time. Batch or collapse bursts.
- For
@channelin a huge channel, fan out through a queue with rate limits instead of inline.
Security and isolation
Every request carries a workspace-scoped token. Check membership on every read and write, and include workspace_id in all queries and index filters. Use per-tenant encryption keys for enterprise customers if required.
6. Trade-offs and bottlenecks
- Single sequencer per channel gives strict order but is a hot spot for extremely active channels. Mitigate with leases, fast failover, and batching.
- Channel-level pub/sub vs per-user inboxes: pub/sub is cheap for big channels, but unread counts and per-user state need separate handling. Counters are updated lazily, not per message per user.
- Cassandra vs relational for messages: wide-column gives write throughput and easy scaling, but weaker secondary access. That is why search is a separate index.
- Search consistency: a short lag is acceptable and avoids coupling write latency to indexing.
- Gateway statefulness: stateful connections complicate deploys and failover; draining and backoff are required.
Common mistakes
- Storing one copy of a message per recipient.
- Guaranteeing global ordering instead of per-channel ordering.
- Doing fanout by iterating over members.
- Putting search indexing or push delivery in the synchronous send path.
- Forgetting idempotency keys and gap detection on the client.
- Ignoring permission filtering in search results.