Design a Social Graph
Design the friendship system for a social network with half a billion users. People send friend requests, accept or decline them, unfriend and block. Profiles show a friend list and how many friends you have in common with the person you are looking at, and a People You May Know panel suggests new connections.
Most users have a few hundred friends, but some have thousands, and a few accounts are connected to a huge share of the network. Friend lists are read constantly by other services (feeds, privacy checks, messaging), so the graph sits on the critical path of almost every request. Suggestions involve looking two hops away from every user, which explodes quickly.
In 45 minutes, design how the graph is stored and served, how mutual friends are computed, and how suggestions are generated, ranked and kept fresh.
Sketch on the HLD board, write your answer in the Design doc, and size it with the Estimator. Start the mock interview from the timer for a 45-minute run.
Design Path · Social & Messaging · problem 16 of 70
Ask before you design. Try answering each yourself, then compare.
- Are relationships mutual or one-way?
Typical answer
Mutual friendships created by request and accept. One-way follows exist elsewhere and are out of scope.
- What scale?
Typical answer
500 million users, 300 million daily. Average of about 300 friends, capped at 5,000 per user.
- Who reads the graph?
Typical answer
Mostly other internal services: feed, privacy checks, messaging, search. Expect more than 100,000 reads per second.
- How fresh must suggestions be?
Typical answer
A daily refresh is fine, but right after someone adds a friend the suggestions should react within minutes, and an accepted or dismissed suggestion must never reappear.
- What signals can suggestions use besides mutual friends?
Typical answer
Shared school or workplace, uploaded contacts (with consent), and rough location. Assume a ranking model exists; we design the pipeline around it.
- How should blocking behave?
Typical answer
A block removes any friendship, hides each user from the other everywhere, and must take effect immediately.
Requirements
Functional
- Send, accept, decline and cancel friend requests; unfriend; block.
- Read a user's friend list (paginated) and check whether two users are friends.
- Show mutual friends (count and a few names) between the viewer and another user.
- Show People You May Know: ranked suggestions that exclude friends, pending requests, blocked and dismissed users.
Non-functional
- Friend-check and friend-list reads p99 under 10 ms from cache; 99.99% availability for reads.
- Mutual-friend count p99 under 50 ms; suggestions panel p99 under 150 ms.
- Graph changes visible to all readers within 1 s; blocks take effect immediately.
- Scale to 75 B friendships and 150 K graph reads/s at peak.
Out of scope
- Follower or subscription graphs.
- Training the suggestion ranking model.
- Contact upload and import flows (assume a contacts signal is available).
Back-of-the-envelope estimates
- Graph size: 500 M users × 300 friends ÷ 2 ≈ 75 B friendships. Stored in both directions that is 150 B adjacency entries at ~16 bytes (friend id plus timestamp) ≈ 2.4 TB raw, ~5 TB with index overhead and about 15 TB with 3 replicas.
- Writes: 300 M × 0.2 graph changes/day ≈ 60 M/day ≈ 700/s, peaking around 2,000/s. Each change writes two rows.
- Reads: roughly 200 reads per write ≈ 12 B/day ≈ 140,000/s on average, and much more as point checks inside other services. Caching the active users' lists (20% hot) means ~1 TB of cache.
- Friends of friends: 300 × 300 = 90,000 two-hop paths per user. Doing that for 300 M active users is about 27 trillion path visits per refresh, which rules out computing suggestions on request and forces offline batch work with caps on high-degree users.
Read volume on the adjacency lists and the two-hop explosion for suggestions drive the design; raw storage is small.
API
POST /v1/friend-requests {toUserId} -> 201 {requestId}
POST /v1/friend-requests/{id}/accept -> 204
DELETE /v1/friends/{userId} -> 204
POST /v1/blocks {userId} -> 204
GET /v1/users/{id}/friends?cursor=&limit=100 -> {friends[], nextCursor}
GET /v1/users/{id}/mutual?with={otherId}&sample=3 -> {count, sample[]}
GET /v1/suggestions?limit=20 -> {people:[{userId, mutualCount, reason}]}
POST /v1/suggestions/{userId}/dismiss -> 204
internal RPC: AreFriends(a, b) -> bool; GetFriends(user) -> ids[]Internal services use a batched AreFriends RPC answered from the cache, because privacy checks need hundreds of point lookups per page and a per-call network hop would dominate latency.
Data model
adjacency(user_id, friend_id, created_at, state) in a sharded key-value or wide-column store, partitioned by user_id and clustered by friend_id. Every friendship is written as two rows, one in each user's partition, so friend lists and friend checks never cross shards. state covers friend, request sent, request received and blocked.
The two rows live on different shards, so they are written through an outbox: the request is recorded once, and an idempotent worker applies both sides, retrying until they agree. A periodic repair job compares the two directions.
candidates(user_id, candidate_id, score, mutual_count, reason, generated_at) in a key-value store, the top ~200 per user. dismissed(user_id, candidate_id) is a small set that is never expired. A daily graph snapshot in the data lake (columnar files) feeds the batch job.
High-level design
Changing the graph. A friend request, accept, unfriend or block reaches the Graph Service through the API gateway. The service writes both adjacency rows in the Adjacency Store (one per user partition, made reliable with an outbox and idempotent retries), invalidates both users' entries in the Adjacency Cache, and publishes a graph changed event to the Graph Events stream. Blocks are checked synchronously on every write and read so they take effect at once.
Reading the graph. Friend lists and friend checks are served from the Adjacency Cache, which holds sorted id lists for active users and falls back to the store on a miss. Mutual friends are computed in the Graph Service by intersecting the two cached lists, smallest into largest, which takes well under a millisecond for a few hundred ids each.
Suggestions. Each night a Batch Friend-of-Friend job reads the Graph Snapshot, counts weighted two-hop paths per user with caps on very high-degree users, joins other signals, and writes the top candidates to the Candidate Store. During the day an Incremental Updater consumes graph events: when A and B become friends, it adds B's friends as candidates for A and vice versa, and removes the new friend from both candidate lists. When the panel loads, the PYMK Service reads candidates, filters out current friends, pending requests, blocks and dismissals using the cache, and asks the Ranking Model to order the final 20.
Open the HLD board and press Reference to see the architecture diagram.
Deep dives
Storing the graph: adjacency lists, not a graph database
Nearly every query here is one hop (friends of X, is X a friend of Y) or two hops from a single user. A sharded key-value store with one partition per user answers one-hop queries with a single read and scales horizontally with no cross-shard joins. Writing each edge twice doubles storage but keeps reads local, which is the right trade at 200 reads per write. A general graph database helps with arbitrary traversals, but those are rare and run offline here. Shard by user id hash with many virtual shards so heavy users can be moved, and cap lists at 5,000 so no partition grows without bound.
Mutual friends at request time
Mutual friends between a viewer and a profile is an intersection of two lists of at most 5,000 ids. With both lists sorted and cached, a merge-style intersection or probing the smaller list into a hash set of the larger costs microseconds. Do it inside the Graph Service next to the cache rather than shipping lists to callers. Counts shown on many profile cards at once (for example in search results) are batched per request. For pairs viewed often, cache the count for a few minutes; a slightly stale mutual count is harmless, but a mutual list that includes someone who blocked the viewer is not, so always apply block filtering after the cache.
Generating suggestions without exploding
The batch job processes the snapshot in a distributed engine: for each user, emit every pair of their friends as a candidate path, then group by pair and sum weights. Each path is weighted by one over the log of the middle person's degree, because sharing a friend who knows 5,000 people says little, and very high-degree users contribute only a sampled subset of pairs, which bounds the quadratic blow-up. Join the result with other signals (same school, contacts, location), keep the top 200 per user, and write them out. Only active users need refreshed candidates. Because the batch runs once a day, the incremental updater handles the moments that matter most, right after someone adds a friend, when they are most likely to add more.
Consistency and privacy
A friendship spans two partitions, so the two rows can briefly disagree. Treat the request record as the source of truth, apply both sides idempotently from an outbox, and run a repair job that fixes one-sided edges. Readers that need certainty, such as privacy checks, can read both directions or the request record. Blocks are stored as their own state and checked on every read path, including cached lists, mutual-friend samples and suggestions, so a stale cache never shows a blocked person.
Failure modes
- If the Adjacency Cache fails, reads fall back to the store, which must be sized to absorb a large fraction of traffic; request coalescing stops a stampede on popular users.
- If only one side of a friendship write succeeds, the outbox worker retries until both sides match, and the repair job catches anything left over.
- If the nightly batch job fails, the PYMK Service keeps serving yesterday's candidates plus incremental updates; filtering at read time keeps them safe.
- If the Ranking Model is slow or down, return candidates ordered by their precomputed score so the panel still renders.
Core algorithm in code
import math
from collections import defaultdict
def mutual_friends(graph, a, b):
"""Friends that a and b have in common (intersect the smaller list into the larger)."""
fa, fb = graph.get(a, set()), graph.get(b, set())
small, large = (fa, fb) if len(fa) <= len(fb) else (fb, fa)
return {f for f in small if f in large}
def suggest(graph, user, blocked=frozenset(), dismissed=frozenset(), k=3, max_fanout=1000):
"""People you may know: rank friends-of-friends who are not already friends.
A shared friend with a huge friend list says less than one with a small list,
so weight each path by 1 / log(degree of the friend in the middle).
Return [(candidate, score, mutual_count)] best first."""
friends = graph.get(user, set())
score, mutual = defaultdict(float), defaultdict(int)
for f in friends:
their = graph.get(f, set())
weight = 1.0 / math.log(len(their) + 1)
# super-connected friends: only look at a bounded sample of their list
for cand in sorted(their)[:max_fanout]:
if cand == user or cand in friends or cand in blocked or cand in dismissed:
continue
score[cand] += weight
mutual[cand] += 1
ranked = sorted(score, key=lambda c: (-score[c], c))[:k]
return [(c, round(score[c], 3), mutual[c]) for c in ranked]
def befriend(graph, a, b):
graph.setdefault(a, set()).add(b) # stored in both directions,
graph.setdefault(b, set()).add(a) # like the two adjacency rows
g = {}
for a, b in [("ana", "ben"), ("ana", "cara"), ("ana", "dev"),
("ben", "eli"), ("cara", "eli"), ("dev", "eli"),
("ben", "fay"), ("cara", "gus"),
("ana", "hub")] + [("hub", f"fan{i}") for i in range(40)]:
befriend(g, a, b)
print("mutual(ana, eli):", sorted(mutual_friends(g, "ana", "eli")))
print("suggestions for ana:")
for cand, s, m in suggest(g, "ana", blocked={"gus"}, k=4):
print(f" {cand:<6} score={s:<6} mutual={m}")
print("hub has", len(g["hub"]), "friends, so being friends with hub is weak evidence")
Trade-offs
- Storing each edge twice makes friend lists single-partition reads but doubles writes and needs repair for half-applied edges.
- Sharded adjacency lists scale simply for one- and two-hop queries but make deeper traversals expensive, so those run offline.
- Nightly batch suggestions are cheap per user but stale; the incremental updater adds freshness at the cost of a second code path.
- Down-weighting and sampling high-degree friends keeps the job tractable but can miss some genuine connections through popular people.
- Caching mutual counts saves CPU on popular profiles but can show a slightly outdated number.
What a strong answer shows
- Stores the graph as per-user adjacency lists written in both directions and justifies it by query patterns and read:write ratio.
- Computes mutual friends as a cached set intersection and handles batching for many profile cards.
- Estimates the two-hop explosion and moves suggestion generation offline with weighting and degree caps.
- Adds an incremental path so suggestions react quickly to new friendships.
- Filters suggestions at read time for friends, pending requests, blocks and dismissals.
- Addresses cross-shard consistency of two-sided edges and immediate blocking.
Mistakes to avoid
- Running a friends-of-friends query on demand when the panel loads.
- Choosing a graph database by reflex without explaining which queries need it.
- Storing each friendship once and needing a scatter-gather to find the other direction.
- Ranking suggestions purely by raw mutual count, so popular users dominate everyone's list.
- Forgetting that blocks and dismissals must override every cached and precomputed result.
Follow-ups to expect
- How would you show degrees of separation between two users? (Bidirectional breadth-first search with a depth limit of 3, run on demand with tight budgets, or precomputed for close pairs.)
- How would you support one-way follows as well? (Separate follower and following lists in the same store; different fan-out rules.)
- How do you rebalance a shard holding several heavy users? (Virtual shards mapped to nodes; move a virtual shard with dual writes then cutover.)
- How would you measure suggestion quality? (Acceptance rate and requests sent per impression, through A/B tests.)