How to design nearby friends
The first sections are free. The deep dives, level expectations and quiz are part of Pro.
On this page
- The problem
- Clarifying questions
- The requirements menu
- Non-functional requirements
- Estimates
- Core entities
- The API
- The high-level design
- What breaks first
- The deep dives
- Entity fields
- One location update, end to end
- Scaling pub/sub
- Connections and friend changes
- Variants
- What each level is expected to show
- The 30-second answer
- Quiz
The problem
Nearby friends shows people who opted in which of their friends are within a few miles, and the list changes as everyone moves. Each phone reports where it is over a long-lived connection, and the server has to get that report to the friends who are online, wherever their connections happen to live. The answer turns on the fan-out: about 334,000 reports a second become about 14 million deliveries a second, because each one goes to about 40 online friends. The tier that carries those deliveries is what you size, and since a fresh report replaces a lost one half a minute later, you can carry them with a light, lossy messaging layer instead of a durable one.
Clarifying questions
| Ask | Why it matters | A typical answer |
|---|---|---|
How many people are online at once, and how often does a phone report its position? | Together these two figures give the write rate for the whole system, and the report interval also sets how stale a friend's dot may be before anyone notices. | About 10 million online at once, each reporting every 30 seconds, so about 334,000 location updates a second. |
How many friends does a person have, and how many of them are online at the same time? | The number of online friends is the fan-out factor: each report is copied once per online friend, and that product is the biggest number on the board. | About 400 friends on average, with about 10% online, so about 40 online friends per update. Friends are capped at 5,000, the limit Facebook uses. |
What radius counts as nearby, and how fresh does the list have to be? | The radius decides where the distance check can run, and the freshness target decides whether an open connection is needed or occasional polling would do. | Within 5 miles by default, configurable per person, with the distance and the time of the last update shown. The list should refresh every few seconds, and a friend who has sent nothing for 10 minutes drops off. |
Is it acceptable to lose an update now and then? | If a dropped update is fine, the messaging layer can be fast and lossy; if each one must arrive, you need a durable log and acknowledgments, which costs far more at this rate. | Yes. The next report arrives 30 seconds later and replaces it. Replicas may lag a few seconds, and the service should stay up through server failures. |
Do we need to keep where people have been, or just where they are now? | Keeping history turns the write path into a heavy append stream that needs its own store, separate from the live cache. | Keep location history for analytics. Nothing in the live feature reads it. |
Friends only, or anyone nearby who opted in? | Friends share a social graph, so the delivery path can follow friendships. Strangers share nothing but geography, which calls for a different way of grouping updates. | Friends only for this round. Be ready for the stranger version as a follow-up. |
Is a list with straight-line distance enough, or do we need a map and road distance? | A map and road distances pull in a routing service and a tile pipeline, neither of which belongs in a round about fan-out. | A list with straight-line distance is enough. Maps, road distance and privacy law are out of scope. |
Non-functional requirements
| Requirement | What it forces |
|---|---|
About 334,000 location updates a second | Each update is written to a cache and to a history store, so both must take that rate without a round trip to a relational database. The socket tier has to hold 10 million open connections across many servers, so no single shared server may sit in the path of all updates. |
Low latency from a friend’s move to my screen | The server pushes to the phone instead of waiting to be asked, and the hop between the sender's server and the friend's server goes through memory, not a disk-backed queue. The distance check runs on a server that already holds both positions, so no lookup is added on the way. |
An occasional lost update is fine | This is what allows a fire-and-forget messaging layer between servers, with no acknowledgments, retries or replay. It also allows resizing that layer while updates are flowing, as long as the loss is brief. |
Eventual consistency: replicas may lag a few seconds | The cache and the user database can be replicated asynchronously, and a friend's dot being a few seconds behind is accepted. Nothing in the design needs a transaction across stores. |
Highly available | Socket servers are replaceable and drained before removal, the messaging layer is spread over many servers so losing one affects a slice of channels, and in this design the cache and user database get replicas, accepting the lag the consistency line allows. A phone that loses its connection reconnects and rebuilds its list from the cache. |
Estimates
| Quantity | Working | Result | What it sizes |
|---|---|---|---|
Location updates a second | 10 million online users ÷ 30 seconds between reports ≈ 333,333 | About 334,000 updates a second | The write rate on the socket tier, the cache and the history store. |
Online friends per update | 400 friends × 10% online = 40 | About 40 deliveries per update | The fan-out factor: how many copies of each update leave the messaging layer. |
Deliveries to friends a second | 334,000 updates a second × 40 online friends ≈ 13.4 million | About 14 million deliveries a second | The load on the pub/sub tier, and the biggest number in the design. |
Pub/sub servers by CPU | 14 million deliveries a second ÷ about 100,000 a server = 140 | At least 140 pub/sub servers | The size of the pub/sub cluster, which is decided by CPU. |
Pub/sub servers by memory | Alex Xu's notes put the channel bookkeeping for 100 million users of the feature at about 200 GB; 200 GB ÷ 100 GB a server = 2 | Two servers would hold the channels | Why memory is the wrong thing to size by: it suggests two servers when CPU needs 140. |
Channel subscriptions across the socket tier | 10 million online users × 400 friends = 4 billion | About 4 billion subscriptions held at once | The subscription bookkeeping on socket servers, and how large the wave of resubscribes is when channels move. |
Cost of a user at the friend cap | 5,000 friends × 10% online = 500 online friends; 500 ÷ 40 = 12.5 times the average fan-out | 500 deliveries per update and 5,000 subscriptions on connect | What one heavy user costs the socket server that holds them and the pub/sub tier. |
History rows a day | 334,000 updates a second × 86,400 seconds a day ≈ 29 billion | About 29 billion rows appended a day | Why history goes to a store built for appends, partitioned by user, and not to the cache or the user database. |
Core entities
| Entity | What it holds |
|---|---|
Location cache entry | The latest known position of one person, kept in memory and expiring on its own when no new report arrives. |
Location history row | One row per report, appended for analytics and read by nothing in the live path. |
Friendship | One row per direction of a friendship, so a person's friends are one lookup by their id. |
User settings | Whether a person shares their location and how far nearby reaches. |
Pub/sub channel | A named stream per person that carries their location reports to whichever servers hold their online friends. |
The API
| Endpoint | Notes |
|---|---|
| The phone sends latitude, longitude and its clock reading on the open connection. The server writes the cache entry with a 10 minute expiry, appends the history row and publishes to the sender's channel. No reply is sent; the next report corrects anything that was lost. |
| Pushed by the server holding my connection after it has checked the distance against my radius. Carries the friend's id, position, distance and the time of their report, so the phone can render the row with no further call. |
| The first frame carries my position. The server loads my friend list, takes a subscription for each of those friends, reads their cached positions, and returns the ones inside my radius as the first screen. Friends with no cache entry are treated as inactive. |
| Sent when a friendship is added or removed while the app is open, so the server holding my connection adds or drops one channel without my having to reconnect. |
| Ordinary request and response calls to stateless API servers backed by the user database. Turning sharing off here also deletes my cache entry and publishes a removal on my channel, so friends with the screen open drop me at once rather than after the expiry. |
The high-level design
Step 1 of 4
Open connections and a cache of latest positions
Start with the live path and the ordinary path kept apart. Each phone opens a WebSocket through the load balancer to a socket server and reports its position every 30 seconds; the server stores the latest position in a Redis cache under the user's id with a 10 minute expiry, so someone who closes the app disappears from the cache on their own. Everything that is not live, friends, profiles and settings, goes over HTTP to stateless API servers backed by the user database, which is sharded by user id. The socket servers are stateful, since each holds many open connections, and that is why the two kinds of server are separate: the stateless side can be deployed and scaled without touching any connection.
What breaks first
The deep dives
One location update, end to end. I walk two blocks and my phone sends a new position. Name each box it touches on the way to a friend's screen, and say where the distance check runs and why there.
Scaling pub/sub. Each update is delivered to about 40 online friends, so about 14 million deliveries a second. What carries that, how many servers does it take, and what decides the count?
Connections and friend changes. A person opens the app, adds a friend, and then the server holding their connection is removed for a deploy. What happens at each step, and what does a person with thousands of friends cost?
Concepts this guide uses
Sources
- Alex Xu, System Design Interview, chapter 18: nearby friends (notes by Preslav Mihaylov)
- Redis glossary: Understanding pub/sub in distributed systems
- Redis documentation: EXPIRE
- Wikipedia: Haversine formula
- Wikipedia: Geohash
- Wikipedia: Consistent hashing
- MDN: The WebSocket API (WebSockets)
- AWS documentation: Edit target group attributes for your Application Load Balancer (deregistration delay)