Design Nearby Friends: Real-Time Pub/Sub Location Streaming at Scale
Why Yelp Architecture Fails for Moving Friends
- 10M active users pinging GPS every 30 seconds = ~334,000 location updates/sec.
- Assuming each user has ~400 friends and ~10% are active concurrently = $334\text{K} \times 40 = 13.4\text{ million location push notifications/sec}$!
Nearby Friends Real-Time PubSub Architecture
1. Architecture Components & Data Flow
- WebSocket Gateway Cluster:
- Mobile clients maintain stateful WebSocket connections to regional WS servers.
- HTTP REST servers still handle login, friend graph management, and privacy toggles.
- User Location Cache (Redis):
- Stores only the latest coordinates:
user:42 -> { lat, lon, timestamp }with a 10-minute TTL (no need to keep stale offline positions in RAM).
- Stores only the latest coordinates:
- Location History DB (Cassandra):
- Optional append-only store (
(user_id, ts) -> lat, lon) for trip timelines or ML ETA analytics; completely decoupled from the real-time hot path.
- Optional append-only store (
- Redis Pub/Sub Cluster:
- One dedicated Pub/Sub channel per active user (
channel:user:42). - When Bob opens the app, his WebSocket handler subscribes to the Redis channels of all his friends who allow location sharing.
- One dedicated Pub/Sub channel per active user (
2. Tracing a Real-Time Location Ping
- WebSocket server receives
{ lat, lon, ts }. - Persist asynchronously to Location History DB and overwrite Alice's key in Redis Location Cache (
TTL = 600s). - Publish Alice's new
{ lat, lon }to Redis Pub/Sub channelchannel:user:alice. - All WebSocket servers subscribed to
channel:user:alice(hosting Alice's active friends) receive the event. - Each WebSocket server computes the distance between Alice and the subscribed friend: if
< 5 miles, push update to the friend's phone; otherwise drop silently!
3. Scaling Redis Pub/Sub to 14 Million Messages/Sec
- Memory footprint per channel is minimal (~20 bytes per hash pointer; 100M channels $\approx 2\text{ GB}$).
- Consistent Hashing Sharding: Shard Redis Pub/Sub servers using a Consistent Hashing Ring keyed by
publisher_user_id(hash(alice_id) -> pubsub_node_7). - Because Pub/Sub traffic scales linearly with cluster nodes and carries zero disk persistence, adding nodes scales horizontally with predictable latency.
Handling Edge Cases
- Friend Add/Remove Mid-Session: Emit lightweight control events to dynamically
SUBSCRIBEorUNSUBSCRIBEon the user's WebSocket handler. - Users with Thousands of Friends: Cap push frequency or group random nearby alerts (
max 1 update per friend per 30s) to preserve mobile battery and cellular bandwidth.