System design interview: design a nearby friends feature

A nearby friends feature shows which of your friends are within a few kilometres right now and keeps their distance up to date as everyone moves. The hard part is not finding points on a map but the update stream: every online user reports a position every few seconds, and each report has to reach that person's online friends, so the design centres on WebSocket connections, a pub/sub channel per user and a short-lived location cache.

By Published 7 min read

1. Clarify the requirements

This prompt sounds like the proximity search, and candidates who reuse that design lose time. Confirm that both sides move and that only friends count.

  • Functional: a user who opts in sees friends within a set radius (say 5 km) with distance and last-updated time; the list refreshes while the screen is open; friends who stop sharing or go offline disappear after a short delay.
  • Non-functional: a moving friend's distance updates within a few seconds; the system tolerates lost updates (the next one arrives soon); a user's position is visible only to friends they allowed.
  • Out of scope unless asked: showing strangers nearby, a map with routes, and long-term location history beyond what analytics needs.

2. Estimate the scale

Rough numbers for a large social app (assumed figures)
QuantityAssumptionResult
Users online in the feature at peak80 million daily users of the feature, 10% online at once8 million open connections
Location updatesone every 30 seconds per online userabout 267,000 updates a second
Fan-out300 friends who use the feature, 10% of them online30 deliveries per update, about 8 million messages a second
Pub/sub nodesassume one node moves about 200,000 messages a secondabout 40 nodes; run 80 for headroom and failover
Connection serversabout 100,000 WebSocket connections per serverabout 80 servers at peak
Latest-location cacheabout 100 bytes per online userunder 1 GB
Rough numbers for a large social app (assumed figures). Scroll sideways on a small screen.

Storage is tiny; message volume is large. That steers the design toward an in-memory message layer and away from polling a database for friends' positions.

3. Define the interface

client -> server   { type: "location", lat, lng, ts }              every 30 s
server -> client   { type: "friend_location", friend_id, lat, lng, distance_m, ts }
server -> client   { type: "friend_gone", friend_id }               stopped sharing / offline

POST /v1/sharing   { enabled: true, audience: "close_friends" }
GET  /v1/nearby    -> initial list when the screen opens
Messages over one WebSocket per device, plus two plain HTTP calls.

The initial GET avoids an empty screen: it reads the cache for each online friend, filters by distance, and returns the list in one response. After that, the socket carries changes only.

4. Sketch the data model

Where each piece of state lives
DataStoreNotes
Latest position per userKey-value cache: loc:{user_id} -> lat, lng, tsTTL of a few minutes, so silent users fall out on their own
Friend lists and sharing settingsSocial graph service and its databaseRead when a connection opens; changes are pushed as events
Pub/sub channelsOne channel per sharing userExists only while someone subscribes; no persistence
Location history (optional)Write-optimised wide-column store, partitioned by user and dayAt peak about 267,000 rows a second of about 50 bytes, roughly 13 MB a second
Where each piece of state lives. Scroll sideways on a small screen.

5. The core idea: publish once, filter at the edge

Two naive designs fail. Polling, where every open screen asks for all friends' positions every few seconds, multiplies reads by friend count and still lags. Writing positions into a geospatial index and searching around each user works for strangers but ignores that the result must be friends only, and it re-searches on every move.

  1. ConnectWhen a user opens the feature, their connection server loads their friend list and subscribes to the channel of every friend who shares with them.
  2. PublishEach location update is written to the cache with a TTL and published once, to the sender's own channel.
  3. ReceiveEvery connection server subscribed to that channel gets the message, once per subscribing user on that server.
  4. FilterThe server computes the distance between the friend's new position and the receiving user's latest position and pushes it only if it is within the radius, or sends friend_gone if they just left it.

Publishing to the sender's channel instead of to each friend's inbox keeps the publish cost constant: one message, whatever the friend count. The cost moves to subscriptions, which are cheap in memory (about 5 GB of subscriber entries for 8 million users with 30 online friends each, at roughly 20 bytes per entry).

6. The architecture

  1. Devices
    • Phones with the feature open
  2. Connections
    • Load balancer
    • WebSocket connection servers
  3. Real time
    • Pub/sub cluster, channel per user
    • Location cache with TTL
  4. Supporting
    • Social graph service
    • Sharing settings
  5. Async
    • Queue
    • Location history store
Update flow for nearby friends. Phones keep a WebSocket open to a fleet of connection servers behind a load balancer. A location update goes to the user's connection server, which writes the position to a location cache with a TTL and publishes it to the user's channel on a pub/sub cluster. Connection servers that host the user's friends are subscribed to that channel; they receive the update, compare it with each local friend's latest position and push it over the socket if within range. A social graph service supplies friend lists and sharing settings, and sends events when they change. Optional history is written asynchronously from a queue.

