Overview
2026Distributed Systems & Real-TimeSTAR Case Study

Sportz

I scaled a WebSocket sports engine across multiple Node.js instances with Redis 7 Pub/Sub, zero-duplicate Docker-pause recovery, and stampede-coalesced gap replay.

Sportz v2.0 live commentary, Win Probability, Redis HINCRBY fan reactions, and Gemini 3.8 Flash AI Analyst.

0 / 625k
Undelivered messages
98.649%
Deliveries ≤ 400ms SLA
1 / 1,000
Gap replay DB coalescing
Backend & Systems EngineerMar 2025 to Nov 2026

Node.js 24, Express 5, ws, Redis 7 (Pub/Sub & Hashes), PostgreSQL (Neon), Drizzle ORM, Arcjet, React 19, Vite 6

SSituation

Single-instance WebSockets cannot scale horizontally or survive broker hiccups cleanly

While replacing HTTP polling with native WebSockets solved single-node latency, keeping room state solely in one Node.js Map meant adding a second backend instance split spectators across isolated hubs. Moreover, Redis pauses, dropped mobile connections, and synchronized reconnects could trigger duplicate broadcasts, lost reaction deltas, or database stampedes.

Baseline constraints before the refactor
  • Two backend instances must fan out match commentary, score updates, and reactions to 5,000+ sockets consistently
  • If Redis disconnects or pauses (`docker pause`), local sockets must keep receiving updates without duplicates on unpause
  • 1,000 clients detecting a sequence gap simultaneously cannot fire 1,000 identical PostgreSQL replay queries
  • Third-party Arcjet security blips must never take down live match streaming in production

Single-Node Map & Uncoalesced Replay

Isolated State
Reconnect & OutageStampede
1,000 clients = 1,000 Postgres queries
Single-instance bottleneck

Redis 7 Cluster & Coalesced Replay

0 / 625k Lost
500-Seq Dedupe + Coalescing98.649% ≤ 400ms
1,000 gap requests = 1 Postgres query
0.0ms server event-loop lag

Isolated single-node polling/sockets versus horizontally scaled Redis Pub/Sub with gap replay.

TTask

Architect multi-instance Redis fanout, stampede-safe recovery, and 5k-socket benchmarks

Connect backend nodes over Redis 7 Pub/Sub and atomic reaction hashes, engineer sequence-based deduplication and coalesced Postgres gap replay, harden Arcjet fail-open telemetry, and verify delivery at 5,000 concurrent connections.

2 instances × 2,500 clients

Horizontal Redis 7 Backplane

Await Redis channel subscription before acking subscribed, fan out via sportz:match:id & sportz:global, and sync reactions with atomic HINCRBY.

500-seq FIFO ring + 1-query coalescing

Zero-Duplicate Degraded & Gap Replay

Fall back to local broadcast during Redis outages, dedupe returning Redis frames via recentlyBroadcastSeq, and coalesce concurrent gap-replay DB queries.

TRUST_PROXY + arcjetErrors metric

Fail-Open Perimeter & Live Ingestion

Resolve client IPs from rightmost X-Forwarded-For hop, refuse BENCHMARK_BYPASS_ARCJET in production, and surface Arcjet error counts on GET /health.

AAction · Architecture & Implementation

Two Node instances fan out over Redis 7 with coalesced Postgres replay

Match mutations commit to Neon PostgreSQL and publish to Redis 7 channels. Both WebSocket instances stream pre-serialized frames to 5,000 subscribed sockets while coalescing any client gap replays.

Architecture components
Live & Webhook IngestFilters unchanged score polls & ingests match events.
Sportz v2.0 fixture feed filtering live Football, Cricket, and Basketball matches.

Sportz v2.0 fixture feed filtering live Football, Cricket, and Basketball matches.

Explanatory figures & telemetry

Measured system behavior across benchmarks and fault injections

Figure 1

5-Run Horizontal Scale Benchmark (2 Instances × 5,000 Clients = 625,000 Deliveries)

Run 1 (124,546 / 125k)99.637%

454 in 400–500ms · 0 undelivered

Run 2 (122,579 / 125k)98.063%

2,421 in 400–600ms · 0 undelivered

Run 3 (119,429 / 125k)95.543%

5,571 in 400–800ms (max 639ms) · 0 undelivered

Run 4 (125,000 / 125k)100.000%

0 missed SLA · 0 undelivered

Run 5 (125,000 / 125k)100.000%

0 missed SLA · 0 undelivered

On-time deliveries within the ≤400ms SLA across 5 consecutive benchmark runs (125,000 deliveries/run across 5 match rooms). Zero messages (>2000ms) were lost in any run.vpn-cli/sportz README.md · measure-undelivered-distribution.js
Figure 2

Multi-Instance Redis Pub/Sub, Pause Dedupe & Gap-Replay Coalescing

