Build a Real-Time Team Chat System Architecture
System DesignModel answerLast updated
Architect a scalable backend for workplace messaging with channels, direct messaging, history retrieval, and live delivery guarantees.
Problem
You need to architect the backend infrastructure for a workplace communication tool that enables teams to exchange messages instantly. Your system must support organized group discussions, private conversations between individuals, and the ability to review past exchanges.
Core Capabilities
Your design should provide:
- Communication modes: Support both group discussion spaces (with public and restricted access) and private person-to-person messaging
- Historical access: Allow users to retrieve and browse through previous messages with pagination support
- Delivery guarantees: Ensure messages appear in the correct sequence and prevent duplicate displays
- User awareness: Track whether participants are currently active and show which messages haven't been viewed yet
Performance Targets
- Response time: Messages should reach active recipients within 200 milliseconds
- Reliability: The messaging infrastructure should maintain 99.99% uptime, with no message loss even during temporary outages
- Persistence: Successfully acknowledged messages must be durably stored
Expected Load
- User base: 10 million people use the system daily
- Message volume: Up to 50,000 messages traverse the system each second during busy periods
- Group sizes: Typical users participate in 50 discussion groups; popular public groups may contain 100,000 members
- Retention: Message archives must remain accessible for 5 years minimum
Deliverables
Your architecture should address:
- Interface contracts: Specify the primary endpoints for posting messages, retrieving conversation logs, and maintaining live connections
- Storage strategy: Select appropriate database technologies and define schemas for messages and group memberships, including partitioning approaches
- Live distribution: Explain how you'll manage persistent connections and route messages to recipients, especially in large groups
- Consistency mechanisms: Detail how you'll assign ordering to messages and prevent duplicates across the system
Hints
Hint 1
Consider separating durable message storage from ephemeral real-time delivery—they have different requirements and failure modes
Hint 2
For large groups, avoid writing copies per recipient; instead broadcast to connection servers and let them handle local fan-out
Hint 3
Use conversation-specific sequence numbers rather than global timestamps for ordering, and make them gap-detectable so clients can request missing messages
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer: Team Chat System Architecture
1. Scope Definition and Capacity Planning
First, I'll clarify what's included: group spaces, direct messaging, message history, ordering guarantees, presence indicators, and unread tracking. I'm excluding full-text search, threaded replies, and third-party integrations for this design.
Capacity estimates:
-
Concurrent connections: With 10M daily users and roughly 50% online during peak hours, we're looking at ~5M simultaneous WebSocket connections. Assuming each gateway server handles 50K connections, we need approximately 100 gateway instances plus redundancy.
-
Write throughput: 50K messages/second at peak, averaging around 15K/s, translates to roughly 1.3 billion messages daily.
-
Storage requirements: Each message with metadata consumes approximately 1KB, yielding 1.3TB daily or about 2.4PB over five years. With triple replication, we're planning for ~7PB total. This scale necessitates horizontally partitionable storage with the ability to tier older data to cold storage.
-
Fan-out challenge: A 100K-member group with 20% online means one message becomes 20K socket writes. Rather than sending 20K individual backend messages, we'll optimize by sending ~200 messages (one per gateway server), letting each gateway handle local distribution.
2. API Design
REST endpoints:
POST /v1/channels/{channel_id}/messages
Request: { idempotency_key: uuid, content: string }
Response: 202 { idempotency_key, status: "committed" }
GET /v1/channels/{channel_id}/messages?before_sequence=N&limit=50
Response: { messages: [...], continuation_token }
POST /v1/channels/{channel_id}/mark_read
Request: { sequence_number: N }
GET /v1/sync?checkpoints={channel_id: last_seq, ...}
Response: { updates_by_channel }
WebSocket interface:
/v1/stream
Server → Client:
- event.message {channel_id, sequence, message_id, idempotency_key, ...}
- event.unread_update
- event.presence_change
Client → Server:
- keepalive
- channel.focus {channel_id}
Messages can be sent via HTTP or WebSocket with identical semantics. The idempotency_key enables client retries without creating duplicates. Pagination relies on per-channel sequence numbers rather than offsets to handle concurrent writes cleanly.
3. Data Architecture
Message storage (Cassandra/ScyllaDB):
- Partition key:
(channel_id, bucket)wherebucket = sequence / 10000to bound partition size - Clustering key:
sequence DESCfor efficient reverse-chronological queries - This structure supports high write throughput and range scans
Deduplication cache (same store, 24-hour TTL):
- Key:
(channel_id, idempotency_key) → sequence - Prevents duplicate message creation on retries
Channel metadata (sharded PostgreSQL):
- Tables for channels and their properties
- Shard by
organization_idto co-locate related data
Membership (sharded PostgreSQL):
- Two indices:
members_by_channel(shard by channel_id) for access control and fan-out lookups, andchannels_by_user(shard by user_id) for sidebar rendering - Enables efficient bidirectional queries
Read positions (Cassandra + Redis cache):
(user_id, channel_id) → last_read_sequence- Unread counts computed as
channel.latest_sequence - user.last_read_sequence
Presence tracking (Redis with TTL):
user_id → {status, gateway_instance}- Expires automatically on connection loss
I chose wide-column storage for messages because they're append-only, need high write throughput, and are queried by key ranges. Relational databases handle membership and metadata because they require transactions (atomic join/leave operations) and are modest in size.
4. System Architecture
Clients ←→ Gateway Cluster (stateful WebSocket servers)
↓
Message API → Kafka "inbound" (partitioned by channel_id)
↓
Sequencer Workers (per-partition consumers)
- Deduplication check
- Sequence assignment
- Write to Cassandra
↓
Kafka "outbound" → Fan-out Service
↓
Gateway Routing
↓
Client Sockets
This architecture separates durable acceptance (Kafka + Cassandra) from ephemeral delivery (gateways and real-time push). If a push fails, nothing is lost—clients detect sequence gaps and request missing messages through the sync API.
5. Ordering and Deduplication Strategy
Durable acknowledgment: The API validates membership, writes to Kafka with acks=all and min.insync.replicas=2, partitioned by channel_id. Only after Kafka commits do we return 202, guaranteeing no acknowledged message is lost.
Single-threaded sequencing: Each channel's messages land in one Kafka partition consumed by exactly one sequencer worker. This worker maintains an in-memory counter per channel and assigns monotonically increasing sequence numbers without distributed coordination.
Sequence assignment: For each message, the sequencer increments last_sequence, writes to Cassandra, then advances its Kafka offset. On worker restart or partition rebalance, the new owner rebuilds counters by querying the maximum sequence from Cassandra.
Multi-layer deduplication:
-
Server-side: Before assigning a sequence, check the
(channel_id, idempotency_key)table. If found, republish the existing message rather than creating a new one. This handles client retries and consumer replays. -
Client-side: Clients track seen
idempotency_keyvalues and the highest sequence per channel, dropping duplicates. They render their own messages optimistically while waiting for the authoritative echo containing the server-assigned sequence.
Gap recovery: When a client sees sequence 105 after 103, it requests sequence 104 through the history or sync endpoints. Display order always follows sequence numbers, never arrival timestamps.
6. Connection Management and Distribution
Gateway layer: Gateways are stateful WebSocket servers behind TCP load balancers. On connection, they authenticate the user, load their channel list from channels_by_user, and register themselves in a routing registry: channel_id → set(gateway_instances) stored in Redis.
Efficient fan-out: The fan-out service consumes outbound events and sends one message per gateway instance that has members of that channel. Each gateway then distributes to its local connections in parallel.
Cost analysis:
- Direct messages: 2 members across perhaps 2 gateways = 2 backend sends
- 100K-member channel: ~200 sends regardless of member count (limited by gateway instances, not member count)
This approach scales horizontally because write cost is proportional to active gateways, not total membership. Offline members contribute zero cost at write time—they fetch history on reconnection.
Presence distribution: Heartbeats every 30 seconds refresh Redis keys with 60-second TTL. Status changes propagate only to users in small shared channels or currently viewing the profile. Large channels don't receive individual presence updates, avoiding broadcast storms.
7. Failure Handling
Kafka consumer lag: If sequencers fall behind, messages still arrive, just with higher latency. Horizontal scaling of consumer group members resolves throughput issues.
Gateway failures: Clients automatically reconnect to a different gateway. The sync endpoint with per-channel checkpoints ensures they catch up on missed messages.
Database unavailability: Read replicas handle history queries. Cassandra's tunable consistency (QUORUM for writes, ONE for reads) provides availability during node failures.
Network partitions: The idempotency layer prevents split-brain scenarios from creating duplicate messages when retries span a partition.
Common Pitfalls
- Per-user inbox anti-pattern: Writing a copy per recipient in large channels creates unacceptable write amplification
- Timestamp-based ordering: Wall-clock times across servers can't guarantee ordering; use explicitly assigned sequences
- Synchronous fan-out: Blocking the write path until all recipients receive the message kills throughput and availability
- Missing gap detection: Without sequence numbers, clients can't tell when they've missed messages
- Global message counters: A single counter across all channels becomes a bottleneck; partition by channel