Connection servers are stateful: they hold sockets and subscriptions. Deploy them by draining (stop new connections, let clients reconnect elsewhere over a few minutes) rather than killing them, or every client reconnects at once.

7. Deep dives

  • Sharding pub/sub. Spread channels over nodes with consistent hashing on the user ID. Adding a node moves some channels, so subscribers on those channels must resubscribe; do it in a quiet hour and keep a little spare capacity so it is rare. The node map itself sits in a small coordination store that connection servers watch.
  • Friend list changes. A new friendship or a revoked permission arrives as an event; the connection servers involved add or drop one subscription. Because one publish goes to every subscriber, the sender's side cannot filter per friend, so the receiving connection server also checks its cached sharing settings before pushing, and a revoked friend stops receiving even if an unsubscribe is lost.
  • Battery and bandwidth. Phones send less often when still or in the background, and the server sends only meaningful changes (say, moved more than 100 m). Both cut traffic more than any server tuning.
  • Precision. For users who choose a rough location, round the position before publishing so the exact point never leaves the sender's connection server.
  • Strangers nearby (if asked). Use geography-based channels instead: one channel per geohash cell, users subscribe to their cell and its neighbours. The indexing details are in design a proximity service.

8. What breaks, and what you do about it

Failure modes
FailureEffectMitigation
Connection server crashesIts users lose their socket and subscriptionsClients reconnect with backoff and jitter; the new server rebuilds subscriptions from the friend list
Pub/sub node failsChannels on it go quietFail over to a replica or remap channels; positions stay in the cache, so the next update or a refresh recovers
Update lost in transitA friend's distance is briefly staleAccept it; the next update arrives in seconds; show the last-updated time
Mass reconnect after an outageThundering herd on connection servers and the graph serviceJittered reconnects, admission limits, cached friend lists
Cache entry expires while user is still onlineFriend briefly disappearsRefresh the TTL on every update; set the TTL to several update intervals
Failure modes. Scroll sideways on a small screen.

9. Trade-offs to discuss

  • Push or poll. Push over sockets gives seconds of freshness with stateful servers; polling is stateless and simpler but wastes requests and lags. For a screen people watch, push wins.
  • Filter at sender or receiver. The sender does not know every friend's position without extra reads; the receiver's server already holds it. Filtering at the receiver wastes some deliveries to out-of-range friends but avoids a read per friend per update.
  • Delivery guarantees. At-most-once is fine here because positions supersede each other. Paying for durable queues would buy nothing; compare that with a notification system, where a lost message matters.

10. How to talk through it in the interview

Fictional example

Defending the fan-out
Interviewer
Someone with 5,000 friends opens the app downtown. Does that blow anything up?
Candidate
Their updates are still one publish each. The cost shows up as subscribers: maybe 500 of those friends are online, so 500 deliveries per update across a few dozen connection servers. That is a heavy user but not a hot spot, and I could cap shared audiences if it became one.
Interviewer
And why not put everyone in a geospatial index?
Candidate
Because the question is friends only. A spatial search returns strangers I would then filter out, and it reruns on every move. The friend graph already tells me exactly who should hear an update.
  • Derive the 8 million messages a second figure; it justifies everything that follows.
  • Say where the distance check happens and why.
  • Treat lost updates as acceptable and say so; it simplifies the whole message layer.

Practicing this design with Natively

This one is easy to over-design out loud, so rehearsing against the clock helps. During a practice call, Natively keeps a running transcript and can suggest what to cover next when the interviewer pushes on fan-out; it can also draw the connection-server and pub/sub flow as a diagram inside its answer, which you can set beside your own sketch. The notes and transcript left afterwards make it easy to see how long the requirements took.

Questions people ask

How does a nearby friends feature work?

Each online user sends a position every few seconds over a WebSocket. The server stores it in a cache with a short TTL and publishes it to that user's pub/sub channel. Servers holding the user's friends receive it, check the distance against each friend's own position and push the update if it is within range.

Why use pub/sub instead of a database for friend locations?

Positions change every few seconds and lose value within minutes, and the volume is set by fan-out to online friends. An in-memory pub/sub layer delivers each update once per listener without disk writes, while a database would turn every move into reads by every friend.

How is nearby friends different from a proximity service?

A proximity service searches static places around one moving user, so it needs a spatial index. Nearby friends tracks many moving users but only within a friend list, so it needs a real-time message path and uses the friend graph instead of a spatial search.

What happens if a location update is lost?

Usually nothing serious. Each new position replaces the last, so the friend's distance is briefly stale and corrects itself with the next update a few seconds later. Showing the last-updated time keeps that honest.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP