System design interview guide
Nearby Friends System Design Interview
Picture opening a map app at a concert to find the friends who said they would be there. The app shows one friend as nearby, so you start walking toward that dot, but the friend left ten minutes ago, because the map is still using the last spot their phone shared before they crossed town. The part of the app that decides which friends to show on that map is called nearby friends. It has to be quick, gentle on the phone battery, and careful about privacy, since a wrong dot can point at someone who does not want to be found. A good answer explains how the map stays fresh, who is allowed to see whom, and what happens when thousands of people stand in one small area.

Problem statement
Picture opening a social or maps app and asking which of your friends are close to you right now. People opt in to share a rough location from their phones, a viewer asks who is within some distance, and the system answers using only friends who are allowed to be seen and whose location is still fresh. That feature is nearby friends.
Interviewers care that you can explain how the system finds those friends without checking everyone, how often phones send a location, how a paused or blocked person stays hidden, how old locations expire, how a crowded concert is handled, and how repeated lookups of one person are limited. Privacy is part of the core design, not a setting added after the map search works.
Introduction
The problem: a friend who is no longer there
Picture standing in a crowd at a concert, trying to find the friends who said they would come. You open the map in your social app, and it shows a small dot with a friend's name about two hundred metres away. You walk that way and find nobody. That friend left ten minutes ago, and the map was still using the last place their phone reported before they went home. Nothing crashed and no error appeared. The app simply showed an old fact as if it were current.
Now turn the scene around. Imagine you stopped sharing your location an hour ago because you wanted a quiet evening, or you blocked someone you do not want near you. If the app still showed your dot to that person because an old record was sitting in a database, the mistake would be far worse than a wasted walk. It could put a real person at risk.
The feature behind that map is called nearby friends. When you open the map, it shows which of your friends are close to you right now, among the friends who agreed to be seen. It looks small, but it combines three hard things: a constant stream of changing locations from millions of phones, a social network that says who is friends with whom, and privacy promises that must hold every single time, not just most of the time. This page walks through the problem in the order you would think about it in an interview: first what we are solving and why, then what the system must do, then how big it is, then the design choices one at a time, and only after that the finished picture.
Why teams bother with nearby friends
People use features like this to find each other at a festival, on a campus, or in a new city, long before anyone thinks about how the map is built. Behind the friendly dots are reasons a company still cares enough to ship the feature carefully.
Meeting up. Plans are easier to carry out when people can see who is already close. A friend two streets away is a reason to say "come and join us", and that is the kind of moment that makes people open the app.
Trust and safety. Location is among the most sensitive information a company can hold. A feature built carelessly can reveal where someone lives or works, or help someone follow another person. Teams build it carefully because one bad incident is hard to undo.
Battery and cost. A phone that reports its position every few seconds uses a lot of battery, and tens of millions of phones doing it produce an enormous number of writes for the company's servers. If people notice the battery drain, they switch the feature off, and then it has no value.
Legal and privacy duties. In many places the law expects a company to ask for permission, keep location only as long as it needs it, and let people delete it. Those duties shape what the system stores and for how long.
The phone showing a friend who already left is one more case of the same idea: a location is only useful while it is fresh, and it is only acceptable to show while the person agreed to be seen.
What problem are we solving?
A person opens the map and the system has to answer one question:
“Among the people I am allowed to see, who has a fresh location near me?”
The input is a stream of location reports from phones whose owners opted in, plus a request from a viewer that says where they are and how far to look. The output is a short list of friends, each with a rough distance and a note about when the location was last updated. Success means the list is quick to arrive, close to the truth, and contains no one who should not be there.
The wrong answers are easy to picture. A friend who paused sharing still appears. Someone who left thirty minutes ago still looks nearby. A person who blocked the viewer still shows up because an old record survived. And a pattern of repeated checks quietly tracks someone all the way home.
This is not a feature for finding every stranger in the city. It is friend-based and permission-based, which makes it a smaller and safer problem than a general map search. How the system finds those friends quickly, and where it keeps the locations, is the design. We will not guess at that yet. First we need to be clear about what the system must do and how well, so that every choice later has a reason behind it.
This page is in the system design interview guides hub.
How to approach
In an interview you do not start by drawing boxes. You start by turning a short, vague prompt into a clear contract: who shares, who can see, what the map shows, how fresh it must be, and what is out of scope. Only then do you size the problem, make the design choices one at a time, and draw the result. The list below is the order this page follows.
How to design nearby friends in an interview
- Clarify the problem: who opts in, who can see whom, how precise the display is, how fresh a location must be, how often a phone may report, and how big the system is.
- Write the functional requirements (what the system does) and the non-functional requirements (how fast, how fresh, how private, how big).
- Estimate the size: how many people share, how often they report, how many times the map opens, and how many friends a person has.
- Make the design choices in order: when a phone reports, what is stored and for how long, how to find people near a point, what to search first, where permission is checked, what the viewer sees, what happens in a crowd, and how to stop misuse.
- Draw the picture those choices produce, then walk one location update and one map open through it.
- Go deeper where the interviewer pushes: moving between areas, hidden people with old records, crowded venues, and repeated lookups of one person.
Clarifying questions (say these in the room)
In a real interview the prompt is only a few words: “Design nearby friends.” Before you design anything, ask questions until the problem is clear. Each answer below changes the design, which is why it is worth asking.
You: “Is sharing opt-in, and do two friends need to agree before they can see each other? Can a person pause, and can they block someone?”
Interviewer: “Yes, users opt in; friends and blocks matter.”
That answer makes privacy part of every lookup, not a settings page you can ignore. Whether a person may be shown has to be checked at the moment the map is opened, because it can change between one minute and the next.
You: “What should the map show: an exact pin, an exact distance in metres, or something rougher like ‘within 500 m’?”
Interviewer: “Use coarse buckets by default; exact location is not required.”
Write on the board: “Default response = rough distance plus last updated, not raw latitude and longitude.” That one choice drives what you store and what the API returns.
You: “How fresh does a location need to be before we hide it or mark it old?”
Interviewer: “Hide or mark it old after about 10 to 15 minutes.”
Pick a window in that range and call it the freshness window. The technical name for “this record counts as gone after a set time” is a TTL, which stands for time to live. After that time, an old dot must not pretend to be live.
You: “How often can the phone send updates? Every reading from the GPS chip, or only when something meaningful happens?”
Interviewer: “Be battery-aware; do not stream every GPS tick.”
So updates are triggered by movement or by time, not by a clock that ticks once a second. That decision will matter for both battery and server load.
You: “Roughly how many people share at once, how many friends does a typical person have, and how often do people open the map?”
Interviewer: “Assume tens of millions of people sharing, a few hundred friends each, and map opens that spike near big events.”
Those numbers feed the capacity estimate in the next section. They also tell you early that one machine will not be enough and that a crowded event is the case to worry about.
You: “How exact does the result have to be? If a friend is a little outside the radius and still shows, or one right on the edge is missing, is that acceptable?”
Interviewer: “A small error at the edge of the radius is fine. Showing someone who should be hidden is never fine.”
This is an important split. Distance can be approximate, because a friend 600 metres away appearing in a 500 metre search is not harmful. Permission and freshness cannot be approximate, because a wrong answer there shows someone who should not be shown. Saying this out loud tells the interviewer you know which errors are cheap and which are not.
You: “I want to keep turn-by-turn navigation, a full location-history warehouse, and finding strangers nearby out of scope, so we can focus on friend-filtered nearby search and privacy. Does that match what you want?”
Interviewer: “Yes, focus on friend-filtered nearby search and privacy.”
If the interviewer later asks about map libraries or crowded venues, you do not need to answer yet. Park those until the design choices, where each one has a natural place.
Functional requirements
Functional requirements describe what the system does. From the answers above, nearby friends must:
- Let a person opt in and share a rough location. Nothing is collected until the person agrees, and they can stop at any time.
- Accept location updates as the person moves. The phone reports when something meaningful changes, so the system always has a recent position for people who are sharing.
- Answer “who is nearby?” for a viewer. Given where the viewer is and how far to look, return the friends who are close.
- Show only people the viewer is allowed to see. Friendship, blocks, pause, and any audience setting (for example, “close friends only”) all apply on every lookup, not only when the data is written.
- Let a person pause sharing and block someone. A paused or blocked person must disappear from the right viewers quickly.
- Show a rough distance and when the location was last updated. This lets the viewer judge how much to trust a dot without learning exactly where someone is.
Non-functional requirements
Non-functional requirements describe how well the system must do its job. They are the numbers and promises that shape the design.
- Speed. Most map opens finish in under about 500 milliseconds, so the map does not sit blank while the answer is built.
- Freshness. A location older than about 10 to 15 minutes is hidden or marked old. A stale dot is worse than no dot, because it sends someone to the wrong place.
- Privacy and short retention. Raw location is kept only as long as the product needs it, and the default display is coarse. If it is unclear whether a person may be shown, they stay hidden.
- Battery friendliness. The phone must not send a reading on every tick, because a feature that drains the battery gets switched off.
- Scale. Tens of millions of people share, updates can spike inside one region, and a single crowded place can dominate the cost of a lookup.
- Abuse resistance. Even a friend who is allowed to look must not be able to use the map to follow someone, so repeated lookups of one person have to be limited and noticed.
- Graceful failure. When a part of the system is slow or down, the map shows less, not something wrong. Showing no one is better than showing the wrong person.
Out of scope (and why you park these)
Write a short out-of-scope list on the board so the interviewer sees you can bound the problem.
Turn-by-turn navigation. Navigation needs continuous routing, road maps, and live traffic. Nearby friends only needs approximate closeness to people who agreed to be seen.
A permanent location-history warehouse. Trends can be sampled or combined into totals elsewhere, but raw exact history creates privacy risk and does not belong on the path that answers a map open.
Finding strangers nearby. Searching for people you do not know is a different product with a much higher risk of abuse. This design is limited to friends.
Perfect real-time precision. A few minutes of freshness is usually enough. Exact live tracking drains the battery and raises the risk of someone being followed.
That is the requirements stage. If you want to practice it before reading on, try the requirements stage on Practice System Design (about 5–10 minutes), then come back for the sizing and the design choices.
Minute pacing (about 45-60 minutes)
| Minutes | Focus |
|---|---|
| 0–5 | Clarify opt-in, precision, freshness, update policy, scale; write functional and non-functional requirements; agree out of scope |
| 5–12 | Capacity, then the design choices one at a time |
| 12–25 | The high-level boxes, then one location update and one map open walked through |
| 25–40 | The deep dive: moving people, hidden people with old records, crowded venues |
| 40–50 | Scaling, failure, privacy and abuse |
| 50–60 | One production story, tradeoffs, and questions |
In the room (how you open): “I’d start by agreeing who can share and who can see whom, because every answer depends on it. I’d ask how precise the display must be, how fresh a location has to be, how often a phone is allowed to report, how many people and friends we are talking about, and which kind of mistake is worse: showing someone slightly outside the radius, or showing someone who should be hidden. I’ll write the requirements on the board, size the problem, and then make the design choices one at a time, so every box I draw has a reason.”
If you remember one thing: Ask first, write the requirements down, and only then design. Say out loud that wrong permission is never acceptable, while a slightly wrong distance is.
Capacity estimation
Once the requirements are clear, the next step is to find out how big the problem is, because the size decides whether one machine can do the job or the data has to be spread out. The numbers below are illustrative estimates to anchor the whiteboard. Tune them in the room, and say that you would confirm them with real traffic.
| Input | Estimate | What it means for the design |
|---|---|---|
| People sharing at once | About 50 million (the prompt says tens of millions) | Too much for one machine; most data should live near where people are |
| If a phone reported every 5 seconds | 50M ÷ 5 s = about 10 million writes per second | Not workable; reports must be triggered by movement or time and throttled |
| With throttled reports (about one per 2 minutes on average) | 50M ÷ 120 s ≈ 400,000 writes per second, perhaps 1 million per second at a peak | Still large, but each write is small and can be spread out by region |
| Latest location per person | About 100 bytes × 50M ≈ 5 GB | The latest state is small; keeping only the latest, not a history, is what keeps it small |
| Map opens | About 10 million in the busiest hour ≈ 2,800 per second, perhaps 8,000 per second at a peak | Far fewer than writes, but each open does much more work |
| Friends per viewer | About 300 | Checking every friend on every open would be 8,000 × 300 ≈ 2.4 million location lookups per second |
| Crowded place | About 50,000 people in one small area | If 5,000 of them open the map in one minute, one list of 50,000 people is read 5,000 times, about 250 million entries a minute |
| Time budget | 500 ms for most opens | Split roughly between reading the friend list, reading the local area, filtering, and returning |
What the numbers imply
- Writes are more numerous, but map opens are more expensive. An update is one small write. A map open has to look up a friend list, read a local area, check permissions, and compute distances. The crowded-place row shows how a single open can turn very costly.
- Throttling on the phone is not optional. Without it, the write rate in the table above is about twenty-five times higher. The server also needs its own limit, because a bad app release can ignore the phone's rules.
- Keeping only the latest location keeps memory small. About 5 GB of latest state is manageable once it is spread across machines. A history of every report would be many times larger and would also be a privacy risk.
- Do not check every friend on every open. At the estimates above that would be millions of lookups a second, each a network call.
- Crowds, not averages, set the worst case. Average load can look healthy while one venue is slow, so the design has to be judged on the crowded place.
Checkpoint: Why are map opens the hot action even though updates are more numerous?
If you remember one thing: Updates are many but cheap. Map opens are fewer but costly, and a crowd makes the cost climb fastest.
Design decisions
We now know what the system must do, how well it must do it, and roughly how big it is. Now we choose. Each decision below answers one question that the requirements raised, and each one rules out an easier idea that would not survive the requirements. Read them in order, because every decision builds on the one before it.
Decision 1: When does a phone send its location?
The requirements said the battery must last and the number of writes must stay manageable. The simplest idea is for the phone to send its location every second, or every few seconds, so the server always has the very latest position.
That fails two requirements at once. In the estimate above, 50 million phones reporting every 5 seconds is about 10 million writes a second. And each report wakes the phone's location chip and its radio, which is exactly what drains a battery.
There are a few ways out. The phone could report on a fixed timer, say every two minutes, which is simple but wastes reports on people who are standing still and still goes stale for someone who is moving fast. It could report only when the person moves far enough, which is cheap on battery because modern phones can tell an app “wake me only after a significant move”, but then a person who sits still for an hour looks like they vanished. Or it could report when the person opens the map, which keeps the viewer's own position fresh but does nothing for friends.
The choice is a mix. A phone that has opted in sends a report when it has moved far enough, or when a minimum amount of time has passed (a small heartbeat that says “I am still here”), or when the person opens the map. It includes how accurate the reading is, and if the accuracy is poor it waits or sends a rougher position. The server adds its own limit per device on top, because a buggy app release that ignores these rules should not be able to flood the backend.
Decision 2: What do we store about a location, and for how long?
Once reports arrive, the system has to decide what to keep. The simplest idea is one row per person with exact latitude and longitude, updated on every report, with the older rows kept “in case analytics needs them”.
That breaks the privacy and retention requirements. A trail of exact positions shows where someone lives, where they work, and when they go there, and a leak of that table would be far more harmful than a leak of ordinary profile data. It also says nothing about when a position is too old to show, which breaks the freshness requirement.
The alternatives are to keep a full history (the most private risk and the most storage), to keep only the latest exact position, or to keep only the latest position at a lower precision with a timestamp and an expiry. We choose the last one. Each sharing person has exactly one latest state record, holding the position rounded to the precision the product promised, the time it was updated, and a time after which the record counts as gone (the TTL from the clarifying questions, about 10 to 15 minutes). The store removes expired records by itself, so freshness stays correct even if a cleanup job falls behind. If the business wants movement trends, those are counted or averaged outside this path and never read back when the map opens.
Decision 3: How do we find people near a point without checking everyone?
The system now holds the latest location for every sharing person, and a viewer asks for people near a point. The simplest idea is to measure the distance from the viewer to every sharing person and keep the close ones.
With tens of millions of people that is far too slow for a 500 millisecond budget, and it would run thousands of times a second. We need a cheap first step that throws away almost everyone, and only then do exact distances for the few who are left.
The idea is to cut the map into small squares and give each square an id. These squares are called cells. When a person reports a location, the system works out which cell they are in and files them under it. When a viewer asks who is nearby, the system lists the cells that cover the search circle, reads only the people filed under those cells, and ignores the rest of the world. Two details matter here. First, the circle often touches a few cells, including neighbours, because a friend ten metres away can be standing just across a cell border, so the system must read all the cells the circle touches, not only the viewer's own cell. Second, the cell size should be about the size of the search radius, so a lookup touches a handful of cells; if the cells are far too large the lists are huge, and if they are far too small a lookup has to read dozens of cells.
A cell answer is only “who might be nearby”. It says nothing about who is allowed to appear. That is decided by later steps. Common ways to make cell ids are geohash, S2, and H3, and the section on core design approaches compares them. In the room, name one and explain the pattern, because that matters more than arguing about the brand.
To make this work the system keeps two lookups. One says “where is this person right now?” and is used to check freshness and privacy. The other says “who is in this cell right now?” and is used to find candidates quickly. Most designs keep both.
Decision 4: Do we search the map first, or the friend list first?
There are two possible starting points for a lookup. The simplest is to start with the viewer's friend list, which holds about 300 people, look up the location of each, and keep the close ones. For a small product that is perfectly fine and easy to build.
At the estimate of about 8,000 map opens a second at a peak, that is about 2.4 million location lookups every second, each a call to a store, and some people have thousands of friends. That strains the speed and scale requirements.
The other way starts from the map. Read the people in the cells around the viewer, then keep only those who are on the friend list. That reads a few cells instead of hundreds of friends, and it is the choice for a large system. The cost moves to a different place, though: in a dense area the list of people in a cell is large, and most of them are not friends.
So the choice is cells first, then friends, because the number of cells touched is small and steady while the friend list can be long. The friend ids are loaded as a set at the same time the cells are read, so checking “is this person a friend?” is a quick lookup. State your expected numbers out loud (300 friends, a few cells), so the cost is visible. Decision 7 returns to the dense-area case, and there we will sometimes flip the order.
Decision 5: Where is permission decided?
A person found in a cell is only a candidate. The requirements said paused and blocked people must stay hidden, even if an old record still exists. The simplest idea is that friends can see each other, and the app hides anyone who paused.
That fails in two ways. A check that lives only in the app can be bypassed by anyone who changes the app, and a friend setting is not enough because the person might have paused, blocked the viewer, or shared only with close friends.
Another idea is to remove a person from the index the moment they pause or block. That is a good thing to do, but it depends on a message arriving and a delete finishing, and if either is slow or lost, the person is still in the index and shows up on a map.
So we do both. When someone pauses or blocks, the system removes them from the index quickly, and on every map open the query service also re-checks the current privacy state of each candidate: is sharing on, is it paused, does either side block the other, and does the audience setting allow this viewer. The index finds candidates and never grants permission. The privacy and friend data can be cached for speed, but only for a short time, and the cache is cleared whenever someone blocks, pauses, or unfriends. If the system cannot confirm the state, it hides the person. The time from “pause” to “hidden everywhere” becomes a safety measurement worth watching.
Decision 6: What does the viewer see?
After the candidates are filtered, there is a list of friends with exact positions. The simplest idea is to return those positions so the app can draw a pin for each friend.
The requirements said not to reveal exact positions by default, and there is a second, less obvious reason. Even an exact distance is revealing: if someone can ask “how far is Alex?” from three different places, they can work out exactly where Alex stands. Exact positions also show homes and routines.
The alternatives are an exact pin, an exact distance, a bucketed distance like “within 500 m”, or a named area like “near Central Park”. We choose a bucketed distance together with a “last updated” time, for example “within 500 m, 2 minutes ago”. The system computes the exact distance only for the people who survived the earlier filters, turns it into a bucket, and returns the bucket. If the product wants to offer more precision to close friends, it is an explicit choice that the person made, not the default.
Decision 7: What happens when thousands of people are in one place?
So far every cell is the same size. The simplest idea is to keep it that way everywhere. In a city centre on a normal day that works. At a stadium it fails: one cell holds the list of tens of thousands of people, and every viewer in the crowd reads that whole list. In the estimate above, 5,000 viewers reading a list of 50,000 people is about 250 million entries a minute, while the rest of the country looks idle.
There are a few ways out. Using much smaller cells everywhere would fix the stadium, but every ordinary lookup would then have to read many more cells and the index would change constantly as people cross tiny borders. Capping what is read and degrading the answer helps, but it can miss friends. Splitting only the crowded cells into smaller ones adapts to the venue and leaves the rest alone.
We choose three things together. Crowded cells are split into finer sub-cells (S2 and H3 make that easy because their cells come in nested sizes). The number of candidates read per lookup is capped. And when the crowd list is much bigger than the friend list, the query flips the order and looks up the viewer's few hundred friends directly, instead of reading fifty thousand strangers. If the cap is hit, the product degrades to a gentle message such as “many friends in this area” instead of trying to rank everyone.
Decision 8: How do we stop the map from being used to follow someone?
Each lookup has been authorized, the person is a friend, and the answer is coarse. The simplest idea is to stop there. That leaves a gap: an allowed friend can ask the same question about the same person every minute, from many places, and quietly follow them. Every single request looks valid, which is why this kind of misuse hides in normal-looking traffic.
An overall rate limit on the API helps against scanning a grid of the map block by block, but it does not stop a slow, steady watcher. Detecting the pattern needs to look at pairs: which viewer keeps asking about which target, how often, and whether they ever interact normally.
So the choice is layered. Cap the search radius and the lookup rate at the API (the rate limiter guide shows how). Watch viewer and target pairs in the background, off the path that answers the map. Keep an audit record of sensitive lookups. When risk looks high, lower the precision, ask the target, or block the viewer. Internal support tools follow the same rules, with a reason code on every use.
Putting the decisions together
Taken together, the eight decisions are the design. A phone that opted in sends a small report when it has moved far enough or waited long enough. The server keeps only the latest, coarse position with an expiry and files the person under a map cell. When someone opens the map, the system reads the cells around them, keeps only friends, re-checks permission and freshness for each, hides anyone it is unsure about, computes distance only for the few who remain, and returns a rough bucket with a last-updated time. Crowded cells are split and capped, and repeated lookups of one person are limited and watched.
In the room (a fuller opening you can actually say): “I’d make this opt-in and privacy-first. A phone reports only when it has moved far enough, when a minimum time has passed, or when the person opens the map, and the server also limits each device. The server keeps one latest, coarse location per person with a timestamp and an expiry of about ten to fifteen minutes, not a history of exact positions. To find people near a point I’d cut the map into cells, read the cells covering the radius including neighbours, and then keep only the viewer’s friends. Permission is re-checked on every lookup: sharing on, not paused, no block in either direction, audience allowed, and fresh enough. If I cannot confirm any of that, the person is hidden. The viewer gets a rough distance bucket and a last-updated time, never raw coordinates by default. For a stadium I’d split the crowded cell, cap how many candidates I read, and look up the friends directly when the crowd is bigger than the friend list. For misuse I’d limit the radius and rate, watch repeated lookups of one person, and keep an audit trail.”
The next section draws these decisions as one picture and shows who owns what.
High-level architecture
The decisions above were made one at a time. This section puts them on one page as a picture: which services exist, who owns what, and how a location update and a map open travel through them. The deeper mechanics come later, so keep this at the level of a map.
The design has four main services. Location ingress is the door that receives updates from opted-in phones and turns each position into a map cell—a small area id on the map. Location index stores each person’s fresh location by user id and by cell. Graph and privacy service owns friends, blocks, visibility, and sharing state. Nearby query service combines cells with those graph rules and returns safe results.
Who owns what:
- Mobile client decides when to wake the GPS chip, applies battery-aware throttling, and sends accuracy plus movement details.
- Location ingress checks who the user is, confirms they opted in, rejects impossible jumps, rounds the location to the precision the product promised (so it never stores more detail than it promises), and writes the fresh state.
- Location index keeps
user_id -> current cell and locationandcell_id -> user ids, with an expiry on each. - Graph and privacy service returns allowed friend ids, blocks, close-friend tiers, and pause or hide state.
- Nearby query service works out the covering cells, merges candidate lists, filters by friendship and privacy, calculates the final distance, and returns the rough display fields.
- Abuse and risk pipeline watches repeated lookups, suspicious target patterns, fake GPS signals, and internal tool access.
[ Mobile client ]
| opt-in + movement / interval update
v
[ Location ingress ] ---> [ Location index ]
| user -> cell + updated_at
| cell -> user ids (TTL)
|
+--> abuse / anomaly stream
[ Nearby query ]
| 1) auth + viewer privacy
| 2) graph: allowed friend ids + blocks
| 3) cells covering radius
v
[ Location index candidates ] -> intersect -> distance refine -> coarse response
In the room: Say the order clearly. Cells find a local candidate set, the graph and privacy rules decide who is allowed, and exact distance runs only on the survivors. Do not make “exact distance to everyone” the first step. (That exact-distance maths is often called Haversine, but you do not need to lead with the name.) Include neighbouring cells so friends near a cell border are not missed.
Core design approaches
The design above relies on cells, two lookups, and a choice of what to search first. This section looks at the alternatives behind those choices, so you can say when each one fits and why.
Cell schemes: geohash, S2, and H3
Nearby search needs a cheap first filter, “who is in this neighbourhood of the map?”, not “check every user on earth”. Three common ways to give map cells an id are below.
| Scheme | How it works | Strength | Watch out for |
|---|---|---|---|
| Geohash | Turns a position into a short text string; places that are close often share the start of the string | Easy to sketch and to store in any database | Two points that are close can have very different strings across a cell border, so you must read neighbouring cells; cells get narrower toward the poles |
| S2 | Maps the globe onto cells in nested sizes, each with a 64-bit id | Nested sizes make it easy to split a crowded cell; a built-in helper lists the cells covering a circle | More to learn than geohash |
| H3 | Covers the globe with hexagons in nested sizes | Every neighbour is about the same distance away, which makes radius searches tidy | Child cells do not fit exactly inside their parent, which matters if you split crowded cells |
In the interview, naming one and explaining the candidate-filter pattern matters more than arguing about the brand.
User-to-cell and cell-to-users
Once the map is cut into cells, the system still needs two different ways to look things up, because a map open and a privacy check ask different questions.
- By user: “Where is Alex right now?” The system stores the latest cell, with a coarse location, for each sharing person.
- By place: “Who is in these nearby cells?” For each cell it keeps the list of people currently in that square. Engineers often call that list a posting list.
A map open needs the second. Checking freshness and privacy needs the first. If you only keep “where is each friend?”, you still walk hundreds of friends one by one, which is fine for a tiny product and painful at high traffic.
Query cells first vs friends first
After you have both lookups, the next choice is which one you start with when someone opens the map. Starting with the friend list is easy to explain; starting with the nearby cells is usually cheaper when traffic is high. The table below compares the two orders.
| Order | When it works | Cost risk |
|---|---|---|
| Friends first | Small friend lists, sparse areas | Every map open walks all of a person's friends |
| Cells first, then friends | Large friend lists, high traffic | Reads a few cells, then intersects with the friend set; dense cells make the first read heavy |
If a viewer has about 300 friends, either order can work for a small product. At scale, prefer cells first, then intersect, and when one cell is far bigger than the friend list, look up the friends directly. State the expected friend count and make the cost visible.
Pull map query vs push “friend nearby”
There is also a product choice about when the answer is computed. In a pull design, the app asks “who is nearby?” only when the person opens the map. In a push design, the server sends a notice such as “a friend is nearby” even when the map is closed. Pull is simpler to build and calmer for the person being found. Push can feel creepy and can create floods of notices at events. Default to pull, and treat push as an optional product with strict caps, quiet hours, and user controls.
Data model
Now that we know what the system keeps, the next question is what exactly gets stored. Location data should be short-lived and permission-aware. The model needs to answer the current position, which cell someone is in, how fresh it is, and whether it may be shown.
| Entity | Key fields | Why it exists |
|---|---|---|
location_state | user_id, cell_id, coarse lat/lng, accuracy, updated_at, version, expiry (TTL) | Current fresh location for a sharing user |
cell_membership | cell_id, user ids, update version or score | Candidate lookup for a nearby query |
privacy_state | user id, sharing mode, precision tier, paused flag, allowed audiences | Decides whether location may be returned |
friend_edge | user A, user B, state, close-friend tier | Friend filtering and optional precision tier |
block_edge | blocker, blocked, updated_at | Must remove visibility immediately |
query_audit | viewer, target or candidate count, time, reason, tool | Abuse and compliance review where required |
One person first: Alex opens the app at a concert and her phone reports a position. The system stores location_state:alex with her cell, a rounded position, a timestamp, and a version number, and it adds her to the member list of that cell. The table above is the same idea in general form.
Use a TTL—an automatic expiry time—on location_state so the whole record disappears when it expires. A list of people in a cell holds many people, and most stores cannot expire one entry inside a list on its own. A practical way is to keep each cell's members in a sorted set where the score is the update time, then ignore members older than the freshness window when reading and trim them in the background. Store raw coordinates only as long as needed for freshness and ranking. For display, return rough distance buckets or coarse labels unless the product explicitly requires exact coordinates for a trusted tier.
Detailed design
We now know what is stored, so we can put the pieces in motion. Two journeys matter: a phone reports its location, and a viewer asks who is nearby. Both must check privacy. A paused person's update must not enter the index, and a leftover cell entry must not make someone appear. This section tells each journey as a story, then shows the API a client sees. The deeper questions come in the deep dive right after.
The write path: one location update
It starts on the phone. The phone only sends if the person opted in, and only after something meaningful happened: it moved far enough, a minimum amount of time passed, or the person opened the map. It includes how accurate the reading is. If the accuracy is poor, the phone waits or sends a rougher position, because a wildly wrong point is worse than a late one.
The request reaches the location ingress, which first works out who is calling. It then checks the person's sharing state. If sharing is off or paused, the request is rejected, or only a coarse allowed state is kept. It also rejects readings that make no sense, such as a jump across a continent in a few seconds, which usually means a fake position or a bad reading.
The ingress then rounds the position to the precision the product promised and works out the cell id for it. It writes the person's latest state, which holds the cell, the rounded position, a timestamp, and a version number, along with an expiry. The write only succeeds if the version is newer than what is stored, so a late, old update cannot overwrite a newer one. It adds the person to the new cell's member list and removes them from the old cell's list if they changed cells. If the two views disagree for a moment, the query path trusts the latest-state record and its timestamp, not a leftover list entry. Finally it sends a small event to a stream so the abuse pipeline can look at patterns, and that happens after the write, never in front of it.
A person walking through a festival can cross cells often. Movement thresholds, minimum intervals, and coalescing (keeping only the newest of several quick moves) keep battery and write volume under control.
- The phone decides to send, only if opted in.
- Ingress checks who the caller is and the sharing state.
- Reject impossible or very inaccurate readings.
- Round to the promised precision and compute the cell.
- Write the latest state with a newer-version check and an expiry.
- Move the person between cell lists if needed.
- Emit an event to the abuse stream after the write.
The read path: one map open
The viewer opens the map. The request passes the gateway, which checks who the viewer is and applies the rate limits from Decision 8. The query service first asks whether this viewer may use the feature at all.
At the same time it does two things in parallel. It loads the viewer's allowed friends, blocks, and privacy settings from the graph and privacy service, and it works out which cells cover the search circle around the viewer, including neighbours, because a friend ten metres away can be standing just across a cell border.
It reads the people in those cells, merges and removes duplicates, and keeps only the people who also appear in the allowed-friends set. Then it drops anyone who is paused, blocked, not visible to this viewer, or older than the freshness window. For the few who remain, it reads their latest-state record to confirm the timestamp and the version, because a list entry on its own might be a leftover. Only now does it compute exact distance, and only for those survivors. It turns each distance into a bucket and returns the list with a last-updated time. If the graph service is slow or the privacy state cannot be confirmed, the service hides the affected people and returns fewer results instead of guessing.
- Check the viewer, and the rate limits.
- In parallel: load friends, blocks and privacy, and compute the covering cells.
- Read candidates from those cells and merge them.
- Intersect with allowed friends, and drop paused, blocked, hidden and old entries.
- Confirm the latest-state record for each survivor.
- Compute exact distance for survivors only, and return buckets with last-updated.
- If anything is uncertain, hide it.
GET /v1/nearby/friends?radius_m=1000
→ Gateway: authenticate viewer, rate-limit
→ Query service: load allowed friends + blocks + privacy (in parallel with)
cover radius with cells (+ neighbours)
→ Read cell candidates → intersect with allowed friends
→ Drop stale / hidden / blocked → confirm latest state
→ Exact distance for survivors → coarse buckets + last_seen
API design: what the phone sends and what the map receives
Nearby friends has a small public API plus calls inside the system. Four things matter: the call the query service makes inside the system, what the client receives, the status codes, and the calls people use to control their own sharing.
The internal call. Inside the system, the query service exposes one function. Given the viewer, the centre of the search, a radius, and a limit, it returns the safe list.
NearbyQuery(viewer_id, center, radius_m, limit)
→ [ { friend_id, approx_distance_bucket, last_seen } ]
The calls from the client.
| Endpoint | Role |
|---|---|
POST /v1/location:update | Authenticated client sends location, accuracy, and movement details |
GET /v1/nearby/friends | Viewer asks for nearby friends inside a capped radius |
POST /v1/location:pause | Person pauses or resumes sharing |
PUT /v1/location/privacy | Person updates precision and audience settings |
GET /v1/location/audit | Optional access history for the person or for support |
A location update is naturally safe to repeat, because the latest version wins, so a retry after a lost response does no harm.
GET /v1/nearby/friends parameters
| Param | Role |
|---|---|
lat, lng | Viewer location, or omitted if the server uses the viewer's latest state |
radius_m | Search radius, capped by server policy |
limit | Maximum friends returned |
fresh_within_sec | Optional freshness preference, bounded by the product maximum |
What the client receives. Each result has a friend id, a distance bucket such as within_500m, and a last-seen time. There are no latitude or longitude fields by default.
{ "friend_id": "u42", "approx_distance_bucket": "within_500m", "last_seen": "2m ago" }
Which status code means what. A 403 means the viewer is not allowed to use the feature. A 400 means the radius is above the policy limit. A 429 means too many lookups or an abusive pattern, and it carries a Retry-After value so the client knows when to try again. A 200 with an empty list means no allowed, fresh friends are nearby, which is a normal answer and not an error. A 503 means the service is temporarily unable to answer safely, and the app should show “unavailable” instead of an old map. For location updates, a 204 means accepted, a 403 means sharing is off or paused, and a 429 means the phone is sending too often.
In the room: “A phone that opted in sends a small update only when something meaningful happened. Ingress checks sharing, rounds the position, computes the cell, and writes the latest state with a version and an expiry, then moves the person between cell lists. A map open reads the cells around the viewer, intersects with allowed friends, drops paused, blocked and old entries, confirms the latest record for each survivor, and returns rough distance buckets with last-updated. If anything is unclear, the person is hidden.”
Deep dive: the questions an interviewer asks next
You have drawn the design and walked a location update and a map open through it. This is where a good interviewer starts digging, and the questions usually come in a fairly predictable order, because each answer raises the next one. Read this section as that conversation. Each question is followed by an answer you can give, plus a hint of where the interviewer is likely to go next. If the next question is already clear from your answer, you can say it before they ask.
“Why not just keep one exact row per person and measure the distance to each friend?”
That is the obvious first design, and it is worth saying why it fails.
user_id -> exact_lat, exact_lng, updated_at
Query:
load all friends
compute distance to every friend
return exact points
It looks simple, but it fails on privacy, freshness, and scale. It stores precise positions too long, so a leak shows homes and routines. It makes large friend lists expensive on every map open, because nothing narrows the search by place. And it returns exact points even when the product only needs rough closeness. The better design keeps a short-lived, coarse record plus an index by cell.
Where it goes next: “What does that better record look like?”
“What does the short-lived record look like?”
Here is an example using an S2-style cell id. Treat s2:… as “bucket id”, not as a library you must memorise.
location_state:user_123 = {
cell_id: s2:89c25,
coarse_lat_lng: ...,
updated_at: T,
version: 41,
expires_at: T + freshness_window
}
cell:s2:89c25 = sorted/set(user_ids with updated_at/version)
The latest-state record lets the query service check freshness and privacy before it returns a result. The cell list lets it find nearby candidates cheaply. The expiry makes old data disappear even if a cleanup worker misses a move, so freshness does not depend on a perfect background job.

