Design a Multi-Tenant Real-Time Chat Platform at Global Scale
System DesignModel answerLast updated
Design a collaborative messaging system supporting thousands of isolated organizations, millions of concurrent users, real-time delivery under 200ms, and global traffic distribution.
Scenario
A company is building a team collaboration platform similar to workplace messaging tools. It needs to support 10,000 organizations ("tenants"), ranging from two-person startups to enterprises with 50,000+ employees, all sharing the same underlying infrastructure while remaining fully isolated from one another.
You are asked to design this system from scratch for a system design interview. Walk through your reasoning at each step.
Functional Requirements
- Users can send and receive messages in group channels or one-on-one conversations.
- Message history is persisted and pageable.
- Users can see whether others are online, away, or offline.
- Messages must be delivered in order within a channel.
Non-Functional Requirements
- End-to-end message delivery latency under 200 ms (sender to recipient, within a region).
- Strong data isolation between tenants — one organization must never access another's data.
- High availability globally, with regional presence to serve traffic during local business hours.
- The platform must not degrade for small tenants when a large tenant experiences a traffic spike.
What You Are Expected to Cover
- API Design — Core endpoints for sending messages, retrieving history, managing presence, and the WebSocket contract.
- Data Model — Schema for messages, channels, and memberships that handles multi-tenancy and supports efficient history queries.
- Architecture — End-to-end message delivery flow, including real-time push, persistence, and offline notifications.
- Scalability — How you prevent a single large tenant from degrading the experience for everyone else ("noisy neighbor" problem).
Scale Assumptions to Work From
- 10M daily active users; roughly 5M concurrent WebSocket connections at peak.
- Average of 50 messages per user per day (~6,000 messages/sec average, ~30,000/sec peak).
- An average channel message is seen by ~20 online users, making fan-out the dominant bottleneck.
- Messages average ~1 KB; about 500 GB of new message data per day.
- SLA: 99.99% availability; under 200 ms delivery within a region.
Hints
Hint 1
Start by separating the write path (sender → durable log) from the fan-out path (log → recipients' sockets). They have very different scaling characteristics and should not block each other.
Hint 2
Multi-tenancy is not just a schema choice — think about it in layers: routing, storage placement, rate limiting, and resource bulkheads. A single 'shared table with tenant_id' answer misses most of it.
Hint 3
Presence and typing indicators are eventually consistent by nature. Identify early which signals can be shed under load without breaking core messaging guarantees.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Step 1: Nail the Numbers
Before touching architecture, translate requirements into concrete load figures. Interviewers reward this.
- Concurrent connections: 5M WebSocket connections at peak. At ~50k connections per gateway node, that's ~100 gateway nodes minimum.
- Message ingest: 30k messages/sec at peak.
- Fan-out: 30k msg/s × 20 recipients = 600k socket pushes per second. Fan-out dominates; ingest is the easy part.
- Storage: ~500 GB/day of raw message data, ~180 TB/year before replication.
- Tenants: 99% are small teams. Roughly 100 enterprises have 10k–50k users each. Design must serve both without over-engineering for small tenants or under-serving large ones.
Clarify semantics upfront: messages are ordered per channel (not globally), delivery is at-least-once with client-side dedup, and presence can be eventually consistent.
Step 2: API Design
Tenant identity always comes from the auth token — never a query parameter. That is your first isolation boundary.
# Messaging
POST /v1/channels/{channel_id}/messages
body: { client_msg_id, text, thread_parent_seq? }
-> 201 { message_id, seq, created_at } # idempotent on client_msg_id
GET /v1/channels/{channel_id}/messages?after_seq=&before_seq=&limit=50
-> { messages: [...], has_more: bool }
# Presence and read state
PUT /v1/presence body: { status: "active" | "away" }
POST /v1/channels/{channel_id}/read body: { last_read_seq }
# WebSocket
WS /v1/connect
server → client: message.new, message.edited, presence.changed, typing
client → server: heartbeat, subscribe_presence(user_ids[]), resume({ channel_id: last_seq })
The resume call lets a reconnecting client tell the server its last seen sequence per channel. The server can then replay any missed messages through the history endpoint.
Step 3: Data Model and Multi-Tenancy Strategy
Three options, with tradeoffs:
| Approach | Pros | Cons |
|---|---|---|
Shared tables with tenant_id | Simple ops, works for 10k tenants | Weakest isolation; noisy neighbor risk |
| One database per tenant | Strong isolation, per-tenant backups | 10k databases is an operational nightmare |
| Hybrid (tiered) | Small tenants pooled; enterprises get dedicated shards/cells | Requires a routing directory and migration tooling |
The hybrid approach is right here. A tenant directory (tenant_id → { region, cell_id, shard_id, tier }) is cached at every service. Moving a tenant from pooled to dedicated becomes a metadata change plus a background data copy.
Store messages in a wide-column store (Cassandra or ScyllaDB) or sharded relational DB (Vitess):
messages
PRIMARY KEY ((tenant_id, channel_id, bucket), seq DESC)
-- bucket = time window (e.g., weekly) to bound partition size
columns: message_id, sender_id, body, thread_parent_seq, edited_at, deleted
channels (tenant_id, channel_id, name, type, last_seq)
channel_members(tenant_id, channel_id, user_id, role)
user_channels (tenant_id, user_id, channel_id, last_read_seq)
Key decisions:
- Sequence numbers are assigned by the per-channel partition leader in the message service. This makes them strictly monotonic and gapless, so "sync after seq N" is a trivial range scan.
- Unread counts are computed as
channel.last_seq - last_read_seq— no counter columns to maintain. - History reads hit a single Cassandra partition, keeping latency predictable.
Step 4: Architecture (Cell-Based)
Client ─ GeoDNS ─ L4 Load Balancer ─ WebSocket Gateway ──────────────┐
│ │ (push)
Message Service ─ Kafka (keyed by channel_id)
│ ├─ Persister → Message DB
Session Registry (Redis) ├─ Fan-out → Gateways
Presence Store (Redis + TTL) ├─ Notification Svc → APNs/FCM
└─ Search Indexer
A cell is a self-contained regional unit: gateways, services, Kafka cluster, and DB shards. It is the blast-radius boundary. Tenants are assigned to cells; enterprises may get a dedicated cell.
Message send flow:
- Client POSTs to the message service (or sends over WebSocket).
- Service authenticates, checks channel membership, deduplicates on
client_msg_id, assignsseq, and writes to Kafka withchannel_idas the key. This is the durable commit. Never ack to the sender until this write succeeds. - Client receives the ack with
seqin ~20–40 ms. - Downstream consumers run in parallel:
- Persister writes to the message DB.
- Fan-out service looks up online recipients from the session registry (
user_id → gateway_node) and pushes to those gateways. - Notification service handles offline users, mentions, and batching.
- Gateways push to open sockets. Clients dedup by
message_idand detect gaps by checkingseqcontinuity.
Presence:
- Clients heartbeat every 30 seconds. The gateway writes
presence:{user_id}to Redis with a TTL. Expiry means offline; no heartbeat for a shorter window means away. - Presence updates are only pushed to clients that subscribed (e.g., open DMs, visible sidebar). They are coalesced on a 1–2 second window to avoid storms.
Step 5: The Noisy Neighbor Problem
This is typically the follow-up interviewers probe hardest. Address it in layers:
- Placement isolation: Enterprises get dedicated cells or DB shards. Small tenants are bin-packed into pooled cells. Tenants can be live-migrated as they grow.
- Per-tenant rate limiting: Token buckets at the gateway cap messages/sec, API calls/sec, and connection count, tiered by plan. Burst headroom is allowed, but sustained overuse is throttled.
- Bulkheads: Pooled cells use separate Kafka consumer groups and thread pools per tenant tier. A large tenant's fan-out backlog cannot starve a small tenant's delivery.
- Weighted fair queuing: Fan-out and notification workers dequeue by tenant using weighted fair queuing so no single tenant monopolizes a worker.
- Priority shedding under load: When a cell is saturated, shed in this order: typing indicators → presence changes → read receipts → push notifications → and only as a last resort, message delivery.
Common Mistakes to Avoid
- Acking the sender before the Kafka write succeeds. "Async persistence" only works if the log write is synchronous. Memory-only durability means data loss on crash.
- Treating fan-out as a simple broadcast loop. At 600k pushes/second, fan-out must be parallelized, batched, and isolated per tenant.
- One schema strategy for all tenants. Stating "shared table with tenant_id" misses isolation requirements for enterprises. The hybrid tiered model is the defensible answer.
- Ignoring the tenant directory. Without a routing layer that maps tenants to cells/shards, cross-tenant isolation and live migration are impossible to implement cleanly.
- Overcomplicating presence. Presence does not need strong consistency. Redis TTL + coalesced pushes is the right tradeoff. Spending too much design time here signals poor prioritization.