To keep the architecture evolvable without sacrificing reliability, Typing & Presence System (Slack /, partition message tables by `(channel_id, bucket_month)` with clustering key `message_id` (Snowflake) to keep history scans O(1) seek and prevent unbounded partition growth.
TL;DR30-second simplified summary▾
At 50M concurrent WebSocket connections (~1,000 Gateway Pods holding 50K connections each), statefulness lives strictly at the edge gateway layer while all routing and persistence remain horizontally scalable.
Each incoming message receives a time-ordered Snowflake ID (or per-channel sequence ID) so clients sort messages deterministically across devices without relying on client clocks. Messages persist asynchronously to ScyllaDB / Cassandra partitioned by (channel_id, time_bucket) to bound partition sizes.
SETEX 45s) with online/offline hysteresis, paired with hybrid push/pull fan-out for small vs. massive channels.Scale Envelope & Latency Budget.
Why this matters: Size a 50M-connection, 1M-msg/sec real-time chat system with <100 ms p99 delivery and 100K-member channel support.
Think of Scale Envelope & Latency Budget as the intuition layer for Design a Real-Time Chat, Typing & Presence System (Slack / Discord / WhatsApp Scale): Size a 50M-connection, 1M-msg/sec real-time chat system with <100 ms p99 delivery and 100K-member channel support.
Design a real-time chat and presence platform supporting 50M concurrent WebSocket connections, 1M messages/sec, < 100 ms p99 message delivery, multi-device read-cursor sync, and both 1:1 DMs and 100K-member channels.
Scale Envelope & Latency Budget
1.Connection Density: 500 tuned epoll/kqueue gateway pods each hold ~100K concurrent TLS WebSockets.
2.Latency Target: End-to-end ingest -> Redis lookup -> Pub/Sub -> recipient socket under 100 ms p99.
3.Scale Range: Same platform must handle 2-person DMs and 100K-member broadcast channels without O(N^2) meltdowns.
500 WebSocket gateways, Snowflake ordering, and hybrid push/pull fan-out target 50M sockets and 1M msg/sec at <100 ms.
Core Architecture & Data Flow.
Why this matters: Assign Snowflake IDs, persist to ScyllaDB/Cassandra, resolve online gateways via Redis MGET, and push or notify.
Think of Core Architecture & Data Flow as the intuition layer for Design a Real-Time Chat, Typing & Presence System (Slack / Discord / WhatsApp Scale): Assign Snowflake IDs, persist to ScyllaDB/Cassandra, resolve online gateways via Redis MGET, and push or notify.
Each incoming message receives a time-ordered Snowflake ID (or per-channel sequence ID) so clients sort messages deterministically across devices without relying on client clocks. Messages persist asynchronously to ScyllaDB / Cassandra partitioned by (channel_id, time_bucket) to bound partition sizes.
Core Architecture & Data Flow
1.Time-Bucketed Partitions: Partition chat history by (channel_id, month_bucket) to prevent unbounded wide-row growth.
2.Parallel Persist + Push: Persist to ScyllaDB and fan out to online WebSocket gateways concurrently for <100 ms p99.
3.Batched Presence: One Redis MGET resolves gateway IDs for all recipients in small/medium groups.
Snowflake IDs, time-bucketed ScyllaDB storage, and batched Redis gateway lookups power <100 ms message delivery.
- Problem
- How to implement Design a Real-Time Chat, Typing & Presence System (Slack / Discord / WhatsApp Scale) without hitting unbounded tail latency, state divergence, or operational fragility.
- Naive Solution
- Use a single unpartitioned path with unbounded retries and synchronous global coordination.
- Why It Fails
- Global coordination serializes throughput under load, while unbounded retries amplify transient stalls into full outages.
- Alternatives
- Compare synchronous strict-consistency paths against bounded asynchronous replication, local caching, or partitioned ownership.
- Engineering Decision
- To keep the architecture evolvable without sacrificing reliability, typing & Presence System (Slack /, partition message tables by
(channel_id, bucket_month)with clustering keymessage_id(Snowflake) to keep history scans O(1) seek and prevent unbounded partition growth. - Trade-Offs
- Gains predictable p99 latency and fault isolation in exchange for explicit bounding, observability, and slightly higher implementation complexity.
When Design a Real-Time Chat, Typing & Presence System (Slack / Discord / WhatsApp Scale) experiences a sudden 5x traffic spike alongside a slow downstream dependency, which engineering choice best protects system stability?
Gateway Routing & Offline Push Fallback.
Why this matters: Implement route_chat_message to batch-resolve recipient gateways and split delivery between Pub/Sub and push queues.
Think of Gateway Routing & Offline Push Fallback as the intuition layer for Design a Real-Time Chat, Typing & Presence System (Slack / Discord / WhatsApp Scale): Implement route_chat_message to batch-resolve recipient gateways and split delivery between Pub/Sub and push queues.
def route_chat_message(presence_store, pubsub, push_queue, recipient_ids: list[str], msg: dict) -> None:
gateways = presence_store.mget_gateways(recipient_ids)
for uid, gw_id in zip(recipient_ids, gateways):
if gw_id:
pubsub.publish(f'gw:{gw_id}', {'user_id': uid, 'msg': msg})
else:
push_queue.enqueue({'user_id': uid, 'channel_id': msg['channel_id'], 'preview': msg['snippet']})Gateway Routing & Offline Push Fallback
1.Zero N+1 Lookups: Batching recipient IDs into one MGET keeps gateway routing O(1) round-trips.
2.Multi-Device Support: Map user_id -> set of (device_id, gateway_id) so desktop and mobile both receive live pushes.
3.Offline Push Decoupling: Enqueue offline notifications asynchronously so slow APNs/FCM calls never block live chat.
Batch MGET resolution splits recipients cleanly between live gateway Pub/Sub and async offline push queues.
Sharding & Hot-Spot Mitigation.
Why this matters: Switch channels >500 members from push fan-out to cursor-based pull and shard Redis presence by user_id.
Think of Sharding & Hot-Spot Mitigation as the intuition layer for Design a Real-Time Chat, Typing & Presence System (Slack / Discord / WhatsApp Scale): Switch channels >500 members from push fan-out to cursor-based pull and shard Redis presence by user_id.
Partition state deterministically and apply bounded-load or sub-bucket sharding for hot keys.
Sharding & Hot-Spot Mitigation
1.Fan-Out Cap: In a 100K-member channel, pushing 1 message/sec would emit 100K writes/sec; pull caps amplification.
2.Active-View Pull: Only users currently viewing the massive channel poll or subscribe to its lightweight delta stream.
3.Lazy Presence: Clients subscribe to presence only for visible DM/sidebar contacts, avoiding global broadcasts.
Capping push fan-out at 500 members and using lazy presence subscriptions prevents 100K-member storms.
Failure Modes & Graceful Degradation.
Why this matters: Contain gateway crashes and slow mobile clients using jittered reconnects, bounded socket buffers, and push DLQs.
Think of Failure Modes & Graceful Degradation as the intuition layer for Design a Real-Time Chat, Typing & Presence System (Slack / Discord / WhatsApp Scale): Contain gateway crashes and slow mobile clients using jittered reconnects, bounded socket buffers, and push DLQs.
Apply circuit breakers, fallback caches, and dead-letter quarantine queues.
Failure Modes & Graceful Degradation
1.Full-Jitter Backoff: Spreading reconnects over 0..30s prevents TLS handshake storms after a gateway node restarts.
2.Slow-Consumer Isolation: Close sockets whose outbound send buffer fills; they recover missed messages via gap sync on reconnect.
3.Presence Hysteresis: 45s Redis TTL with 30s heartbeats absorbs transient 3G/4G packet loss without flapping offline.
Jittered reconnects, bounded socket send rings, and 45s heartbeat hysteresis contain mobile network churn.
Consistency, Idempotency & Recovery.
Why this matters: Guarantee gap-free message history and multi-device read-cursor consistency across reconnects.
Think of Consistency, Idempotency & Recovery as the intuition layer for Design a Real-Time Chat, Typing & Presence System (Slack / Discord / WhatsApp Scale): Guarantee gap-free message history and multi-device read-cursor consistency across reconnects.
Enforce atomic state transitions, fencing/idempotency keys, and fast snapshot recovery.
Consistency, Idempotency & Recovery
1.Seamless Gap Recovery: On WebSocket reconnect, clients send last_seq per active channel to pull missed messages.
2.Monotonic Read State: Using max(existing, new) prevents a stale offline tablet from resetting unread badges.
3.Idempotent Send: Deduplicating by client_msg_id ensures flaky subway retries never post duplicate messages.
Channel sequence IDs, reconnect gap-sync, and monotonic read cursors keep multi-device chat consistent.
Telemetry, Circuit Breakers & Failure Modes.
Why this matters: Monitor synthetic WebSocket echo latency, Pub/Sub lag, presence flap rates, and gateway connection churn.
Think of Telemetry, Circuit Breakers & Failure Modes as the intuition layer for Design a Real-Time Chat, Typing & Presence System (Slack / Discord / WhatsApp Scale): Monitor synthetic WebSocket echo latency, Pub/Sub lag, presence flap rates, and gateway connection churn.
Track p99 latency, retry/conflict ratios, and saturation metrics; fail fast with bounded retries and circuit breakers whenever invariants degrade.
Telemetry, Circuit Breakers & Failure Modes
1.Echo Canary: Cross-region canary bots exchange messages every 5s to measure real socket-to-socket p99.
2.Graceful Rolling Drain: Send WebSocket GOAWAY frames in waves during deploys so 50M connections migrate smoothly.
3.Flap-Rate Alert: Alert if offline->online transitions within 5s spike, indicating heartbeat or Redis TTL issues.
Synthetic echo canaries, Pub/Sub lag alerts, and waved GOAWAY drains protect 50M-socket reliability.
Practice: Make the trade-off yourself.
Why partition ScyllaDB/Cassandra messages by `(channel_id, month_bucket)` instead of just `channel_id`?