1. Perimeter
Arcjet HTTP Upgrade

TRUST_PROXY rightmost IP + slidingWindow(30/10s)

Fails open on Arcjet ERROR + logs /health arcjetErrors
2. Backplane
Redis 7 Pub/Sub + HINCRBY

sportz:match:id + sportz:global + awaited subscribe ack

2,500 sockets per instance stay synchronized
3. Pause Shield
recentlyBroadcastSeq (500 FIFO)

Degrades to local broadcast; skips returning Redis seqs

0 duplicates across 2 instances on docker unpause
4. Gap Recovery
inFlightReplayQueries Map

Coalesces concurrent (matchId, lastSeq) queries; >200 → snapshot

1,000 reconnecting clients = 1 Postgres query
Fault path:
Finished match private replay requested → Streams 1x/10x directly to requesting socket with 3s cooldown → Bounded by MAX_CONCURRENT_CLIENT_REPLAYS=5 per instance
How two Sportz backend nodes coordinate broadcasts, survive docker pause without duplicate frames, and coalesce concurrent client gap replays.sportz-websockets-main/src/ws/server.js
Figure 3

625,000-Delivery Latency Buckets & Server Event-Loop Telemetry

Aggregate ≤400ms SLA (616,554 / 625,000)98.649%
≤ 400ms On-Time SLA (p50 ≈ 26ms)

Delivered cleanly within 400ms target across all 5 runs

616,554 msgs(98.65%)
400–600ms Tail Bucket

4,932 (400–500ms) + 2,773 (500–600ms), symmetric across I1/I2

7,705 msgs(1.23%)
600–800ms Tail Bucket (Max 639ms)

0 msgs in 800–2000ms and 0 undelivered (>2000ms)

741 msgs(0.12%)
Server Event-Loop Lag0.0ms

Pre-serialized JSON frames kept libuv lag <0.5ms on both servers.

Instance Tail Split49% / 51%

4,141 (I1) vs 4,305 (I2) late deliveries — single-process client bottleneck.

Reaction Sync SafetyAtomic HINCRBY

Local deltas deleted only after HINCRBY succeeds; broadcasts snapshot.

Distribution of all 625,000 deliveries across the 2.0-second window on a single Ryzen 7 6800H host running 2 server instances, Redis 7, and 5,000 sockets.vpn-cli/sportz README.md · perf_hooks.monitorEventLoopDelay
Action · Trade-offs

Four distributed-systems choices that survived 5,000-client load

Action · Bugs fixed

Four concurrency and security bugs caught in testing

Subscribed ack fired before Redis channel subscription completed

494fd0c
Symptom

Fast clients missed the first commentary event emitted right after subscribing.

Cause

Server sent { type: 'subscribed' } synchronously while activeSub.subscribe() was still in flight.

Fix

Awaited activeSub.subscribe() (with a 200ms race guard) before sending subscribed ack.

Docker unpause delivered duplicate events across 2 instances

7c698d9
Symptom

Clients received events twice after Redis recovered from container pause.

Cause

Degraded local fallback sent events locally, then OS-buffered Redis PUBLISH frames echoed back.

Fix

Disabled offline queue and added 500-seq FIFO recentlyBroadcastSeq deduplication.

Arcjet lacked resolved client IP behind reverse proxy

511ed6d
Symptom

Rate limits bucketed proxy hops instead of client IPs and silent errors hid denials.

Cause

TRUST_PROXY X-Forwarded-For IP wasn't passed via ipSrc to wsArcjet/httpArcjet.

Fix

Extracted rightmost trusted IP into buildProtectOptions({ ipSrc }) and added DEBUG_IP logging.

Test/benchmark scripts risked targeting remote Postgres

af97a52
Symptom

Missing local DB overrides could accidentally hit non-local connection strings.

Cause

Benchmark and Vitest harnesses lacked an explicit localhost hostname guard.

Fix

Added localhost-only DB guard and dedicated CI Postgres 5433 test service.

Horizontal Delivery Reliability
Before:Single Node.js Map isolated to 1 instance
After:0 / 625,000 dropped across 2 instances × 5,000 clients (98.649% ≤400ms)
5-run benchmark (README.md)
Gap-Replay DB Load
Before:N reconnecting clients = N Postgres queries
After:1,000 concurrent gap requests coalesced into 1 Postgres query
inFlightReplayQueries (server.js)
Outage & Security Posture
Before:Redis drop or Arcjet error risked blind spots
After:500-seq FIFO dedupe (0 dups on unpause) + fail-open arcjetErrors
vitest & outage suite
Roadmap

Separate the load generator onto a dedicated host outside the server CPU budget to isolate the client-side 639ms tail and validate multi-node network hops.

First load can take ~30s (Render free tier idle sleep).