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

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.
Start the journey7 sections· Last modified Nov 22, 2026
FIRST PRINCIPLES. PRODUCTION SCALE.
The idea to keep with you

To keep the architecture evolvable without sacrificing reliability, Heartbeat Hysteresis & Hybrid Fan-Out, never broadcast every user's presence heartbeat globally—use lazy pull/subscription for presence and switch from write-push to read-pull above ~500 channel members.

TL;DR30-second simplified summary
▾

Broadcasting online/offline status changes for 50M concurrent users to every contact on every flaky mobile reconnect triggers a quadratic fan-out storm (O(N * F) events/sec).

Production presence systems decouple Heartbeat Ingestion (clients ping every 30s, refreshing SETEX presence:user_id 45s in Redis) from Lazy Presence Subscriptions (clients only subscribe to visible friends/active DM headers) and apply Offline Hysteresis (wait 45s+ before flipping offline so brief tunnel drops don't flicker).

Before you begin · Building blocksAlready know these? Jump to Stage 01 ↓
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

Core Intuition & Failure Mode.

Why this matters: Decouple heartbeat TTL tracking from lazy presence subscriptions and hybrid push/pull channel fan-out.

Think of Core Intuition & Failure Mode as the intuition layer for Real-Time Presence, Heartbeat Hysteresis & Hybrid Fan-Out: Decouple heartbeat TTL tracking from lazy presence subscriptions and hybrid push/pull channel 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.

STAGE 01 · CORE INTUITION

Core Intuition & Failure Mode

50M WebSocketClientsEdge ConnectionsRedis SETEX 45sPresence StateLazy SubscriptionsBounded Fan-OutHybrid Push / PullChannel Deliveryqueries

1.Global Broadcast Trap: Broadcasting every user's online/offline transition to 50M sockets creates O(N^2) storm traffic.

2.45s TTL + Hysteresis: 30s heartbeats into 45s TTL keys tolerate one dropped mobile packet without flapping offline.

3.Hybrid Fan-Out: Push directly to small groups (<=500); let 100K-member channels pull/page from a shared feed.

45s Redis heartbeat TTLs, lazy roster subscriptions, and hybrid push/pull fan-out avoid O(N^2) presence storms.

02
STAGE 02 · CORE MECHANICSfoundation

Architectural Mechanics.

Why this matters: Route chat messages via gateway-mapped Redis MGET while falling back to offline push notifications.

Think of Architectural Mechanics as the intuition layer for Real-Time Presence, Heartbeat Hysteresis & Hybrid Fan-Out: Route chat messages via gateway-mapped Redis MGET while falling back to offline push notifications.

Production presence systems decouple Heartbeat Ingestion (clients ping every 30s, refreshing SETEX presence:user_id 45s in Redis) from Lazy Presence Subscriptions (clients only subscribe to visible friends/active DM headers) and apply Offline Hysteresis (wait 45s+ before flipping offline so brief tunnel drops don't flicker).

STAGE 02 · CORE MECHANICS

Architectural Mechanics

Incoming MessageOrdered EventRedis MGET GatewaysPresence LookupGateway Pub/SubOnline DeliveryOffline Push QueueOffline Deliveryif online

1.Snowflake Ordering: Time-ordered Snowflake IDs let multi-device clients sort messages deterministically without client clocks.

2.Batched Presence Lookup: One Redis MGET resolves gateway mappings for hundreds of recipients in a single round-trip.

3.Async Persistence: Write messages durably to Cassandra/ScyllaDB alongside live WebSocket fan-out.

Batched Redis gateway lookups route live WebSocket pushes in <100 ms and fall back to APNs/FCM for offline users.

Engineering Decision Framework
Problem
How to implement Real-Time Presence, Heartbeat Hysteresis & Hybrid Fan-Out 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, heartbeat Hysteresis & Hybrid Fan-Out, never broadcast every user's presence heartbeat globally—use lazy pull/subscription for presence and switch from write-push to read-pull above ~500 channel members.
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 Real-Time Presence, Heartbeat Hysteresis & Hybrid Fan-Out experiences a sudden 5x traffic spike alongside a slow downstream dependency, which engineering choice best protects system stability?

03
STAGE 03 · SAFE IMPLEMENTATIONintermediate

Heartbeat TTL & Presence Batch Reader.

Why this matters: Implement heartbeat TTL refresh and batched gateway resolution with strict input validation.

def refresh_presence(redis_client, user_id: str, gateway_id: str, ttl_sec: int = 45) -> None:
    if not user_id or not gateway_id:
        raise ValueError('user_id and gateway_id are required')
    redis_client.set(f'presence:{user_id}', gateway_id, ex=ttl_sec)

def get_visible_presence(redis_client, friend_ids: list[str]) -> dict[str, bool]:
    if not friend_ids:
        return {}
    keys = [f'presence:{uid}' for uid in friend_ids[:200]]  # Cap batch size
    vals = redis_client.mget(keys)
    return {uid: (val is not None) for uid, val in zip(friend_ids[:200], vals)}
STAGE 03 · SAFE IMPLEMENTATION

Heartbeat TTL & Presence Batch Reader

Validate IDsInput GuardSETEX presence:uid45TTL RefreshMGET recipient_idsLookup StepSplit Online /OfflineDelivery Splitread by

1.Non-Empty Guard: Reject missing user_id or gateway_id before touching Redis to prevent orphaned keys.

2.O(1) Refresh: SETEX overwrites both gateway_id and 45s expiry atomically—handling seamless reconnects.

3.Pipeline MGET: Batching recipient lookups avoids N+1 Redis round-trips in group chats.

Atomic SETEX heartbeats and batched MGET lookups cleanly split online WebSocket delivery from offline push queues.

04
STAGE 04 · SCALING & TRADE-OFFSintermediate

Throughput & Latency Trade-Offs.

Why this matters: Scale to 50M concurrent sockets and 1M msg/sec by sharding Redis presence and capping group push size.

Think of Throughput & Latency Trade-Offs as the intuition layer for Real-Time Presence, Heartbeat Hysteresis & Hybrid Fan-Out: Scale to 50M concurrent sockets and 1M msg/sec by sharding Redis presence and capping group push size.

Evaluate asymptotic bounds, cache locality, and tail-latency impact under peak load.

STAGE 04 · SCALING & TRADE-OFFS

Throughput & Latency Trade-Offs

500 WebSocketGatewaysStateful EdgeRedis Cluster ShardsPresence ScalePush Threshold <=500Fan-Out Bound<100 ms p99DeliveryScale Targetbounds

1.Epoll / Kqueue Edge: Each tuned gateway pod holds ~100K idle TLS WebSockets in ~4-6 GB RAM.

2.Fan-Out Threshold: Switching channels >500 members to pull/cursor-sync caps amplification at 500x.

3.Coalesced Typing: Rate-limit and coalesce typing indicators at the gateway to cut wasted Pub/Sub traffic.

500 gateway pods, user-sharded Redis presence, and a 500-member push cap sustain 50M sockets at <100 ms p99.

05
STAGE 05 · FAULT ISOLATIONadvanced

Blast-Radius & Failure Isolation.

Why this matters: Prevent reconnect thundering herds and gateway crashes using jittered backoff and bounded outbound queues.

Think of Blast-Radius & Failure Isolation as the intuition layer for Real-Time Presence, Heartbeat Hysteresis & Hybrid Fan-Out: Prevent reconnect thundering herds and gateway crashes using jittered backoff and bounded outbound queues.

Isolate shared resources, apply bounded queues, and prevent retry amplification.

STAGE 05 · FAULT ISOLATION

Blast-Radius & Failure Isolation

Gateway Pod CrashFailure EventJittered ReconnectHerd ShieldBounded Send BufferMemory ShieldIsolated Push DLQCore Protectionprotects

1.Reconnect Jitter: Without exponential backoff + jitter, a gateway restart triggers 100K simultaneous TLS handshakes.

2.Slow-Consumer Shed: Disconnect WebSockets whose outbound ring buffer fills instead of letting them OOM the gateway.

3.Separate Push Workers: Slow APNs/FCM endpoints never block live WebSocket Pub/Sub threads.

Jittered client reconnects, bounded per-socket send buffers, and isolated push queues contain gateway failures.

06
STAGE 06 · RECOVERY & CONSISTENCYadvanced

Durability, Consistency & Recovery.

Why this matters: Guarantee at-least-once delivery and multi-device read-cursor sync using sequence IDs and client ACKs.

Think of Durability, Consistency & Recovery as the intuition layer for Real-Time Presence, Heartbeat Hysteresis & Hybrid Fan-Out: Guarantee at-least-once delivery and multi-device read-cursor sync using sequence IDs and client ACKs.

Use idempotent state transitions, atomic commits, and deterministic replay.

STAGE 06 · RECOVERY & CONSISTENCY

Durability, Consistency & Recovery

Channel seq_idOrdering KeyClient Catch-UpGap RecoveryRead-Cursor LWWMulti-Device SyncIdempotent msg_idExactly-Once UXsyncs cursor

1.Gap Sync on Reconnect: Clients pass last_seen_seq on WebSocket resume to fetch any missed messages during brief drops.

2.Monotonic Read Cursor: Store max(read_seq) per (user, channel) so an old mobile device never rewinds desktop read state.

3.Client-Generated UUID: Deduplicate retries by client_msg_id so poor cellular connections never double-post.

Per-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 gateway connection churn, Redis MGET latency, Pub/Sub lag, and presence flapping rates.

Think of Telemetry, Circuit Breakers & Failure Modes as the intuition layer for Real-Time Presence, Heartbeat Hysteresis & Hybrid Fan-Out: Monitor gateway connection churn, Redis MGET latency, Pub/Sub lag, and presence flapping rates.

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

Gateway Conn ChurnStability SignalDelivery Latency p99SLO MetricPresence Flap RateHeartbeat SignalSlow-Client DropsGuardraildiagnoses

1.Flapping Alert: A spike in offline transitions followed within 5s by online indicates heartbeat_interval is too close to TTL.

2.End-to-End Canary: Ping synthetic echo bots across regions every 5s to measure real WebSocket delivery p99.

3.Graceful Drain: Send WebSocket GOAWAY + jittered reconnect window before terminating pods during deploys.

Tracking connection churn, presence flap rates, and synthetic echo latency catches WebSocket bottlenecks early.

Practice · Explain the consequences

Practice: Make the trade-off yourself.

Question 1 of 3
Score: 0/3

Why do presence systems use a 45-second TTL with 30-second heartbeats?

Recommended Learning Flow