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

Design a Nearby Places and Friends

Find places from geohash cells kept in memory, and push friends’ moves through a channel per user over WebSockets.

Follow a request

Clients
Edge
Services
Data
PhoneApp with GPS
Load balancerHTTP
WebSocket serversLive sockets
Search service9 cells, filter
Place serviceDetails, edits
Pub/sub ringChannel per user
Friend graphWho shares
Geo cell cacheCell → place ids
Places DBRows + geo index
Location cacheTTL 10 min
Location historyLog, 30 days
1user → ws · { lat, lng, ts }Ana’s phone sends her point over its open socket, 30 s after the last one.1 / 6

The numbers, at a glance

For every update a phone sends……10 friends’ servers receive it
1 update ≈ 334,000/s10 deliveries ≈ 3.34M/s
Pub/sub nodes neededAt 70% of 200,000 messages a second each
The geo index is tiny6 GB of index against 400 GB of place rows
Small enough to copy into memory on every cache replica, so we never shard it by region.

A friend’s move, in order

Ana and Ben are on different WebSocket servers; the pub/sub node in between owns Ana’s channel.

Ana’s phone
Ana’s WS server
Location cache
Pub/sub node
Ben’s WS server
Ben’s phone
1 { lat, lng, ts }
2 SET loc:ana TTL 600
3 OK
4 PUBLISH user:ana
5 message
6 Ana · 1.2 km
RequestResponseAsync, does not block

How to find what is near a point

The decision this question is really about.

Lat and lng ranges
Too slow
lat BETWEEN …
index on lat only
filter thousands of rows
+ Any SQL database.− Scans a strip of the map, 20 reads a search.
Quadtree
Good, more work
root square
split until ≤ 100 places
rebuild on start-up
+ Adapts to density.− Custom tree to build and sync on every server.
Geohash cells
Our pick
point → "9q8yyk"
9 cellscache hit 95%
filter by true distance
+ Plain strings: a B-tree, cache key or shard key.− Always read 8 neighbours.

How it grows

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

Stage 1 · ≈ 100 searches/sMake it work
Phone
App server
SQL database
One server and lat/lng columns. Fine for a demo.
Stage 2 · ≈ 17,000 searches/sIndex the map
Phone
Load balancer
Search × 9Place service
Geo cell cachePlaces DB
Geohash cells in a cache, 9 search servers, a place service.
Stage 3 · 500K sharersGo live
Phone
Load balancerWebSocket servers
Search × 9Place servicePub/subFriend graph
Geo cell cachePlaces DBLocation cache
WebSockets, a location cache with a TTL and pub/sub channels.
Stage 4 · 10M sharersScale the fan-out
Phone
Load balancerWebSocket × 100
Search × 9Place servicePub/sub ring × 25Friend graph
Geo cell cachePlaces DBLocation cacheLocation history
A pub/sub ring of 25 nodes and a history stream.
Was this walkthrough useful?Your vote tells us what to improve next.