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
Open a page
Push the new number
A viewer vanishes
A gateway dies
Counts on a search page
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
The numbers, at a glance
≈ 220,000 central writes/s10M viewers on gateways
1MPolling
570KHeartbeats
220KGateway counts
12% through pub/sub88% fanned out at gateways
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.
open → INCRclose → DECR
laptop shut: no DECR
count climbs forever
+ One write per join and leave.− Silent leaves are never subtracted.
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.
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.
Viewer
App server
Counter store
Viewer
Load balancer
App × N
Presence store
Viewer
Load balancer
GatewaysCount API
AggregatorPub/sub
Sharded count store
Viewer
CDNLoad balancer
GatewaysCount API
AggregatorPub/subOther regions
Sharded count store
Was this walkthrough useful?Your vote tells us what to improve next.