Skip to content
SD-49 · Back to the write-up

Design a Live Page Viewer Count

Gateways count their own viewers, an aggregator adds up the gateways for each page, and the gateways push the new number to their viewers.

Follow a request

Clients
Edge
Live tier
Counting
ViewerBrowser tab
CDN5 s copies
Load balancerPins sockets
GatewaysLocal counts
Count APIBatch reads
Pub/subChannel per page
AggregatorSharded by page
Count store8 shards, in memory
1agg → store · HSET pc:42 gw17The aggregator records gateway 17’s count with the arrival time, its lease.1 / 5

The numbers, at a glance

For every 100 viewers……one viewer’s change reaches the central store
≈ 220,000 central writes/s10M viewers on gateways
Central writes a secondAt 10 million viewers, by design
Pushes that go central1.5M pushes/s, 180,000 central messages
So the expensive part of fan-out happens next to the viewers.

A join, in order

The viewer sees a number at once from the store; the corrected total follows on the next 2 s tick.

Viewer
Load balancer
Gateway
Count store
Aggregator
Pub/sub
1 wss /live + token
2 pin socket
3 { watch: 42 }
4 GET pt:42
5 1,283
6 1,283 viewing
7 batch: 42 → 6,513
8 HSET pc:42 gw17
9 page:42 = 1,284
10 1,284
11 push 1,284
RequestResponseAsync, does not block

Where the counting happens

The decision this question is really about.

Counter per page
Drifts
open → INCRclose → DECR
laptop shut: no DECR
count climbs forever
+ One write per join and leave.− Silent leaves are never subtracted.
Heartbeat per viewer
Correct, heavy
heartbeat every 20 s
ZADD page:42 viewer
500K writes/s, 50K on one key
+ Silent viewers expire.− One write per viewer every 20 s; hot key.
Count at the gateway
Our pick
socket open = viewing
gateway: page 42 → 6,512
sum of 154 fieldsfan out at gateways
+ The socket is the heartbeat; one number per gateway.− Needs leases for dead gateways.

How it grows

Add a box only when a number forces you to. Highlighted boxes are new at each stage.

Stage 1 · ≈ 10,000 viewersMake it work
Viewer
App server
Counter store
A counter per page, plus polling. Fine until people leave silently.
Stage 2 · ≈ 500,000 viewersExpire silent viewers
Viewer
Load balancer
App × N
Presence store
Heartbeats every 20 s into a sorted set per page; old entries drop out.
Stage 3 · ≈ 10M viewersCount at the gateway
Viewer
Load balancer
GatewaysCount API
AggregatorPub/sub
Sharded count store
Live sockets, local counts sent every 2 s, sums by page, fan-out at gateways.
Stage 4 · ≈ 30M viewersGo global
Viewer
CDNLoad balancer
GatewaysCount API
AggregatorPub/subOther regions
Sharded count store
4 regions swap page totals; a CDN caches listing reads for 5 s.
Was this walkthrough useful?Your vote tells us what to improve next.