Skip to content

How to design nearby friends

The first sections are free. The deep dives, level expectations and quiz are part of Pro.

On this page
Practice this question

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

AskWhy it mattersA 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.

The requirements menu

RequirementScopeWhy

See friends within 5 miles (configurable), with their distance and when it was last updated

Core

The product itself. The radius decides where the distance check runs, and the timestamp is why each stored location carries the time it was reported.

The list refreshes every few seconds

Core

This is what rules out a page the user reloads. Friends' moves have to reach the phone without the phone asking, which means an open connection or very frequent polling.

Friends inactive for 10 minutes drop off the list

Core

Someone who closed the app should not sit on the list at a stale spot. An expiry on each stored location handles it without a cleanup job, which is the choice this design makes.

Location history is kept for analytics

Core

Turns each update into a durable append as well as a cache write. The history store has to take the full write rate but is read by nobody in the live path.

Turn sharing off, or pause it for a while

Optional

Worth taking if time allows: it is a settings call over HTTP, but a person who turns sharing off should vanish from friends' lists at once, which means deleting their cached location and pushing a removal to friends who are watching, rather than waiting for it to expire.

A slower report interval when the phone has not moved

Optional

Cuts the update rate and saves battery, and it is cheap to add because the interval is a client setting. Leave it if the interviewer wants the full 334,000 updates a second on the board.

Hide my location from some friends but not others

Out of scope

Real products have this, but it adds a permission check per delivery. Say where the check would sit (the friend's server, before pushing, since a publish reaches all subscribers of the channel) and park it.

See strangers nearby who also opted in

Out of scope

Keep it in mind as a twist. It changes how updates are grouped, from one channel per person to one per area, so name it and keep the friends design simple until asked.

A notification when a friend comes into range while the app is closed

Out of scope

Delivery to a closed app goes through the platform's push service, a different path with different latency. Out of scope for a round about live updates.

Querying location history for analytics

Out of scope

Writing history is in scope; reading it is a batch or warehouse job that does not touch the live path.

GDPR and other privacy law

Out of scope

Retention and consent matter in production, but they are policy on top of the design. Mention that history retention would follow it and move on.

Showing friends on a map

Out of scope

A map is a client rendering concern plus a tile service. The backend returns the same list either way.

Distances by road; straight-line distance is enough

Out of scope

Road distance needs a routing engine per pair of friends. A straight-line formula is a small computation on the server that already holds both positions.

Non-functional requirements

RequirementWhat 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

QuantityWorkingResultWhat 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

EntityWhat 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

EndpointNotes

WebSocket: send my location every 30 seconds

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.

WebSocket: receive a friend’s location update

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.

WebSocket: on connect, send my location and receive my nearby friends

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.

WebSocket: subscribe to or unsubscribe from a friend

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.

HTTP: friends, profiles and settings

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

socketHTTPexpiryMy phoneLoad balancerAPI serversSocket server AUser databaseCache

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.

socketHTTPfriendsexpirypublishappendchannelradiusringMy phoneLoad balancerAPI serversSocket server AUser databaseLocation cacheRedis pub/subCassandra historySocket server BFriend's phoneetcd registry
The whole design

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.

A concept that helps here: WebSockets, server-sent events and pollingA concept that helps here: Cache invalidation and TTLsA concept that helps here: Fan-out on write and on read

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?

A concept that helps here: Consistent hashingA concept that helps here: Hot keys and hot partitionsA concept that helps here: Geospatial indexing

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?

A concept that helps here: Routing messages between stateful serversA concept that helps here: Heartbeats and presenceA concept that helps here: Load balancing at layer 4 and layer 7

Concepts this guide uses

Sources

  1. Alex Xu, System Design Interview, chapter 18: nearby friends (notes by Preslav Mihaylov)
  2. Redis glossary: Understanding pub/sub in distributed systems
  3. Redis documentation: EXPIRE
  4. Wikipedia: Haversine formula
  5. Wikipedia: Geohash
  6. Wikipedia: Consistent hashing
  7. MDN: The WebSocket API (WebSockets)
  8. AWS documentation: Edit target group attributes for your Application Load Balancer (deregistration delay)
Sign in to report a mistake