Skip to main content
← PROBLEMS / SYSTEM-DESIGN
An end-to-end domain learning journey

Design a Real-Time Chat, Typing & Presence
System (Slack / Discord / WhatsApp Scale).

Terminate stateful WebSockets at edge Gateway Pods backed by Redis session maps, sequence messages per channel with Snowflake/monotonic IDs into ScyllaDB/Cassandra, and route offline users to APNs/FCM.
Start the journey7 stages· Last modified Nov 22, 2026
FIRST PRINCIPLES. PRODUCTION SCALE.
The idea to keep with you

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.

Before you begin · Building blocksAlready know these? Jump to Stage 01 ↓
Real-Time Presence, Heartbeat Hysteresis & Hybrid Fan-Out
Real-time presence uses periodic WebSocket heartbeats into TTL-backed Redis keys (SETEX 45s) with online/offline hysteresis, paired with hybrid push/pull fan-out for small vs. massive channels.
Consistent Hashing & Virtual Nodes
Consistent hashing assigns data keys to servers in a way that limits how many keys move when servers are added or removed. This helps avoid widespread cache misses and sudden load on databases.
Full walkthrough · 7 stages
01
STAGE 01 · CORE INTUITIONfoundation

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.

STAGE 01 · CORE INTUITION

Scale Envelope & Latency Budget

50M WebSocketsEdge Scale1M Messages / SecThroughput SLAMulti-DeviceCursorsConsistency1:1 DMs -> 100KRoomsFan-Out Scopeorders

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.

02
STAGE 02 · CORE MECHANICSfoundation

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.

STAGE 02 · CORE MECHANICS

Core Architecture & Data Flow

Snowflake / Seq IDOrdering EngineScyllaDB / CassandraDurable HistoryRedis MGET GatewaysRouting LookupPub/Sub or APNs/FCMDual Deliveryroutes via

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.

Engineering Decision Framework
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 key message_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.
Decision Exercise · Make the Call

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?

03
STAGE 03 · SAFE IMPLEMENTATIONintermediate

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']})
STAGE 03 · SAFE IMPLEMENTATION

Gateway Routing & Offline Push Fallback

mget_gateways(uids)Presence ReadZip (uid, gw_id)Route Splitgw_id != NoneLive WebSocketgw_id == NoneAPNs / FCMif online

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.

04
STAGE 04 · SCALING & TRADE-OFFSintermediate

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.

STAGE 04 · SCALING & TRADE-OFFS

Sharding & Hot-Spot Mitigation

Channels <= 500Low-Latency PushChannels > 500Bounded Fan-OutRedis ClusterShardsPresence ScaleLazy Roster SubsZero O(N^2) Stormqueries

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.

05
STAGE 05 · FAULT ISOLATIONadvanced

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.

STAGE 05 · FAULT ISOLATION

Failure Modes & Graceful Degradation

Jittered ReconnectHerd ShieldBounded OutboundRingGateway OOM FixAPNs / FCM BreakerCore ProtectionOffline Push DLQQueue Hygieneisolated from

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.

06
STAGE 06 · RECOVERY & CONSISTENCYadvanced

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.

STAGE 06 · RECOVERY & CONSISTENCY

Consistency, Idempotency & Recovery

Per-Channel seq_idGap DetectorGET ?after_seq=NReconnect Syncmax(last_read_seq)Multi-Deviceclient_msg_id DedupNo Double-Postupdates

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.

07
STAGE 07 · OBSERVABILITY & GUARDRAILSadvanced

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.

STAGE 07 · OBSERVABILITY & GUARDRAILS

Telemetry, Circuit Breakers & Failure Modes

Synthetic EchoProbesLive SLOPub/Sub Queue LagDelivery SignalPresence Flap RateHeartbeat KPIGOAWAY Pod DrainDeploy Guarddiagnoses

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 · Explain the consequences

Practice: Make the trade-off yourself.

Question 1 of 3
Score: 0/3

Why partition ScyllaDB/Cassandra messages by `(channel_id, month_bucket)` instead of just `channel_id`?

Recommended Learning Flow