Figure: A geo cell only finds candidates. Privacy and freshness checks decide what can leave the API.
Where it goes next: “What happens when someone walks from one cell into the next?”
“What happens when a person moves from one cell to another?”
When a person moves from cell A to cell B, a naive system may leave them in both cells. That creates ghost dots, where someone appears in a place they have already left. A robust system writes a newer version to location_state, adds the person to B, and removes or expires them from A. When the query reads a cell, it compares each member's version or timestamp with the latest-state record. If the list entry is older than the record, the candidate is dropped.
To see why the version matters, imagine two quick updates: one that moves the person to B, and a slower earlier one that says A, which arrives late. Without a version check, the late message would pull the person back to A. With it, the write is refused because its version is older.
Where it goes next: “And if a friend is just across a border?”
“A friend ten metres away is standing in the next cell. How do you not miss them?”
You do not search only the viewer's own cell. You work out every cell that the search circle touches and read all of them. With S2 there is a helper that returns the set of cells covering a circle. With geohash you read the viewer's cell plus its eight neighbours. The cost is a few extra reads, which is small compared with missing a friend who is standing in plain sight.
The edge of the circle itself does not need to be exact. After reading the cells, the query computes true distance for the survivors and cuts anyone outside the radius, which matches the “small error at the edge is fine” agreement from the requirements.
Where it goes next: the interviewer will probably move to people who should not be shown.
“A person paused sharing, but their old record is still in a cell. How do you make sure they never show up?”
The key is that the cell list never grants permission. When someone pauses or blocks, the system removes them from the index quickly, which is the fast path. But the query does not rely on that having happened. It re-checks each candidate against the current privacy state, which holds the sharing flag, the pause flag, blocks in both directions, and the audience setting, before returning anyone.
Caches make this harder. The friend and privacy data are cached for speed, so a pause or a block can be missed if the cache is old. The answer is a short cache life, clearing the cache on pause, block, and unfriend, and a version number on the privacy state, so the query can tell when what it holds is out of date. When the state cannot be confirmed, the person is hidden. Showing nobody is better than showing someone who should be hidden.
Where it goes next: “What happens at a stadium?”
“What happens when 50,000 people stand in one cell?”
The cell list for that cell holds tens of thousands of ids, and every viewer in the crowd reads it. The algorithm is correct and still very slow at that venue, because the work grows with the size of the crowd, not with the number of friends.
The fix has three parts. Split crowded cells into finer sub-cells so a lookup reads a small piece of the crowd. Cap how many candidates one lookup may read, so one open cannot take unbounded time. And when the crowd list is bigger than the friend list, flip the order and look up the viewer's few hundred friends directly, which reads far fewer records than the crowd. If the cap is reached, the product shows a gentle message like “many friends in this area” instead of a ranked list. Alert on the number of candidates per cell, because overall traffic can look normal while one venue is slow.
Where it goes next: “And what about someone watching another person on purpose?”
“An allowed friend checks the same person every minute. What stops that?”
Every one of those requests passes the permission check, so the pattern is invisible to a per-request check. The system has to look at the pattern itself. The API limits the radius and the rate of lookups, so nobody can scan the map block by block. A background job watches viewer and target pairs: one viewer asking about the same target again and again, across many places, with no normal interaction between the two, is a warning sign. When the risk looks high, the system lowers the precision, notifies the target, or blocks the viewer. Sensitive lookups are written to an audit record, and internal support tools need a reason code and leave the same kind of record.
Say it in the interview: “A cell index finds candidates; it does not grant permission. Freshness, blocks, opt-in, and rough display still decide what leaves the API.”
Hot cells and block handling are covered again in Key challenges. What you measure belongs in Observability and Bottlenecks and tradeoffs.
If you remember one thing: The deep dive is a conversation. One exact row forever is the red flag, a short-lived versioned cell record is the fix, and permission is checked on every lookup.
Key challenges
The deep dive showed that the core idea is simple once the record is short-lived and the index is by cell. What makes the real system hard is everything around it. Six hard parts appear again and again, and each is a place the interviewer is likely to push, so name them early.
| Challenge | What users see if it goes wrong | What to say in the interview |
|---|---|---|
| Battery drain | The phone gets hot and people switch the feature off | Update on movement or after a minimum time; use the phone's significant-change support |
| Stale dots | A friend is shown nearby after leaving | Give each location an expiry, show last-seen, hide old entries, and check versions so leftover cell rows do not win |
| Hot cells | The map is slow at concerts | Split crowded cells into finer ones, cap how many candidates you read, flip to friends-first when the crowd is huge, and return a rough result instead of scanning everyone |
| Privacy leaks | An exact home or commute is exposed | Return rough distance buckets, require opt-in and pause, keep raw location only briefly, and keep an audit trail |
| Block churn | A blocked person still sees someone's location | Enforce blocks on the lookup path itself and clear the friend or privacy cache when someone blocks |
| Fake GPS or impossible jumps | A user appears to teleport across continents | Check accuracy, reject impossible jumps, and trust suspicious updates less |
The system should fail toward less precision. Showing no nearby result is usually safer than showing a stale or unauthorized dot.
If you remember one thing: Stale dots and block churn are design requirements, not production surprises.
Scaling the system
Those hard parts get worse as the number of people grows, so the next question is what happens when traffic multiplies. You do not have to wait for the interviewer to ask. Right after you finish the design, say the scaling story yourself, then be ready for the follow-ups.
What you can say upfront: “Most people look near where they are standing, so I would store and search location near that place and not in one global pile. I would split the cell-to-people data by region or by a prefix of the cell id, so writes land where the people are and a lookup touches one or two regions. Dense cities still need splitting, because one concert can overload a single cell, so crowded cells are split into smaller ones and capped. I would cache the friend sets for a short time, clear them when someone blocks or pauses, and treat privacy data as the one place where a stale read is a safety bug. Update spikes are absorbed by throttling on the phone, a limit on the server, and batching the newest update per person.”
That one paragraph answers most of what follows. Here are the follow-ups, in the order they usually come.
Interviewer: “Traffic doubles, or the user count grows ten times. What do you change?”
You: “The services that handle updates and map opens keep no important state, so I add more of them. The data is the part that needs splitting. I split the location index by region, so each region holds the people who are physically there, and I add machines in the regions that grow. I check memory and the busiest cells first, then the graph service, because the friend lookups are the next thing to grow.”
Interviewer: “How exactly do you split the data? By user id?”
You: “Not for the cell lists. If I split by user id, the people in one neighbourhood would be spread over every machine, and a map open would have to ask all of them. I split the cell-to-people data by place, using a prefix of the cell id or a region, so one map open touches only one or two machines. The user-to-location record is looked up by user id, so it can be split by user id. These are two different lookups with two different keys.”
Interviewer: “What if a viewer is standing near the border between two regions?”
You: “The search circle may touch cells that live in two regions, so the query reads from both and merges the results. That is only a few extra reads for people near a border, and it is better than copying every person into several regions. I would never send a query to every region, because global friend tracking is not part of this product.”
Interviewer: “A festival starts and updates spike in one area. What happens?”
You: “The phone's own throttling limits how much each phone sends, and the server adds a limit per device for bad app releases. At the busy region I coalesce updates, keeping only the newest one per person in a short window, since an older one is already out of date. The crowded cells are split into smaller sub-cells so no one list takes all the traffic.”
Interviewer: “Can we read the friend and privacy data from replicas to spread the load?”
You: “For friend lists a short delay is fine. For blocks, pauses, and privacy settings I am strict, because a replica that lags behind could show someone who just blocked the viewer. I either read these from the primary, or keep a small version number that tells the query when its copy is old, and hide the person when it is unsure.”
If you remember one thing: Split location by place, not by user. Crowded cells need extra splitting, and privacy data is the one thing that cannot be stale.
Failure handling
Scaling answers “what if there is more traffic”. This section answers “what if something breaks”. Again, say it first. In this product, returning an unauthorized exact location is worse than returning an empty list, so what impresses an interviewer is that the answer was decided before the failure happened.
What you can say upfront: “Every failure has a decision made in advance, and the rule is to fail toward showing less. If the graph or privacy service is slow, I hide the people I cannot confirm and return fewer results, not guess. If the location index lags, old dots are hidden by the expiry and the version check, and the app shows ‘last seen’ so people can judge. If a pause or a block arrives late, I clear the cache and hide the person when the state is unclear. If the whole region is down, I show ‘unavailable’ or an old, clearly labelled result, and I never make up a precise position.”
The follow-ups are about the details of those decisions.
Interviewer: “The graph service times out in the middle of a map open. What does the user see?”
You: “The query service cannot confirm who is allowed, so it does not guess. It returns an empty or reduced list, or a short ‘unavailable’ message, and the map still loads. A circuit breaker—a switch that stops calling a dependency that keeps failing—lets the service answer straight away instead of waiting on a dead graph service. Users see a quieter map, which is degraded service. An outage is the app showing an unauthorized dot, and I avoid that above everything.”
Interviewer: “The location index falls behind. Who gets hurt?”
You: “People who just moved are missing or in their old place for a short time. The expiry removes old records anyway, and the version check drops list entries that are older than the person's latest record, so ghosts are limited. The app labels each friend with how long ago the location was updated, so a slightly old dot is clearly marked.”
Interviewer: “Someone pauses, but a friend still sees them for several minutes. What went wrong?”
You: “The pause updated the privacy state, but a cached copy was still being used and a list entry was still in the cell. I clear the cache on pause and block, keep a version number on the privacy state, and have the query hide anyone whose state it cannot confirm. I treat the time from pause to hidden as a safety measure, with an alert if it is slow.”
Interviewer: “A phone reports a very inaccurate or impossible position. What do you do?”
You: “I look at the accuracy value and at how fast the person would have had to travel. A jump across a continent in a few seconds is rejected or given low trust. Poor accuracy is replaced by a rougher position, or the update is delayed, because a dot in the wrong place is worse than a late one.”
Interviewer: “A single venue overloads the lookup. What do you do at that moment?”
You: “I cap how many candidates one lookup may read, flip to looking up the viewer's friends directly when the crowd is bigger, and return a message like ‘many friends in this area’. I also return 429 to clients that scan the same area over and over, so the abusive traffic does not use up the capacity.”
| Scenario | What the user sees | What to build |
|---|---|---|
| Location index lag | Nearby list misses recent movers | Use expiry times, version checks, and “last updated” labels |
| Graph service slow | Query times out or returns too much | Cache allowed friends; when privacy is unclear, hide the person instead of guessing |
| Bad GPS accuracy | Dot jumps or appears in the wrong place | Accuracy limit, outlier checks, rougher fallback |
| Privacy update delayed | Paused user still visible | Clear the privacy cache; hide when state is uncertain |
| Hot cell overload | Slow map at an event | Finer sub-cells, candidate caps, 429 for abusive scans |
| Regional outage | Empty or stale results | Show “unavailable” or an old, labelled result; do not invent a position |
If you remember one thing: When privacy state is unknown, hide. Fail toward showing less, never toward showing more.
Observability (what you measure)
Once the system is live, you need a way to tell whether it is healthy, and in this product that means two kinds of health. Measure both how the system performs and whether it keeps its privacy promises. A fast query that leaks stale locations is not healthy.
| Signal | Why it matters |
|---|---|
| Location update rate by app version | Catches battery-draining releases |
| Index lag and stale candidate drop rate | Shows whether moving people leave ghost entries |
| Query p95/p99 by cell density (the time the slowest 5 in 100 and 1 in 100 lookups take) | Finds hot venues and overloaded cell lists |
| Candidate count before and after friend filtering | Confirms the map search and graph filtering are working |
| Block or pause propagation time | Measures a safety-critical clean-up |
| Repeated lookups per viewer and target pair | Detects stalking-like access patterns |
| Response precision distribution | Verifies rough display rules are actually applied |
Alert on hot cells, query p99, update storms, and any privacy clean-up delay that exceeds the product bar. For this feature, a spike in audit records can be as important as a spike in errors.
Security and abuse
A location feature is also a safety tool, and people will try to misuse it, so this section covers how to keep it honest. Nearby friends should be opt-in, authenticated, and permission-checked on every path. The server should enforce blocks, pause, hidden mode, and audience tiers, because the app screen alone is not enough. Return rough distance buckets by default and avoid raw coordinates unless a trusted mode explicitly allows them.
For repeated nearby scans, reuse the patterns from the rate limiter guide and rate limiting fundamentals.
Limit the query radius and the query rate so someone cannot scan a grid block by block. Detect repeated access against one target, especially when the viewer and target rarely interact. Keep audit trails for sensitive internal tools and for product surfaces where policy requires it.
Retain raw location for as little time as the product needs. If analytics wants movement trends, combine or anonymize the data outside the hot path. Treat exact location, home and work guesses, and friend-graph overlaps as sensitive data. A breach of location history can be more damaging than a leak of many ordinary profile fields.
Cost awareness
Every choice so far also has a price, and interviewers like to hear that you noticed. Every location update costs phone battery, radio wake-ups, backend writes, and rewriting the map-cell indexes as people move, so reducing how often phones report is both a cost win and a trust win. Hot cells cost more than average cities because one list can dominate query time.
Returning exact coordinates may look cheap technically, but it creates privacy and compliance cost. Rough display, short expiry windows, and short retention reduce long-term storage and audit burden. Caching friend sets saves graph traffic, but stale privacy caches can create expensive safety incidents, so clearing them on change is worth paying for.
Push notifications for “friend nearby” are expensive in user attention. They should be capped and deduplicated. The default lookup-on-open model is often cheaper and less creepy.
Green Dashboard. Angry Users. The Production Mindset System Design Interviews Expect.
Everything so far describes how nearby friends should work on a good day. This section is about what happens on a bad day, told as short stories from the people who carry the pager (the on-call engineers). Location incidents rarely announce themselves as “the map index failed.” They show up as battery complaints, safety reports, ghost dots, and one venue making a whole region slow.
A calm dashboard can mean “all is well” or “every privacy check is being skipped.” A healthy request rate can mean “people are happy” or “one person is being followed.” Interviewers like this gap because it separates a diagram from someone who has run the thing.
Four nightmares that look fine on a dashboard:
| What the dashboard shows | What is actually happening |
|---|---|
| Overall traffic is normal and the error rate is flat | One venue's cell list is huge and every lookup there is slow |
| Every request returns 200 | A paused person is still visible because a cached copy is old |
| Writes are all succeeding | A new app release sends an update on every GPS reading and drains batteries |
| Latency and errors are green | One friend is looking up the same person every minute |
Scene 1: Festival hot cell melts the query path
The moment: A large music festival is running in one city, with about sixty thousand people in a single field, and many of them open the app to find their group. Map lookups in that city jump from 200 milliseconds to several seconds. Global traffic is normal, and only one city looks bad.
The trap: The cell size was chosen for a normal city and is too coarse for this crowd. One cell's list holds a huge share of the active people. Every viewer opens the map, reads the same large list, and then keeps only their friends. The algorithm is correct on average and terrible at the venue.
What to build: Split hot cells into finer sub-cells, cap candidate reads, and look up the friends directly when the crowd list is bigger. Return a deterministic top result with a clear “more friends nearby” message. Alert on candidate count per cell, not only global traffic.
stadium crowd
→ one cell list grows
→ candidate read p99 rises
→ every nearby lookup slows
→ split sub-cells / cap candidates
Scene 2: Pause sharing does not hide fast enough
The moment: A person leaves a gathering and pauses sharing so nobody can see where they go next. A friend who is still at the gathering keeps seeing them nearby for several minutes. Support treats it as a privacy incident.
The trap: The app updated the privacy state, but the query service used a cached friend and visibility record. The old cell entry still existed, and the query did not re-check the latest privacy state before returning the person.
What to build: Clear the privacy cache on pause and block, keep a version on the privacy state, and have the query service prefer “hide” when it cannot confirm the state. Measure the time from pause to hidden as a safety target.
Scene 3: Battery drain after a mobile release
The moment: A new version of the app goes out. A few days later, app-store reviews start mentioning battery drain, and backend location writes double for one app version. Map lookups did not change.
The trap: The client started sending an update on every GPS callback instead of on movement or a minimum interval. Backend writes succeed, so the availability dashboards stay green while users uninstall the feature.
What to build: Server-side limits per device and app version, a 429 with Retry-After for noisy clients, a kill switch for bad versions, and update-rate dashboards split by app build.
Scene 4: Stalking pattern hides inside normal 200s
The moment: A user contacts support because someone seems to know where they are. The API logs show only successful nearby lookups, all from a friend's account.
The trap: The system authorized each lookup one by one but never looked at the pattern: one viewer asking about the same target every minute, in many places, with no normal interaction between them. Availability and latency were green.
What to build: Limit repeated viewer-and-target lookups, lower precision when the risk rises, audit sensitive patterns, and make blocks take effect immediately. Internal support tools should need reason codes and leave audit rows.
In the interview: Pick one scene and tell it like a short story: what people felt, which metric lied, and what you would build next. Hot cells need adaptive indexing. Pause needs privacy cache clearing. Battery needs phone and server limits. Stalking needs pattern detection, not just a login check. You do not need all four.
Bottlenecks and tradeoffs
Those stories all trace back to a small number of choices where you cannot have both things you want. Interviewers listen for whether you can name the tension, say what breaks, and pick a side on purpose. Here are the four that matter most for nearby friends.
Precision vs privacy
The tension — Finer cells and exact coordinates make the map feel better, but they reveal routines.
What breaks — A leak or a misuse shows where someone lives or works.
What teams do — Rough distance buckets and short expiry windows, with more precision only as an explicit choice for close friends.
Say in the interview — State the display precision and the retention window together, because they are one product promise.
Freshness vs battery
The tension — Fresh dots need frequent updates, and frequent updates wake the GPS chip and radio.
What breaks — Battery drain makes people switch the feature off, and backend writes climb.
What teams do — Update on movement or after a minimum time, and show last_seen when freshness is uncertain.
Say in the interview — “I’d rather show an honestly labelled two-minute-old dot than burn the battery for a one-second-old one.”
Cell candidates vs friend graph cost
The tension — Searching by place cuts the world down to nearby people, and filtering by friends cuts those down to allowed people. The best order depends on friend count and crowd size.
What breaks — Cells first is slow in a crowd, and friends first is slow for someone with thousands of friends.
What teams do — Cells first by default, flip to friends first when the crowd list is bigger, and never degrade into scanning all users.
Say in the interview — Give the expected friend count and crowd size, and pick the cheaper side.
Pull vs push
The tension — Pull on open is calmer and cheaper, while a push such as “friend nearby” is engaging but noisy and easier to abuse.
What breaks — Push can flood people at big events and feel like being watched.
What teams do — Default to pull; if push exists, make it opt-in, capped, deduplicated, and quiet-hours aware.
Say in the interview — “Pull by default; push only with caps and user control.”
If you remember one thing: Say the display precision and the retention window together, and pick the cheaper side of the friend and cell lookup on purpose.
Interview tips
You now have a full design and the tradeoffs behind it, so the last thing to practice is defending it when the interviewer pushes back. These five are the pushes that come up most after you finish the design.
Raw GPS table is not a nearby system
In the room
You might say: “Store each person's latitude and longitude, then measure the distance to each friend.”
Interview Push: “Do you scan every user in a city, and do you keep exact coordinates forever?”
Land here: Keep one short-lived location record per person and file them under a small map cell, not a forever table of exact GPS points. When someone opens the map, read only the cells that cover the search radius, keep the people who are also allowed friends, and measure exact distance only for that small leftover set. Return rough distance buckets by default, keep raw exact location only briefly, and let the automatic expiry remove old rows so a friend who already left does not stay on the map.
Friendship does not replace permission
In the room
You might say: “If two people are friends, they can see each other nearby.”
Interview Push: “What if one paused sharing, blocked the other person, or only shares with close friends?”
Land here: Being friends is only one input, not a free pass to appear on the map. On every lookup the server must still check that sharing is on, that neither person paused or blocked the other, that the audience setting allows this viewer, and that the location is still fresh. Cached friend or privacy data needs clearing when someone blocks, pauses, or unfriends. If any of that state is unclear, hide the person instead of returning an old dot.
Every GPS tick is too expensive
In the room
You might say: “The phone sends its location every second so the map stays fresh.”
Interview Push: “What happens to battery and update traffic at tens of millions of users?”
Land here: The phone should wake for a real move, a minimum wait, or the person opening the map—not for every GPS reading. The product can still feel fresh within a few minutes without streaming a constant location feed, and that choice saves battery and write load. The server also needs its own per-device limit, because a bad app release can ignore the phone’s rules and flood the backend.
A stadium cell breaks average-case thinking
In the room
You might say: “The lists of people in a cell are small, so the lookup is fast.”
Interview Push: “What about a concert where thousands of people fall into the same cell?”
Land here: Watch how many people sit in each cell, because average traffic can look fine while one venue is broken. Split crowded cells into finer ones, cap how many candidates one lookup may read, and look up the viewer’s friends directly when the crowd list is bigger than the friend list. If the cap is hit, return a gentle “many friends nearby” result instead of scanning the whole crowd.
Abuse is not only unauthenticated traffic
In the room
You might say: “Only friends can look people up, so stalking is solved.”
Interview Push: “What if an allowed friend looks up the same person every minute?”
Land here: Permission is necessary but not enough, because every one of those requests can look valid on its own. Cap the search radius and the lookup rate, watch viewer-and-target pairs for repeated checks, keep audit records, lower precision when risk rises, and make blocks take effect immediately. The design has to notice the pattern of following someone, not only whether a single request was allowed.
Red flags to avoid without correcting yourself: “Store exact GPS forever,” “query all users,” “friend means always visible,” “push everyone nearby by default,” “blocks are handled only in the app.”
After each push, close with one real part of the design you would build, such as a short-lived record with an expiry, a privacy re-check on every lookup, or a cap on candidates per cell, not “we will scale it later.”
What should stick
After working through the requirements, the decisions and the depth sections, you should be able to explain:
- Map cells find candidates — cutting the map into small areas means you only look nearby, and that filter does not decide permission. Library names like geohash, S2, and H3 are optional.
- Privacy is on the hot path — opt-in, pause, block, audience tier, and freshness are checked before returning anyone, and unknown means hidden.
- Freshness has a cost — update on movement or interval, not on every GPS reading, and show
last_seen. - Moving people need versions and an expiry — old cell entries must expire or be ignored, with the freshness window hiding a person after about 10 to 15 minutes.
- Crowded venues and abuse are production realities — stadiums need split cells and caps, and repeated lookups of one person need pattern detection.
Tell it in the room: “A phone sends location sparingly after opt-in. The server writes a short-lived, coarse record plus a timestamp and files it under a map cell. A lookup reads the cells around the viewer, keeps only allowed friends, drops old or hidden people, and returns a rough distance plus last-seen, never exact GPS by default.”
Key Takeaways
- Nearby friends only shows friends who agreed to be seen, so permission, pause, blocks, and freshness are checked on every lookup, not only when data is written.
- Store one short-lived, coarse record per person with a timestamp and an expiry of about 10 to 15 minutes, and not a history of exact positions.
- Cut the map into cells so a lookup reads only the few cells around the viewer, then keep friends and compute exact distance only for the survivors.
- Do not send every GPS reading: report on movement, after a minimum time, or when the map opens, and limit each device on the server.
- Crowded places break average-case thinking, so split crowded cells, cap candidates, and look up friends directly when the crowd is bigger than the friend list.
- When the privacy state is unclear, hide the person; fail toward showing less.
- Return rough distance buckets and last-seen, and watch repeated lookups of one person to catch stalking.
Related Topics
- System design interview guides - Hub for this walkthrough
- Rate Limiter System Design - Abuse/QPS controls for repeated nearby scans
- Distributed Cache System Design - Expiry, hot keys, short-lived location state
- Facebook Feed System Design - Friend graph + privacy filtering contrast
- Notification Service System Design - Why push “friend nearby” needs caps
- Rate limiting and throttling - Fundamentals for query/update throttles
- Redis caching - Friend-set / hot-cell caching patterns
- Authentication and authorization - Opt-in, blocks, and permission on the hot path
- Practice: Nearby Friends - Interactive board + AI feedback
Quick revision notes
The problem in your own words. Nearby friends shows a person which of their friends are close right now, using only friends who agreed to be seen and whose location is still fresh. The hard part is that privacy and freshness must hold on every lookup, while tens of millions of phones send changing locations.
The design in one breath. A phone that opted in sends a small report when it has moved far enough, waited long enough, or opened the map. The server keeps one coarse latest location per person with an expiry and files them under a map cell. A lookup reads the cells around the viewer, keeps only allowed friends, re-checks permission and freshness, hides anyone it is unsure about, and returns a rough distance with a last-updated time.
The choices you must be able to defend. Keep one short-lived, coarse location instead of an exact history. Search nearby map cells first, then keep friends. Re-check privacy on every lookup, and hide anyone whose state you cannot confirm. Return rough distance buckets instead of exact positions. Split and cap cells when a crowd packs one place. Say which errors are cheap (a little distance error) and which never are (showing someone who should be hidden).
The numbers worth remembering. About 10 million writes a second if phones reported every 5 seconds, against about 400,000 with throttling, as estimates. About 2.4 million friend lookups a second if you checked every friend on every open. About 250 million list entries a minute if 5,000 people open the map at a 50,000-person venue.
The mistakes that cost points. Storing exact GPS forever, scanning all users, treating friendship as permission, sending every GPS reading, ignoring crowded cells, handling blocks only in the app, and forgetting that an allowed friend can still be a stalker.
Frequently asked follow-ups
- How often should mobile clients send location updates?
- How do geohash or S2 cells help with nearby search?
- Do you query all users, all friends, or nearby cell candidates first?
- How do pause, block, and opt-out work?
- How do you prevent stalking or exact home-location leaks?
Deep-dive questions and strong answer outlines
Walk through one location update.
The client sends an update only when the user opted in and either moved far enough, crossed a cell boundary, or a minimum interval passed. The server verifies auth and privacy state, snaps or stores the location at the approved precision, updates user->cell and cell->users indexes with a timestamp, and sets an expiry time so stale rows disappear.
How does nearby query work?
The query service loads the viewer's allowed friend set and privacy state, computes the cells covering the radius, fetches candidate user ids from those cells, intersects with friends and visibility rules, drops stale rows and blocked users, then computes exact distance for the small survivor set. The response returns coarse distance buckets and last_seen, not exact raw GPS by default.
How do you handle moving users?
Each update removes the user from the old cell and adds them to the new cell, or writes a new version that readers can compare. The record has updated_at and an expiry. If cell index and user location briefly disagree, queries prefer recent user location and hide stale entries rather than showing false precision.
How do you protect against stalking?
Require opt-in, mutual visibility, blocks, coarse distance display, rate limits, audit records for sensitive queries, and anomaly detection on repeated queries against one target. Avoid exact coordinates in default responses and expire raw location quickly.
What happens at a stadium?
One map cell can contain many users, so the list of people filed under that cell becomes huge. Use finer subcells or adaptive S2 levels, cap candidate scans, rank deterministically, cache close-friend sets when appropriate, and degrade to "many friends in this area" rather than scanning a city-sized list on every request.
AI feedback on your design
After a practice session, InterviewCrafted summarizes strengths, gaps, and interviewer-style expectations—similar to a written debrief. See a static example report, then practice this problem to get feedback on your own answer.
FAQs
Q: Should the app keep GPS on all the time?
A: No. A practical design updates on movement, cell changes, significant-change APIs, or a minimum interval. Always-on GPS drains battery and creates more privacy risk than most nearby-friends products need.
Q: Is this the same as global map search?
A: No. Nearby friends is friend-filtered and permission-filtered. You are not searching every person in the world. You use cells to find local candidates, then intersect with the social graph and visibility rules.
Q: Why use coarse distance buckets?
A: Exact meters can expose homes, workplaces, and routines. Buckets like "within 500 m" or "near Central Park" often give enough product value while reducing tracking risk. The product may allow more precision for close friends, but it should be an explicit choice.
Q: What does TTL mean for location?
A: TTL is the freshness window after which a location is hidden or marked stale. If a user has not updated for, say, 10 or 15 minutes, the system should not confidently show them nearby. A stale dot can be more harmful than no dot.
Q: How do blocks work?
A: Blocks must be enforced on the query path, not only on the UI. If user A blocks user B, B should not receive A in nearby results even if A's location row still exists in a cell index. Cache friend sets carefully and invalidate on block.
Q: How do you design nearby friends in a system design interview?
A: Opt-in location with a short freshness window; index by geo cells; on query cover the radius with cells, intersect allowed friends and blocks, drop stale rows, refine distance only for survivors; return coarse buckets plus last_seen.
Q: How do you prevent stalking in a nearby friends design?
A: Opt-in and mutual visibility, blocks on the query path, coarse display, radius and QPS limits, viewer–target anomaly detection, short retention, and hide the person when privacy state is unclear instead of guessing.
Q: What happens at a stadium or concert?
A: One coarse cell can explode. Use finer subcells, cap scans, deterministic ranking, and degrade to "many friends nearby" instead of full posting-list scans.
Practice interactively
Open the practice session to use the canvas and stages, then review AI feedback.