Skip to content

Design a Social Graph and Shortest-Path Search

Advanced 78 min read Part 17 of 18

Design a social graph: sharded adjacency lists, BFS and bidirectional search, degrees of separation, partitioning, TAO-style caching and friend suggestions.

The Problem#

Design the system that stores who is friends with whom in a large social network, and answers questions about that graph quickly:

  • List a user's friends, newest first, with a count ("1,248 friends").
  • Check whether two users are friends, and show mutual friends ("12 mutual friends").
  • Compute the degree of separation between two users and show a shortest path ("You → Asha → Ben → Chen"), as LinkedIn does with its 1st, 2nd and 3rd degree labels.
  • Suggest new friends ("People You May Know") from the structure of the graph.
  • Serve the graph to every other product: the news feed needs friend lists to build timelines, privacy checks need "is the viewer a friend of the author", messaging needs block lists.

The graph has billions of vertices (users) and hundreds of billions of edges (friendships). It does not fit on one machine, and some vertices have millions of edges (celebrities, if the graph includes follows). The read rate is enormous, because almost every page view in a social product asks something of the graph, while the write rate (new friendships, unfriends, blocks) is small in comparison.

What makes the problem interesting:

  • Graph traversal across machines. A breadth-first search touches friends, then friends of friends, then their friends. Each hop multiplies the frontier by the average degree, and each vertex may live on a different server. A naive search makes millions of network calls.
  • Partitioning a graph is hard. Any way of splitting users across machines cuts many edges, because social graphs are densely interconnected. Which users share a machine decides how many network hops a query needs.
  • Read amplification. The feed, notifications, privacy checks and search all read the graph. The graph store sees billions of reads per second at the scale of the largest networks, so caching is not an optimisation; it is the system.
  • Small worlds. Most pairs of users are only four or five hops apart, so "how far apart are we?" is usually answerable, but the search space explodes after two or three hops.
  • Two-sided edges. A friendship is symmetric: Asha is Ben's friend and Ben is Asha's. Stored as two directed edges on two different shards, the pair must stay consistent.

Analogy. Think of a city's phone book where every entry also lists that person's friends' numbers. Finding a friend's friends means looking up each friend's entry. Finding how you are connected to a stranger means a chain of lookups: your friends, their friends, and so on, until you hit the stranger. If the phone book is split into hundreds of volumes kept in different buildings (shards), each lookup may require a trip to another building. A good design puts people who know each other in the same volume (partitioning), keeps photocopies of the most-used pages at the front desk (caching), and searches from both ends at once, you from your side and the stranger from theirs, meeting in the middle (bidirectional search).

Background: a few terms used in this design#

  • Vertex (node) and edge: a user is a vertex; a friendship or follow is an edge between two vertices.
  • Undirected vs directed: friendship is undirected (mutual); a follow is directed (Asha follows a celebrity who does not follow back).
  • Degree: the number of edges of a vertex: a user's friend count. In a directed graph, in-degree (followers) and out-degree (following) differ.
  • Adjacency list: for each vertex, the list of its neighbours' IDs. The natural storage format for a sparse graph.
  • Breadth-first search (BFS): explore a graph level by level: all neighbours first, then all neighbours of neighbours. On an unweighted graph, BFS finds shortest paths.
  • Bidirectional search: run BFS from both the source and the target, and stop when the two frontiers meet.
  • Degree of separation (distance): the number of edges on a shortest path between two users. Friends are at distance 1, friends of friends at 2.
  • Frontier: the set of vertices discovered at the current BFS level but not yet expanded.
  • Supernode (hub): a vertex with a huge degree, such as a celebrity with millions of followers.
  • Graph partitioning: assigning vertices to machines so that most edges stay inside a machine (few cut edges) while machines stay balanced.
  • Lookup service: a directory that maps a user ID to the shard or server holding that user's data.
  • TAO: Facebook's graph-aware caching and storage system for objects and associations, described in a 2013 paper.

See Graph Databases for the general data model.

Clarifying Questions#

QuestionAssumption for this design
Friendship (mutual) or follow (one-way)?Mutual friendship is the core; follows are discussed as an extension with supernodes.
How many users and edges?2 billion users, average about 200 friends, so about 200 billion friendships (400 billion directed edges).
Maximum friends per user?Capped at 5,000 friends (as Facebook does); follows uncapped.
What queries matter?Friend list, friend count, is-friend check, mutual friends, distance and shortest path, friend suggestions.
Read and write rates?Graph reads in the millions per second from other services; friend additions and removals in the tens of thousands per second at peak.
How far must path search go?Exact up to 3 hops (LinkedIn-style "3rd degree"); beyond that, an approximate distance or "more than 3" is acceptable.
Path search latency?Distance label on a profile in under about 100 ms; full path search in under a second.
Consistency?A user sees their own new friendship immediately; others within seconds. Both directions of a friendship must eventually agree.
Edge weights?Unweighted for paths. Suggestions may use weights such as interaction strength.
Privacy?Friend lists can be hidden; blocked users must never appear in paths, suggestions or lists.
Multiple regions?Yes: users worldwide, reads served from the nearest region.
May we use a graph database?Allowed, but we will design with sharded storage plus a graph-aware cache, which is what the largest networks do, and compare.

Requirements#

Functional requirements#

  1. Users can send, accept and remove friend requests; friendships are mutual. Users can block other users.
  2. List a user's friends (paginated, newest first) and show the friend count.
  3. Check whether two users are friends, and list their mutual friends with a count.
  4. Compute the degree of separation between two users (1, 2, 3 or "further") and return one shortest path.
  5. Suggest people a user may know, ranked, with explanations ("8 mutual friends").
  6. Provide a graph API that other services (feed, privacy, notifications, search) use to read edges at high rates.

Non-functional requirements#

  • Very high read throughput: millions of edge reads per second, most served from cache in about a millisecond.
  • Low latency: friend list and is-friend checks in single-digit milliseconds; degree labels under about 100 ms at p99; path search under 1 second.
  • High availability: graph reads must keep working during failures, since nearly every product depends on them. Prefer serving slightly stale data over failing.
  • Durability and eventual symmetry: no friendship is lost; both directed edges of a friendship converge.
  • Read-your-writes: after accepting a request, the user immediately sees the new friend.
  • Privacy correctness: blocks and visibility settings are always enforced in every query.
  • Scalability: grows with users and edges by adding shards and cache servers.

Capacity Estimation#

See Back-of-the-Envelope Estimation. Two sizes help: a classic interview size, and a planet-scale size.

The classic interview size. 100 million users with an average of 50 friends gives 5 billion friendships. One billion friend searches per month is 1 billion ÷ 2.5 million seconds ≈ 400 searches per second on average, more at peak, with very uneven popularity: some searches are repeated often, many are executed once. Even here the graph is too big for comfortable single-machine use once you add metadata and replication: 5 billion friendships as 10 billion directed edges × 8 bytes per neighbour ID = 80 GB of raw adjacency lists, before indexes, timestamps or replicas.

The planet-scale size used in this design.

  • Users (vertices): 2 billion.
  • Average degree: about 200 friends (the distribution is heavily skewed: the median is lower, around 100 in published Facebook studies, and a long tail goes up to the 5,000 cap).
  • Friendships: 2 billion × 200 ÷ 2 = 200 billion undirected edges, stored as 400 billion directed edges (one in each user's list).

Storage.

  • Each directed edge stores the neighbour ID (8 bytes), a creation time (4–8 bytes), and a small state or type field: about 20 bytes. 400 billion × 20 bytes = 8 TB of edge data.
  • With indexes and storage-engine overhead (about 2×) and three replicas: about 50 TB on disk. That is a few hundred database shards of 100–200 GB each.
  • User objects (profile fields used by graph queries: name, privacy settings, counts): 2 billion × 500 bytes = 1 TB.

Reads.

  • 1 billion daily active users, each loading feeds, profiles and notifications that touch the graph. Suppose each page view or app refresh triggers 10–50 graph reads (friend lists, is-friend checks for privacy, counts), and there are about 100 billion page views and refreshes a day: 1–5 trillion graph reads per day ≈ 10–60 million per second. Published figures for Facebook's TAO describe reads at the scale of a billion per second, so these numbers are within the realm of real systems.
  • Degree-of-separation labels: shown on profile views and search results. Say 20 billion per day ≈ 230,000 per second, mostly for distance 1 or 2.
  • Full shortest-path searches (explicit "how are we connected?"): far rarer, perhaps 10,000 per second at peak.

Writes.

  • New friendships: perhaps 1–2 billion per day across the network in requests sent, and a fraction accepted. Say 500 million accepted per day ≈ 6,000 per second, peaking around 20,000. Each writes two directed edges and updates two counts.
  • Unfriends, blocks and request state changes add a similar order of magnitude. Total graph writes: tens of thousands per second, which is a few hundred times smaller than the read rate.

Traversal cost. The number that matters most: a BFS from one user reaches about 200 friends at distance 1, and about 200 × 200 = 40,000 at distance 2, minus overlap. Because friends share friends, real two-hop neighbourhoods are smaller, perhaps 10,000–30,000 distinct users. Distance 3 is about 200 times larger again: millions of users. A one-directional BFS to depth 3 is therefore impractical per request; a bidirectional search to depth 3 only needs two depth-1 or depth-2 expansions, as Deep Dive 2 shows.

QuantityEstimate
Users2 billion
Average friends~200 (median ~100, cap 5,000)
Directed edges~400 billion
Edge data~8 TB raw, ~50 TB with overhead and replicas
Graph reads~10–60 million per second
Degree labels~230,000 per second
Path searches~10,000 per second at peak
Graph writes~10,000–50,000 per second
Two-hop neighbourhood~10,000–40,000 users

Core Entities#

  • User (vertex): ID, display name, privacy settings (who can see my friend list, who can send requests), friend count, region.
  • Friendship (edge): two directed edges (A to B and B to A), each with creation time and state. The canonical record is keyed by the ordered pair (smaller ID, larger ID).
  • Friend request: sender, recipient, state (pending, accepted, declined, cancelled), creation time.
  • Block: blocker, blocked, time. Blocks are directed and override everything else.
  • Follow (optional extension): follower, followee, time; directed edges with no symmetry constraint.
  • Suggestion: for a user, a ranked list of candidate users with features and reasons, refreshed periodically.
  • Shard map entry: user ID or ID range, shard, replica locations; the lookup service's data.

API Design#

Two APIs: a public one used by apps, and an internal graph API used by other services. See API Design Best Practices and API Styles: REST, gRPC, GraphQL and More.

# Public (REST over HTTPS)
POST   /v1/friend-requests            { toUserId }                → 201 { requestId }
POST   /v1/friend-requests/{id}/accept                            → 200
DELETE /v1/friends/{userId}                                       → 204 (unfriend)
POST   /v1/blocks                     { userId }                  → 201
GET    /v1/users/{id}/friends?cursor=…&limit=50                   → { friends[], nextCursor, total }
GET    /v1/users/{id}/mutual-friends?with={otherId}&limit=20      → { users[], total }
GET    /v1/users/{id}/connection?to={targetId}&maxDepth=3          → { degree, path[] }
GET    /v1/me/suggestions?limit=20                                → { suggestions[{ user, reason, mutualCount }] }
 
# Internal graph API (RPC, batched)
assoc_range(id1, type, offset, limit)        → newest-first edge list
assoc_get(id1, type, [id2...])              → which of these edges exist
assoc_count(id1, type)                       → edge count
assoc_add(id1, type, id2, time, data)        → write (and inverse edge)
assoc_delete(id1, type, id2)
neighbours_batch([id...], type, limit)       → adjacency lists for many vertices on one shard

Design notes:

  • The path endpoint takes a depth limit. Path search is bounded, by depth and by a time budget. If no path is found within the limit, the response says "further than 3" rather than searching the whole graph. The primer-style advice applies: set a limit by time or hops, and ask the user before searching further.
  • Batching is essential internally. neighbours_batch fetches the adjacency lists of many vertices that live on the same shard in one call. A BFS that calls one RPC per vertex is hopeless; one RPC per shard per BFS level is workable.
  • The internal API mirrors TAO's association API (Deep Dive 7): typed edges between two IDs, ordered by time, with range, get and count operations. Other services do not need graph queries more complex than these.
  • Accept is idempotent. Accepting an already accepted request returns success, so retries are safe. See Idempotency and Safe Retries.
  • GraphQL is a front-end choice, not a graph store. A GraphQL API can make fetching "user, their friends, and each friend's mutual count" one request for clients, but it is a query language over your services; the hard part (traversal and storage) is unchanged.
  • Privacy filtering happens inside every endpoint: friend lists respect visibility settings, and blocked users are removed from every result, including paths and suggestions.

High-Level Design#

We build the design requirement by requirement, starting with the primer-style baseline (sharded person servers plus a lookup service) and growing into a TAO-style architecture.

1) Store friendships across many machines#

The graph is stored as adjacency lists sharded by user ID: all outgoing edges of user A live on A's shard. A friendship between A and B is two edges: A to B on A's shard, and B to A on B's shard. A lookup service (or a deterministic function of the user ID) maps each user to a shard. Every read about A ("A's friends", "is B a friend of A") then goes to exactly one shard.

2) Serve friend lists and is-friend checks fast#

Reads vastly outnumber writes, so a graph-aware cache tier sits in front of the shards. It caches each user's edge list (or its newest part), counts, and the results of is-friend checks. Caches are organised by the same shard mapping, so a cache server knows which database shard backs it. Deep Dives 5 and 7 cover this tier.

3) Add and remove friendships#

Accepting a friend request writes both directed edges and updates both counts. The two edges usually live on two different shards, so the write must either be a small distributed transaction or (as at large networks) a write to one shard followed by a reliable asynchronous write of the inverse edge, with a repair process that fixes any asymmetry. Deep Dive 9 covers the trade-off.

4) Degrees of separation and shortest paths#

A path service answers "how is A connected to T?" with a bidirectional BFS: it expands A's friends and T's friends in batches per shard, checks for overlap, and expands one more level from the smaller frontier if needed. Distance 1 and 2 are answered from adjacency lists and set intersection; distance 3 needs one more expansion. Precomputed data (two-hop neighbourhoods for active users, landmark distances) speeds up common cases.

5) Friend suggestions#

A suggestion pipeline generates candidates offline and nearline: friends of friends ranked by mutual-friend count and other features, plus other sources (shared schools, workplaces, contacts uploaded with consent). A ranking model scores candidates, and the top results are stored per user in a key-value store, refreshed daily and updated when the user's friendships change.

6) Serving every other product#

The graph API is a platform. The feed builder reads friend lists to fan out posts (as in the separate case study Design a News Feed (Facebook / Twitter)); privacy checks call is-friend in bulk for every item on a page; notifications read lists of friends. These callers make most of the traffic, so the API is batched, cached and replicated to every region.

The full high-level design#

Components:

  • Graph API servers: stateless; translate product requests into batched association operations, enforce privacy and blocks.
  • Path service: runs bounded bidirectional BFS with per-shard batching and a time budget; uses precomputed neighbourhoods and landmarks.
  • Suggestion API and pipeline: serves precomputed, ranked suggestions; batch and nearline jobs keep them fresh.
  • Follower caches: many per region; serve reads, fill misses from the leader cache.
  • Leader caches: one logical leader per shard; all writes and follower misses go through it, so it orders updates and protects the database from thundering herds.
  • Lookup service: maps user IDs (or the shard number embedded in them) to shards and to cache servers; small, replicated, cached everywhere.
  • Sharded edge store: durable adjacency lists, a few hundred logical shards on many machines, with replicas in each region.
  • Change log: carries edge changes to other regions, the inverse-edge writer, caches (invalidations) and offline consumers.
  • Offline graph jobs: daily snapshots for suggestion generation, landmark distances, partition optimisation and analytics.

Key Flows#

Flow 1: Ben accepts Asha's friend request#

Step by step:

  1. Validation. The request must be pending, neither user may have blocked the other, and both must be under the friend cap. These reads go to the cache.
  2. First edge, synchronously. The write goes to the leader cache for Ben's shard, which writes to Ben's database shard: the edge Ben to Asha, Ben's count plus one, and the request's state change, in one local transaction. The leader updates its own cached copy of Ben's list (write-through), so Ben sees Asha immediately (read-your-writes).
  3. Inverse edge, asynchronously but reliably. The database's change log (or an outbox row written in the same transaction) records that the inverse edge Asha to Ben is needed. A consumer applies it through Asha's leader cache. The write is idempotent (inserting an existing edge is a no-op), so retries are safe. Typically this takes milliseconds to a second.
  4. Cache invalidation. Edge changes flow through the change log to follower caches in every region, which update or invalidate their copies of both users' lists and counts.
  5. Side effects. A notification to Asha ("Ben accepted your request"), a feed story, and a nearline refresh of both users' friend suggestions (each of Ben's friends is now a friend of a friend for Asha).

For a short window, Asha's list may not show Ben yet while Ben's list shows Asha. Because Asha sent the request and the notification arrives at roughly the same time, the asymmetry is rarely visible. The alternative, a two-phase commit across shards, is discussed in Deep Dive 9.

Flow 2: Asha views Chen's profile and sees "2nd degree, via Ben"#

Step by step:

  1. Degree 1. A single is-friend check from the cache. If true, the answer is "1st degree".
  2. Degree 2. Asha and Chen are at distance 2 exactly when their friend lists intersect. Intersecting two sorted lists of about 200 IDs takes microseconds. Alternatively, a precomputed two-hop neighbourhood for active users (Deep Dive 3) answers it with one lookup.
  3. Degree 3. If the lists do not intersect, expand the smaller side by one hop (friends of Asha's friends, about 40,000 users before deduplication, fetched in batches per shard) and intersect with Chen's friend list. Any hit gives a path of length 3. If there is none, the answer is "beyond 3rd degree".
  4. Privacy. The intermediate users on the path must be visible to Asha (some users hide their friend lists), and nobody on the path may have blocked Asha. If the first path fails privacy checks, the service looks for another one among the meeting points.

Flow 3: the feed service reads friend lists for 500 users at once#

This is the dominant traffic pattern: other services asking for many small things at once. The keys are grouped by shard and cache server, fetched in parallel with one round trip per server, and the slowest server determines latency. That is why tail latency of individual cache servers matters so much: one request fans out to 180 servers, so a 1-in-1,000 slow server affects about 16% of requests (1 − 0.999¹⁸⁰). Deep Dive 5 discusses the defences.

Data Model#

The storage model is deliberately simple: a sharded key-value or relational store holding objects (users) and associations (typed, directed edges), in the style Facebook described for TAO. Graph-specific intelligence lives in the cache tier and the services, not in the database.

Requests and blocks are separate tables, also sharded by the user they belong to (the recipient for requests, the blocker for blocks, with an inverse "blocked by" association on the other side so both users' queries can check it locally). Suggestions are one row per user in a key-value store, holding a ranked list of candidate IDs with scores and reasons.

-- One table per shard (hundreds of logical shards on many MySQL hosts)
CREATE TABLE associations (
  id1        BIGINT   NOT NULL,       -- owner of the edge (decides the shard)
  assoc_type SMALLINT NOT NULL,       -- 1 friend, 2 follows, 3 followed_by, 4 blocks ...
  id2        BIGINT   NOT NULL,       -- the other end
  time       BIGINT   NOT NULL,       -- creation time, used for newest-first ordering
  state      SMALLINT NOT NULL DEFAULT 0,  -- 0 visible, 1 pending delete, 2 hidden
  data       VARBINARY(255),
  PRIMARY KEY (id1, assoc_type, id2)
);
-- Newest-first range scans: "Ben's friends, most recent 50"
CREATE INDEX assoc_by_time ON associations (id1, assoc_type, time DESC, id2);
 
CREATE TABLE assoc_counts (
  id1 BIGINT NOT NULL, assoc_type SMALLINT NOT NULL, count BIGINT NOT NULL,
  PRIMARY KEY (id1, assoc_type)
);
 
-- assoc_range: newest 50 friends of :id
SELECT id2, time FROM associations
WHERE id1 = :id AND assoc_type = 1 AND state = 0
ORDER BY time DESC LIMIT 50;
 
-- assoc_get: which of these users are friends of :id
SELECT id2 FROM associations
WHERE id1 = :id AND assoc_type = 1 AND id2 IN (:a, :b, :c) AND state = 0;

Notes on the model:

  • Edges are owned by id1. The shard of an edge is the shard of its source vertex. All of a user's friends are in one place, so the friend list is a single range scan on one shard, and "is B a friend of A" is a primary-key lookup on A's shard.
  • Two primary access paths. The primary key (id1, assoc_type, id2) serves existence checks and deduplication (inserting an existing edge is a no-op, which makes writes idempotent). The time index serves newest-first pagination. Both are covering for their queries, so the base rows are never touched.
  • Counts are separate rows. Counting a 5,000-edge list on every profile view would be wasteful; a maintained count row is updated in the same transaction as each edge insert or delete on that shard.
  • Inverse types. Directed relations come in pairs: follows on the follower's shard and followed_by on the followee's shard. For friendship the type is its own inverse.
  • Shard ID in the user ID. Embedding a logical shard number in the 64-bit ID (as TAO does with its object IDs) means routing needs no lookup at all for the common case; the lookup service then only maps logical shards to physical hosts. See Unique ID Generation.
  • Soft states. state allows hiding edges (for example during account deactivation) without deleting them, and marking edges whose inverse write is in progress.
DataStoreWhy
Users and associations (edges), countsSharded MySQL (or another sharded relational or wide-column store)Simple range scans and point lookups; mature replication and tooling; edges keyed by owner
Hot edge lists, counts, membershipGraph cache tier (leader and follower caches, in memory)Billions of reads per second, sub-millisecond
Shard mapLookup service (replicated, cached in every client)Tiny, read on every request
Requests, blocksSame sharded store, keyed by recipient or blockerSame access patterns as edges
Two-hop neighbourhoods and landmark distancesKey-value store such as Cassandra or a RocksDB-backed serviceLarge precomputed data with point reads
Friend suggestionsKey-value store, one row per userRead once per session, rewritten daily
Graph snapshotsDistributed file system or object storage, columnar filesInput for batch graph jobs
Change logDurable log such as Kafka or the database's binlogInverse edges, invalidations, cross-region replication

A native graph database (Neo4j, JanusGraph, Amazon Neptune) could store the same data and run multi-hop queries in its own query language. At hundreds of billions of edges and millions of reads per second, the dominant workload is single-hop reads, which a sharded store plus cache serves more cheaply and predictably; multi-hop work is limited to a few specialised services. The comparison is in a Deep Dive at the end of this page. See Choosing a Database: A Decision Guide.

Deep Dives#

1. Friend graph storage: adjacency lists, sharded#

Why adjacency lists. A graph can be stored as an adjacency matrix (a 2-billion-by-2-billion grid of bits) or as adjacency lists (for each vertex, the list of its neighbours). The matrix would need 2×10⁹ × 2×10⁹ bits = 4×10¹⁸ bits, about 500 petabytes, almost all zeros, because each user has hundreds of friends, not billions. Adjacency lists store only existing edges: 400 billion entries. Social graphs are sparse (the average degree, 200, is tiny compared with the number of vertices), so adjacency lists are the only practical choice.

Representations of a list.

  • Rows in a table (one row per edge, as in the Data Model): simplest, supports point lookups and range scans with ordinary indexes, and gets transactions and replication from the database. Each edge costs perhaps 40–60 bytes including index overhead.
  • One value per user (a serialised list of neighbour IDs in a key-value store): one read fetches all friends. Updates must rewrite the value (or append to it), which is fine for lists up to a few thousand entries but bad for follower lists of millions.
  • Compressed sorted arrays in memory (in caches and in graph-processing systems): sort the neighbour IDs and store the differences between consecutive IDs (gaps) with variable-length integer encoding. Gaps between sorted 64-bit IDs drawn from a 2-billion-user space average about 10 million, which fits in about 3–4 bytes with varint encoding instead of 8. Graph compression research (the WebGraph framework of Boldi and Vigna) goes further, exploiting locality and similarity between lists to reach a few bits per edge for web graphs and social graphs with good ID orderings.

The design uses rows in sharded MySQL as the source of truth, and compressed or plain arrays in the caches and in offline systems.

Sharding by user ID. All edges owned by user A are on A's shard. This is partitioning by source vertex, also called edge-cut partitioning: each vertex is on one shard with all its outgoing edges, and an edge between users on different shards is "cut" (stored on both shards, as the edge and its inverse). The benefit is that every one-hop query (list, count, existence) touches a single shard. The cost is that multi-hop queries jump between shards, which Deep Dives 2 and 4 address.

Logical and physical shards. The ID space is divided into many logical shards (say 16,384), far more than the number of database hosts (say 500). Each host serves about 30 logical shards. When a host gets too full or too hot, logical shards are moved to new hosts: copy the data, replay changes, switch the mapping in the lookup service. No user ID ever changes, and no rehashing of the whole space is needed. See Partitioning and Sharding.

Choosing the shard of a new user. Options:

  1. Hash of the user ID (or a random logical shard): perfectly balanced, ignores locality.
  2. Encode the shard in the ID at creation, chosen by a policy: by region (users from Brazil on shards in South American data centres), or by a social-hash assignment that is updated later.
  3. Directory-based: the lookup service stores user-to-shard for every user (2 billion entries × 8 bytes = 16 GB, a big but manageable replicated table), allowing any user to be moved individually.

The trade-off is between routing cost (a function needs no lookup; a directory needs a cached lookup) and flexibility (a directory allows locality-aware placement and per-user moves). Many systems combine them: the ID encodes a logical shard (fast routing), and logical shards can move between hosts (flexibility at the shard level).

Balanced load, unbalanced degrees. Hashing balances the number of users per shard, but load depends on degree and activity: a shard that happens to hold several very popular accounts receives far more reads. Mitigations: many small logical shards (so heavy users spread out), moving hot logical shards to dedicated hosts, and treating supernodes specially (Deep Dive 8).

Write path. An edge insert on one shard is a small transaction: insert the association row (or no-op if it exists), increment the count row. At 20,000 friendships per second at peak, each producing two edge writes, the cluster handles 40,000 small transactions per second, which is under 100 per second per host across 500 hosts.

Read path without caching. A newest-first friend list read is an index range scan of 50 entries on one shard, under a millisecond with the index in memory. But at tens of millions of reads per second, the database would need tens of thousands of hosts. The cache tier reduces database reads by one to two orders of magnitude.

Deleting a user. Account deletion must remove every edge in both directions: the user's own list (one shard) and the inverse edge in each friend's list (up to 5,000 other shards). That is a background job driven by the user's own list, writing inverse deletions through the normal path, idempotently, and finally deleting the user's rows. Until it finishes, the user's edges are hidden through the state column, so they disappear from queries immediately.

BFS on one machine. For an unweighted graph, breadth-first search finds shortest paths. Start from the source, put it in a queue, mark it visited, and repeatedly take a vertex from the queue and add its unvisited neighbours, remembering each neighbour's predecessor. When the target is taken from the queue, follow predecessors back to the source to get the path. Every vertex is visited at most once, so the cost is O(V + E) in the worst case.

function shortestPath(source, target, maxDepth):
    if source == target: return [source]
    prev = { source: none }
    frontier = [source]
    for depth in 1..maxDepth:
        next = []
        for v in frontier:
            for n in neighbours(v):          # adjacency list lookup
                if n not in prev:
                    prev[n] = v
                    if n == target: return buildPath(prev, target)
                    next.append(n)
        frontier = next
    return none                               # further than maxDepth

This level-by-level form (rather than a single queue) makes it easy to enforce a depth limit and to batch neighbour lookups per level, which is what the distributed version needs.

Why naive BFS does not scale. With average degree d, level k has up to dᵏ vertices. For d = 200: level 1 has 200, level 2 up to 40,000, level 3 up to 8 million, level 4 up to 1.6 billion. Because friends overlap, real numbers are smaller, but a one-directional BFS to depth 3 or 4 still touches millions to a billion vertices. And in a sharded graph, each vertex's neighbour list may be on a different machine: the primer's straightforward design (a user graph service calling the lookup service and then a person server for every vertex) would make millions of sequential network calls per search.

Fix 1: batch per shard and per level. Instead of fetching one vertex at a time, take the whole frontier, group vertex IDs by shard (using the lookup service or the shard bits in the ID), and send one neighbours_batch request per shard, in parallel. A level with 40,000 vertices spread over 500 shards becomes 500 parallel requests of about 80 vertices each, and the level's latency is that of the slowest shard, perhaps 5–20 ms. The number of round trips becomes the number of levels, not the number of vertices.

Fix 2: bidirectional search. Run BFS from both ends. Expand the source's frontier and the target's frontier alternately, and stop when they intersect. If the true distance is D, each side only needs to go about D/2 levels. The work drops from about d^D to about 2 × d^(D/2). For D = 4 and d = 200: one-directional is up to 1.6 billion; bidirectional is 2 × 40,000 = 80,000. That is a factor of 20,000.

function bidirectional(s, t, maxDepth):
    if s == t: return [s]
    prevS = { s: none };  prevT = { t: none }
    frontS = [s];         frontT = [t]
    for step in 1..maxDepth:
        # expand the smaller frontier: it costs less and grows less
        if size(frontS) <= size(frontT):
            frontS = expand(frontS, prevS)       # batched per shard
            meet = frontS ∩ keys(prevT)
        else:
            frontT = expand(frontT, prevT)
            meet = frontT ∩ keys(prevS)
        if meet not empty:
            m = best(meet)                       # e.g. most visible, fewest privacy issues
            return path(prevS, m) + reverse(path(prevT, m))[1:]
    return none

Correctness of the stopping rule. With unit edge weights and level-by-level expansion, the first level at which the frontiers meet gives the shortest distance: any shorter path would have caused a meeting at an earlier step. (With weighted edges, bidirectional Dijkstra needs a subtler stopping condition, but social distance is unweighted.) Within that level, all meeting vertices give paths of the same length, so the service can choose among them, for example preferring intermediaries whose friend lists are visible to the viewer.

Expand the smaller side. Always expanding the smaller frontier keeps the total work close to optimal when the two ends have very different degrees. If the target is a user with 5,000 friends and the source has 50, expanding from the source first is cheaper.

Fix 3: start from hubs (with care). The primer suggests starting from people with many friends, because they shorten paths. In a bidirectional search this appears naturally: high-degree vertices appear in many neighbourhoods, so meetings often happen through them. Treat it as a heuristic for finding some path quickly, not as a guarantee of the shortest one; exactness comes from the level-by-level search.

Fix 4: bound depth and time. The search stops at depth 3 (LinkedIn-style labels) or at a time budget (say 200 ms). If it has not finished, the answer is "3+" or "connection not found within limits". Showing a degree label on a profile does not need more than that, and an explicit "find the full path" request can be allowed a larger budget, run asynchronously, and the user asked whether to continue, as the primer recommends.

Worked example. Asha (180 friends) and Chen (240 friends) are at distance 3. Step 1: expand Asha (smaller): one batched request for Asha's list (already in cache), frontier of 180. Intersect with Chen's visited set, which holds only Chen: no meeting. Step 2: Chen's frontier is 1 versus Asha's 180, so expand Chen: frontier of 240, intersect with Asha's visited set (Asha plus her 180 friends): no meeting. Step 3: expand Asha's 180 friends: fetch 180 lists (about 36,000 IDs, perhaps 25,000 unique), grouped across a few hundred shards, served from cache. Intersect with Chen's 241 visited vertices: meeting found at Dev, who is Asha's friend-of-friend and Chen's friend. Path: Asha → Eli → Dev → Chen. Total: three levels, two of which were single-list reads, and one batched level of 180 list reads. Latency: about 3 round trips of 5–15 ms, well within budget.

Memory per search. Visited sets of tens of thousands of 8-byte IDs plus predecessors use about 1 MB per search. At 10,000 concurrent searches, 10 GB across the path service fleet: fine. A hash set is the simplest structure; for very large frontiers, a Bloom filter of one side's visited set can pre-filter the intersection, with exact confirmation for candidates.

3. Degrees of separation at scale#

The small-world facts. Social graphs are small worlds: almost everyone is connected to almost everyone else through a short chain. Stanley Milgram's letter-forwarding experiments in the 1960s (reported by Travers and Milgram in 1969) produced the popular "six degrees of separation". Watts and Strogatz ("Collective dynamics of 'small-world' networks", Nature, 1998) explained how a few long-range links make a clustered graph small. On Facebook itself, the study "Four Degrees of Separation" (Backstrom, Boldi, Rosa, Ugander and Vigna, 2012), measured the whole graph of about 721 million active users and 69 billion friendships and found an average distance of about 4.74 hops, with almost all pairs within 5 or 6. A companion study, "The Anatomy of the Facebook Social Graph" (Ugander, Karrer, Backstrom and Marlow, 2011), found that over 99.9% of active users were in one giant connected component, and that the median friend count was about 100.

Consequences for the design:

  • A path almost always exists, and it is short. A depth limit of 6 would almost always find one.
  • But "short" in hops is huge in vertices: the 4-hop neighbourhood of a typical user is a large fraction of the whole graph. Exact shortest paths at distance 4–6 cannot be computed per request with BFS from one side, and even bidirectional search at distance 5–6 expands millions of vertices.
  • Users care most about 1st, 2nd and 3rd degree, where the relationship means something ("you both know Ben"). Beyond that, "you are 5 hops apart" has little value.

So the product decision (show exact degrees up to 3, otherwise "3+") is also an engineering decision. LinkedIn, which shows 1st, 2nd and 3rd degree on every profile and search result, has described dedicated graph serving infrastructure built for exactly these queries.

Computing degree 1 and 2 cheaply.

  • Degree 1: an assoc_get on the viewer's shard. Cached; well under a millisecond.
  • Degree 2: non-empty intersection of the two friend lists. With sorted lists of about 200 IDs each, a linear merge takes about 400 comparisons; with one list in a hash set, 200 probes. Microseconds once both lists are in memory.

Degree 3: the precomputed two-hop neighbourhood. For active users, precompute and store the set of users at distance exactly 2 (friends of friends who are not friends), with, for each, one or more intermediary friends. Then degree 3 for target T is: does any friend of T appear in the viewer's two-hop set? That is 200 lookups of T's friends against a set of perhaps 20,000–40,000 entries: microseconds.

  • Storage: 1 billion active users × 30,000 entries × 8 bytes = 240 TB. Too much to store exactly for everyone. Options: store it only for very active users; compress (sorted IDs with gap encoding, about 3 bytes per entry, gives 90 TB); or store a Bloom filter of the two-hop set (30,000 entries at 1% false-positive rate is about 36 KB per user, 36 TB in total) and confirm positives exactly.
  • Computation: each user's two-hop set is the union of their friends' friend lists, so computing it reads about 200 lists. Done as a daily batch job over a graph snapshot (Deep Dive 11) and incrementally when a user's friendships change.
  • Staleness: a friendship formed today might not be reflected until the next update. For a degree label this is acceptable; the exact 1st-degree check is always live.

Bloom filter worked example. A Bloom filter with m bits and k hash functions for n items has a false-positive rate of about (1 − e^(−kn/m))^k. For n = 30,000 and a 1% target, m ≈ 9.6 bits per item ≈ 288,000 bits ≈ 36 KB, with k = 7. To check degree 3 for T, probe T's 200 friends; the chance of at least one false positive among 200 probes is 1 − 0.99²⁰⁰ ≈ 87%, which is far too high. So the Bloom filter answers "definitely not 3rd degree" quickly when all probes are negative, but a positive needs confirmation: fetch the candidate's lists and check exactly. A lower false-positive rate (0.01% at about 19 bits per item, 72 KB per user) makes confirmations rare. See Probabilistic Data Structures for Big Data.

Approximate distances beyond 3: landmarks. For "how far apart are we, roughly?", a landmark (or sketch) method precomputes distances from a few hundred well-chosen vertices (landmarks, often high-degree, central users) to every vertex, with one full BFS per landmark in an offline job. For any pair (u, v), the triangle inequality gives an upper bound:

dist(u, v) <= min over landmarks L of ( dist(u, L) + dist(L, v) )

and a lower bound max over L of |dist(u, L) − dist(L, v)|. With about 100 landmarks chosen by degree or centrality, the upper bound is often exact or off by one on social graphs, as studied in "Fast Shortest Path Distance Estimation in Large Networks" (Potamias, Bonchi, Castillo and Gionis, CIKM 2009). Storage: 100 landmarks × 2 billion vertices × 1 byte (distances are small) = 200 GB. The landmark paths also give an actual path (u to L to v), not necessarily shortest.

Exact distances with 2-hop labelling. A family of distance labelling schemes stores, for each vertex, a small set of (hub, distance) pairs such that the distance between any two vertices is the minimum over shared hubs. Pruned landmark labelling (Akiba, Iwata and Yoshida, SIGMOD 2013) builds such labels by running BFS from vertices in descending degree order and pruning when an existing label already proves a distance. It answers exact distance queries in microseconds on graphs with hundreds of millions of edges, but the labels and preprocessing grow too large for a 400-billion-edge, constantly changing graph. It is a good answer to "what would you do for a static graph of a few hundred million edges?" and illustrates the general idea: trade preprocessing and storage for query time.

Measuring the whole distance distribution. To compute statistics such as "average distance 4.74", nobody runs 10¹⁸ BFS searches. The Four Degrees study used HyperANF (Boldi, Rosa and Vigna, 2011), which keeps a HyperLogLog counter per vertex estimating the size of its k-hop neighbourhood, and computes level k+1 by merging the counters of neighbours (the union of neighbourhoods). Each iteration is one pass over the edges, and a few iterations give the distance distribution for the whole graph. It is a beautiful combination of probabilistic counting and graph iteration, and the same trick estimates per-user neighbourhood sizes for features ("you could reach 12 million people within 3 hops").

Product rules on top. The degree label must respect privacy: if the only 2nd-degree path goes through someone who hides their friend list from the viewer, many products still show "2nd" but not who connects them, or treat it as 3rd. Blocks remove paths entirely. These rules are applied after the graph computation, on the small set of candidate intermediaries.

4. Graph partitioning and the lookup service#

The problem. With hash sharding, a user's friends are spread uniformly across shards. With 500 hosts and 200 friends, a two-hop query touches nearly every host. If friends tended to be on the same shard as the user, many hops would stay local, saving network calls and making the cache more effective. The goal of graph partitioning is to assign vertices to k shards so that (1) each shard has about the same load and (2) as few edges as possible cross shards (minimum edge cut).

Why it is hard. Balanced minimum graph partitioning is NP-hard, so practical systems use heuristics. And social graphs resist clean cuts: they have strong local communities (friends from school, work, a city) but also many long-range edges that make the world small. Real partitions keep perhaps 40–70% of edges local at best, compared with 1/k (0.2% for 500 shards) for random hashing.

Heuristics that work.

  • Geography. Friends tend to live near each other. The primer suggests sharding person servers by location for this reason. Assigning users to shards by country or city puts a large fraction of friendships on the same shard or in the same region. The downside: uneven region sizes and population shifts, which logical shards can absorb.
  • Multilevel partitioning (METIS). The classic algorithm family of Karypis and Kumar (1998) coarsens the graph by merging matched vertices, partitions the small graph, then refines while uncoarsening. Excellent quality for graphs that fit in one machine's memory; distributed variants exist but struggle at hundreds of billions of edges.
  • Label propagation. Each vertex repeatedly moves to the partition where most of its neighbours are, subject to balance constraints. It is simple and parallel, and maps well to a Pregel-style job (Deep Dive 11). Ugander and Backstrom described balanced label propagation for partitioning the Facebook graph (WSDM 2013), formulating the balanced moves as a linear program, and reported large improvements in edge locality over random assignment.
  • Social Hash. Facebook's Social Hash framework ("Social Hash: An Assignment Framework for Optimizing Distributed Systems Operations on Social Networks", Shalita et al., NSDI 2016) separates a static step (assign users to many small groups using graph partitioning, so that related users share groups) from a dynamic step (map groups to machines, adapting to load). The paper reports large reductions in fan-out for production workloads by placing socially related users together.

Edge-cut versus vertex-cut. Partitioning by vertex (each vertex on one shard with its edges, edges between shards "cut") is natural for adjacency-list storage. For graphs with supernodes, vertex-cut partitioning (each edge on one shard, high-degree vertices replicated across shards, as in PowerGraph by Gonzalez et al., OSDI 2012) balances work better, because one celebrity's millions of edges are spread across machines. Serving systems usually stay with edge-cut and special-case supernodes; processing systems often use vertex-cut.

The lookup service. If placement is not a pure function of the ID, something must map users to shards:

  • Data: for each logical shard, its primary host and replicas per region (tens of thousands of entries); optionally, for each user, a logical shard override (billions of entries, only if users move individually).
  • Serving: the map is small at the shard level and is cached in every graph API and cache server, refreshed on change through a watch on a coordination service such as ZooKeeper or etcd. Per-user directories are larger (16 GB for 2 billion users at 8 bytes each), held in a replicated in-memory service or embedded into the ID.
  • Moves: moving a user between logical shards means copying their edges and counts, double-writing during the move, flipping the directory entry, and cleaning up. Moving a logical shard between hosts is the same at a bigger granularity. During a move, readers may be redirected (the old location answers "moved, try shard X").

The primer's design notes that the user graph service must ask the lookup service for every neighbour, which is a "potential for optimisation". The optimisations are exactly: (1) put the shard in the ID so most lookups disappear, (2) cache the shard map locally, and (3) batch lookups per BFS level, grouping by shard.

When locality matters, and when it does not. For one-hop reads (the dominant traffic), locality hardly matters: each read goes to one shard anyway. It matters for multi-hop queries (path search, mutual friends, suggestions) and for batched page loads, where one page needs data about many related users: if they share shards, the request fans out to fewer servers, which reduces tail latency and cache memory. This is why Social Hash was applied to caching and query routing, not only to storage.

5. Caching#

Caching is where most of the system's work happens: at millions of graph reads per second, the database can only serve misses and writes. See Caching Fundamentals and Distributed Caching with Redis and Memcached.

What to cache. The primer suggests caching person data in a memory cache like Redis or Memcached, especially for users who search repeatedly and for well-connected users, and also caching complete or partial BFS traversals. In detail:

Cached itemKeySizeFreshness
Edge list (newest part, or all up to the cap)(user, type)200 × 16 bytes ≈ 3 KB; up to 80 KB at 5,000Updated on write
Edge count(user, type)8 bytesUpdated on write
Is-friend results(user, type, other)TinyDerived from the list when cached; else cached negative results with a short TTL
User objectsuserAbout 500 bytesInvalidated on change
Two-hop sets or Bloom filtersuser36–100 KBRebuilt daily or on change
Path results(viewer, target)SmallShort TTL, minutes
SuggestionsuserA few KBRebuilt daily

Why lists, not query results. Caching the edge list lets one cached object answer many queries: list pages, counts, is-friend checks, mutual friends (intersection of two cached lists), and BFS expansion. Caching results of individual queries (for example each is-friend pair) would multiply entries and make invalidation hard. This is the key idea behind TAO (Deep Dive 7): the cache understands the graph data model, so it can answer association queries from cached lists and apply writes to them in place.

Hit rate arithmetic. With 1 billion daily active users and their friend lists averaging 3 KB, the lists of all active users take 3 TB, plus counts and objects. A cache tier of a few hundred servers with 64–256 GB each holds the whole active graph. Reads of inactive users' lists miss and go to the database, but those are rare. Real systems report hit rates above 95–99% for this kind of workload; at 30 million reads per second, 99% hit rate leaves 300,000 database reads per second, spread over 500 hosts: 600 each, which is comfortable.

Write-through, not invalidate-only. When an edge is added, the cache holding the user's list applies the change to the cached list (prepend the new edge, increment the count) instead of deleting the key. Deleting would force the next read to reload a 5,000-entry list from the database, and popular users would cause constant reloads. Write-through keeps the cache warm. The risk is divergence (the cache applies a change that the database rejected); writing to the database first, then updating the cache from the committed result, avoids it.

Regions and replicas. Each region has its own cache tier serving local reads. Writes go to the region holding the primary database for that shard; the change is replicated to other regions' databases and their caches update from the replication stream. A user in a non-primary region who just made a change might read their own stale data from the local replica; the fix is to route that user's reads to the primary region for a short time, or have the local cache record the write and serve it until replication catches up. TAO's paper describes this kind of handling. See Multi-Region and Global Data.

Tail latency with fan-out. A page load that touches 180 cache servers (Flow 3) waits for the slowest. Defences:

  • Hedged requests: if a server has not answered within the 95th-percentile latency, send the same read to a replica and use the first answer.
  • Partial results: for non-critical data (mutual friend counts on a list of 50 people), return what arrived within the deadline and fill the rest later.
  • Fewer servers per request: locality-aware placement (Deep Dive 4) means related users' lists sit on fewer servers.
  • Avoid slow servers: remove hosts with long garbage-collection pauses or overloaded network interfaces from rotation automatically.

Hot keys. A celebrity's follower count or a viral user's profile may be read millions of times per second. One cache server cannot serve that. Replicate hot keys to many servers (clients read a random replica), cache them in the API servers' local memory for a second, or serve them from a dedicated hot-key tier. See Cache Failure Modes: Stampedes, Hot Keys and Penetration.

Thundering herds. When a popular list is evicted or a cache server restarts, many requests miss together. The leader cache (Deep Dive 7) collapses concurrent misses for the same key into one database read (request coalescing), and leases prevent stale sets. A restarted cache server can be warmed from a peer before taking traffic.

Caching negative results. Most is-friend checks are false ("is this commenter a friend of the viewer?"). If the list is cached in full, a negative answer comes from the list. If only the newest part is cached (for very long lists), a negative answer requires a database point lookup, which is then cached with a short TTL. Otherwise, negative checks become the main source of database load.

Caching BFS results. Path results for the same pair are reused when the same viewer looks at the same profile several times, or in search result pages where many viewers see the same popular target. Partial traversals (the viewer's two-hop set) are reused across all targets for one viewer, which is the larger win. Both are derived data: they can be stale by minutes without harm, and are discarded on the viewer's own friendship changes.

6. Friend suggestions ("People You May Know")#

The goal. Suggest people the user knows in real life but is not yet connected to. Good suggestions grow the graph, which makes every other product better; bad ones annoy or even harm (suggesting an abusive ex-partner). It is a link prediction problem: given the current graph, which missing edges are most likely to be real relationships?

Candidate generation from the graph. The strongest signal is friends of friends: if Asha and Chen share 12 friends, they very likely know each other. For each user, candidates are the two-hop neighbourhood (tens of thousands of people), scored by graph features:

  • Common neighbours: the number of mutual friends.
  • Adamic–Adar: a weighted count of mutual friends, where each shared friend z contributes 1 / log(degree(z)). A mutual friend with 30 friends is a stronger signal than one with 5,000. From "Friends and Neighbors on the Web" (Adamic and Adar, Social Networks, 2003).
  • Jaccard similarity: mutual friends divided by the union of both friend lists, which normalises for very social users.
  • Personalised PageRank or random walks: short random walks from the user; vertices visited often are close in a structural sense. Twitter's "WTF: The Who to Follow Service at Twitter" (Gupta et al., WWW 2013) described computing follow suggestions with random walks and SALSA on an in-memory graph held on a single large server (the Cassovary library), and Pinterest's Pixie (Eksombatchai et al., WWW 2018) serves real-time recommendations with random walks on a large in-memory graph.

Liben-Nowell and Kleinberg's study of link prediction ("The Link-Prediction Problem for Social Networks", 2003, journal version 2007) compared these measures and found that simple neighbourhood measures such as Adamic–Adar perform remarkably well.

Other candidate sources. Shared schools, workplaces, groups and events; contacts uploaded by the user (with consent) matched against phone numbers and emails; people who viewed the user's profile; geographic proximity. These catch relationships the graph does not show yet, such as a new colleague.

Ranking. Candidates from all sources are scored by a model (gradient-boosted trees or a neural network) trained on outcomes: did the user send a request, was it accepted? Features include the graph scores above, profile similarity, interaction signals, how recently the mutual friendships were formed (a cluster of new mutual friends suggests a new school or job), and the candidate's own acceptance rate. The label is accepted requests, not just sent ones, to avoid optimising for spammy suggestions. See ML System Design and Feature Stores.

Computing friends of friends at scale. For one user with 200 friends of 200 friends each, gathering candidates means reading 200 lists and counting occurrences of each ID: a hash map of up to 40,000 entries, milliseconds in memory. For all 2 billion users daily, it is a large batch job: a self-join of the edge table (for each vertex z, emit all pairs of its neighbours), which produces Σ degree(z)² pairs. With an average degree of 200 and a skewed distribution, that is on the order of 10¹⁴ pairs, far too many. Practical jobs therefore:

  • Skip or sample hubs: a vertex with 5,000 friends produces 25 million pairs, and each pair is weak evidence (Adamic–Adar weighs it down anyway). Sample its neighbours or drop it.
  • Compute only for active users, and only for their top-K candidates, with a per-user cap.
  • Use incremental updates: when Asha and Ben become friends, Ben's friends become candidates for Asha and vice versa: 2 × 200 updates, done nearline.

Serving. The suggestion API reads the user's precomputed list, removes anyone who became a friend, was blocked, or was dismissed since, and returns the top 20 with an explanation ("12 mutual friends", "works at the same company"). Mutual-friend counts shown at serving time are recomputed from cached lists (an intersection of two lists), so they are current.

Safety and privacy. Suggestions can expose sensitive relationships (a therapist's patients, a journalist's sources) through mutual-contact inference. Mitigations: never suggest based on sensitive sources without explicit consent; let users opt out of being suggested; exclude blocked users and people who blocked the viewer in both directions; rate-limit how many suggestions mention any one person; and audit the model for harmful patterns. Treat these as requirements, not polish.

Evaluation. Offline: take a snapshot from a month ago, generate suggestions, and measure recall of the friendships actually formed since (precision at K, recall at K). Online: A/B test suggestion acceptance rate, requests sent per user, accepted friendships per user, and negative feedback (dismissals, reports). The separate case study Design a Recommendation System (Twitter For You) covers candidate generation and ranking pipelines in more depth.

7. A Facebook TAO-style graph cache#

The history. Facebook originally stored social data in sharded MySQL with a large Memcached tier in front, using a look-aside pattern: the PHP application read Memcached, fell back to MySQL on a miss, and invalidated keys on writes. This worked but had problems that the paper "TAO: Facebook's Distributed Data Store for the Social Graph" (Bronson et al., USENIX ATC 2013) describes: graph logic spread across application code, inefficient caching of lists (any change invalidated a whole list, which then had to be reloaded), thundering herds, and difficult read-after-write consistency across regions. TAO replaced the look-aside pattern with a graph-aware read-through and write-through cache, still backed by sharded MySQL. The paper reported that TAO served about a billion reads per second and millions of writes per second, with a read-heavy ratio of roughly 500 reads per write.

The data model: objects and associations.

  • Objects are typed nodes with an ID and key-value data: users, posts, comments, pages, check-ins. An object ID embeds its shard number.
  • Associations are typed directed edges (id1, atype, id2) with a 32-bit time and key-value data: friend, likes, authored, commented_on. Many have an inverse type (likes and liked_by), and TAO writes the inverse edge automatically.
  • Association lists are all associations of a given (id1, atype), ordered by time, newest first. This ordering is the key insight: most social queries want the most recent items (newest friends, latest comments), so lists are served from their head.

The API. A small set of operations, designed for the actual query patterns:

assoc_add(id1, atype, id2, time, data)     # plus inverse, if defined
assoc_delete(id1, atype, id2)
assoc_change_type(id1, atype, id2, newtype)
assoc_get(id1, atype, id2set, high?, low?)  # which of these edges exist (optionally in a time window)
assoc_count(id1, atype)                    # size of the list
assoc_range(id1, atype, pos, limit)        # e.g. newest 50 comments
assoc_time_range(id1, atype, high, low, limit)
obj_get / obj_add / obj_update / obj_delete

There is no general multi-hop query language. Multi-hop work (friends of friends, paths) is done by services that compose these calls, which keeps TAO's behaviour predictable at huge scale.

Architecture.

  • Storage: MySQL databases split into many logical shards; each object and its associations (keyed by id1) live on the shard embedded in the object ID. Each shard has one primary region and replicas in others.
  • Cache tiers: each region has cache servers organised in tiers. A follower tier receives client reads; on a miss, it asks the leader tier, which is the only tier that reads from and writes to the database for a given shard. Within a tier, shards are mapped to cache servers by consistent hashing.
  • Leaders serialise writes for their shard (so updates to a list are applied in order), protect the database from thundering herds (one database read per miss, no matter how many followers ask), and send invalidation or update messages to the followers.
  • Multiple follower tiers per region scale reads horizontally: each tier holds a full copy of the hot data, and clients are pinned to one tier. A hot object can additionally be cached in clients for a short time.

The write path. A write from any region is sent through the follower to the leader for the shard. In a secondary region, the local leader forwards the write to the leader in the primary region, which writes to the primary database. The primary leader updates its cache and returns; the secondary leader updates its own cache from the result (so the writer reads their own write locally), and other followers are updated by invalidation messages. Database replication then carries the change to the secondary database, and the replication stream triggers invalidations in the secondary region's caches as well. The model gives eventual consistency across regions, typically within a second, with read-after-write consistency for the writer's own cache tier.

Lists in cache. TAO caches the head of association lists (for example the newest few thousand entries) plus the count. assoc_range with small offsets is served from cache; deep offsets fall through to the database. assoc_get on a fully cached list answers both positive and negative results from cache; on a partially cached list, the leader can consult the time window (if the edge's time is older than the cached range, ask the database).

Consistency details worth knowing.

  • Inverse edges are written by separate operations on possibly different shards, so there is a window where the forward edge exists without the inverse. TAO accepts this and repairs it with background jobs.
  • Versioning: cached items carry version numbers so that an invalidation for an older version does not delete a newer value, and a slow fill cannot overwrite a newer value.
  • Critical reads can be marked to go to the primary region, for example for authentication or immediately after a security-sensitive change.

What TAO teaches for an interview. You do not need a graph database to serve a social graph at the largest scale. You need: a simple, sharded, durable store; a cache that understands lists and counts and applies writes in place; a leader per shard to order writes and collapse misses; replication across regions with read-after-write for the writer; and a small, carefully chosen API. Multi-hop features are built as separate services on top. See Landmark Distributed Systems Papers for related systems papers.

Related systems. Facebook's Unicorn ("Unicorn: A System for Searching the Social Graph", Curtiss et al., VLDB 2013) indexes edges as posting lists (for example friend:123 lists all friends of user 123) and supports set operations such as and, or, difference and a special apply operator that runs a query over the results of another query (friends of my friends who live in a city). It powered typeahead and Graph Search. LinkedIn has described its in-memory graph database, LIquid, for serving connection degrees and graph queries. Twitter's FlockDB (2010) stored follow edges in sharded MySQL with a focus on adjacency-list operations, very much in the same spirit.

8. Supernodes and follow graphs#

The problem. Friendship is capped (5,000 on Facebook), so friend lists are bounded. Follows are not: a celebrity may have 100 million followers. If the design supports follows (as Instagram, X and Bluesky do), the degree distribution follows a power law with a very heavy tail, and a handful of vertices hold a huge share of edges.

Effects on each part of the design.

  • Storage: a 100-million-entry list on one shard is about 2 GB of edge rows, plus indexes. Range scans still work (newest first, with a time index), but the shard holding several such lists becomes large and hot. Mitigation: split very large lists across multiple sub-shards by ID range or hash of id2, with an index entry that points to them.
  • Counts: the follower count of a celebrity changes hundreds of times per second. Increment a sharded counter (several count rows, summed on read) or buffer increments in the cache and flush periodically. See Pattern: Dealing with Contention.
  • Is-follower checks: "does Asha follow the celebrity?" must be answered from Asha's side (her follows list is small) rather than the celebrity's followed_by list. Store both directions and always check the smaller side.
  • BFS: a supernode in a frontier adds millions of vertices in one step. Path services skip or sample supernodes, or treat them as landmarks with precomputed distances, because paths through a celebrity rarely mean anything socially ("you both follow a pop star").
  • Suggestions: co-following a celebrity is weak evidence; Adamic–Adar style weighting discounts hubs automatically, and hub sampling bounds the work.
  • Feed fan-out: as in the separate case study Design a News Feed (Facebook / Twitter), celebrity posts are pulled at read time instead of pushed into 100 million timelines.

Directed graphs change the queries. With follows, "degree of separation" usually follows directed edges or is defined on the mutual-follow subgraph. Friend suggestions become "who to follow", where the candidates are accounts followed by the accounts you follow, and random-walk methods (as in Twitter's WTF and its successor systems) work well.

Hot edge lists in cache. A celebrity's follower list is rarely read in full, but its head (newest followers) and its count are read often. Cache the head and count, replicate them to many cache servers, and serve deep pages from the database at a lower priority. Writes to the head (new followers arriving at hundreds per second) are batched in the leader cache.

A different partitioning for processing. For offline jobs on the follow graph (PageRank, community detection), vertex-cut partitioning (Deep Dive 4) spreads a celebrity's edges across machines, so no worker becomes a straggler. The serving system keeps edge-cut storage for fast one-hop reads; the processing system repartitions the snapshot.

9. Keeping both sides of a friendship consistent#

The issue. A friendship is two directed edges on two shards. Writing both atomically requires a distributed transaction; writing them separately allows a window (or, after failures, a permanent state) where A lists B but B does not list A. Which is acceptable?

Option 1: two-phase commit across the two shards. A coordinator asks both shards to prepare the insert, then commits both. It guarantees symmetry, but it costs two extra round trips, holds locks across a network hop, and blocks if the coordinator fails at the wrong moment. At 20,000 friendships per second spread over hundreds of shards, 2PC is feasible technically, but it couples the availability of every friendship write to two shards and a coordinator. See Distributed Transactions: 2PC, Sagas and Outbox.

Option 2: write one side, then the other, reliably (the large-network choice).

  1. Write the first edge (on the acceptor's shard) together with an outbox row in the same local transaction, or rely on the database's change log.
  2. A worker reads the outbox or log and writes the inverse edge on the other shard, retrying until it succeeds. The write is idempotent (insert-if-absent).
  3. Mark the outbox row done.

This is the transactional outbox pattern. It guarantees that the inverse edge is eventually written as long as the first write committed, without distributed locking. The asymmetry window is the worker's delay, normally milliseconds to a second. See Change Data Capture and the Outbox Pattern.

Option 3: single canonical record. Store one record per friendship keyed by (min(A, B), max(A, B)) on the shard of the smaller ID, and maintain each user's list as a derived index. This makes the friendship itself atomic, but listing B's friends then needs the index on B's shard, which is the same two-write problem moved to the index. It does help as an authoritative tiebreaker for repairs.

Repairs. Bugs, partial failures and manual fixes can still leave one-sided edges. A background consistency checker scans shards (incrementally, by time range), and for each friendship edge A to B checks that B to A exists. Mismatches are repaired from the authoritative source (the friend request record, or the canonical record) and counted as a metric. The TAO paper notes the same property: a forward and inverse association are written separately, a failure can leave a hanging association, and an asynchronous job repairs it.

Ordering hazards. Consider "add friend" followed quickly by "unfriend". If the inverse-edge worker processes them out of order (delete first, then add), the edge would wrongly reappear on one side. Defences:

  • Process outbox entries for the same friendship pair in order (partition the log by the pair key).
  • Use versioned writes: each change carries a timestamp or version, and an older change never overwrites a newer state. A delete leaves a tombstone with its version so that a late add with an older version is ignored.

Unfriending and blocking. Unfriend removes both edges, through the same outbox mechanism. Blocking is stronger: it removes the friendship, cancels pending requests in both directions, and writes a blocks edge (on the blocker's shard) and a blocked_by edge (on the blocked user's shard). Every query that could show one user to the other checks both, from the cache. Because a missed block is a safety problem, block checks are among the reads allowed to go to the primary region when freshness is in doubt.

Multi-region writes. Each shard has a primary region; all writes for it go there. Two users in different continents becoming friends cause writes in two primary regions (one per user's shard). That is fine: each write is local to its shard's primary, and the outbox carries the inverse across regions. The cost is one cross-region round trip for users whose shard is primary elsewhere, which is why users' shards are placed in their home region when possible. See Consistency Models.

Counts under concurrency. Each count row lives on the same shard as its list and is updated in the same local transaction as the edge, so a list and its count never disagree on one shard. Across the two sides they converge as the inverse edges do.

10. Mutual friends and other set queries#

Mutual friends is the intersection of two friend lists. It appears everywhere: on profiles ("12 mutual friends"), in suggestions, in search results, in friend request screens. It is also a building block for degree-2 checks and suggestion features.

Algorithms for intersection. With both lists in memory:

  • Merge of sorted lists: walk both sorted arrays together; O(m + n). Two lists of 200 IDs: about 400 steps, under a microsecond.
  • Hash probe: put the smaller list into a hash set, probe with the larger: O(m + n) with larger constants, but works for unsorted lists.
  • Galloping (exponential) search: when one list is much smaller (50 versus 5,000), for each element of the small list, binary-search forward in the large list: O(m log(n/m)). Useful when one side is a supernode.
  • Bitmaps: for very large lists (followers of popular accounts), compressed bitmaps (Roaring) intersect at memory bandwidth speed.

Where to compute it. Fetch both lists from the cache (two reads, possibly on two servers) and intersect in the API server. For a page showing mutual counts for 50 people, that is 51 list fetches (the viewer's and 50 others'), batched by cache server, plus 50 intersections: milliseconds. Precomputing mutual counts for all pairs is impossible (10¹⁸ pairs); precomputing them for the viewer's two-hop set (as part of the suggestion pipeline) is useful for suggestions only.

Showing which friends are mutual. The list of mutual friends should prefer friends that are meaningful to the viewer: closest friends first (by interaction strength), then others. That needs a ranking step on the intersection, using per-viewer affinity scores from the feed's ranking system.

Privacy. If B hides their friend list, the viewer should not be able to infer it. Products differ on whether mutual friends are still shown (they are, after all, the viewer's own friends). The rule must be applied consistently across mutual-friend lists, paths and suggestions, otherwise one feature leaks what another hides. A good practice: implement privacy checks in one library used by every graph feature.

Other set queries.

  • Friends who live in a city or work at a company: intersect the friend list with an attribute index (users by city). This is exactly what Unicorn's posting lists and set operators were built for.
  • Friends who liked a post: intersect the viewer's friend list with the post's liked_by list. When the like list is huge (a viral post), probe the viewer's friends against the like list instead (200 assoc_get checks, batched).
  • Friends of friends who did something: the apply style query: for each friend, fetch their list, union, then intersect with an attribute set. Bounded by sampling and limits.

11. Offline graph processing#

Many graph features need whole-graph computation: friend-of-friend candidates, two-hop neighbourhoods, landmark distances, partitioning, community detection, PageRank-like scores, fraud clusters, and statistics such as the distance distribution. These run offline on a snapshot of the graph, not on the serving system.

The snapshot. Each day (or more often), dump the association tables of all shards to a distributed file system or object storage as columnar files of (id1, id2, time). 400 billion edges × 16 bytes is about 6.4 TB uncompressed, and about 2–3 TB with columnar compression and delta encoding. Change logs between snapshots allow incremental jobs. See Data Pipelines, Warehouses and Lakes.

The vertex-centric model (Pregel). Google's Pregel ("Pregel: A System for Large-Scale Graph Processing", Malewicz et al., SIGMOD 2010) introduced the think like a vertex model: computation proceeds in supersteps; in each, every active vertex reads messages sent to it in the previous step, updates its state, and sends messages along its edges. A barrier separates supersteps. Distributed BFS fits naturally: in superstep k, vertices discovered at distance k send their distance plus one to neighbours; each vertex keeps the minimum it has received. Apache Giraph is an open-source implementation, and Facebook described scaling it to graphs with over a trillion edges ("One Trillion Edges: Graph Processing at Facebook-Scale", Ching et al., VLDB 2015). Spark's GraphX and similar libraries offer the same model on general data platforms.

# Pregel-style multi-source BFS (e.g. distances from 100 landmarks at once)
superstep 0: each landmark L sets dist[L] = 0 and sends (L, 1) to its neighbours
superstep k: for each received (L, d):
                 if dist[L] at this vertex is unset:
                     dist[L] = d
                     send (L, d + 1) to all neighbours
             vertices with no new labels vote to halt
stop when every vertex has halted and no messages are in flight

Each superstep is one pass over the edges. For a small-world graph, about 6–10 supersteps finish the BFS from all landmarks, because the diameter of the giant component is small (with a long tail of a few far-away vertices). Message volume per superstep is bounded by edges × active labels.

Precomputing BFS results. The primer suggests batch-computing complete or partial BFS traversals offline and storing them in a NoSQL database for fast lookups. In this design that becomes:

  • Two-hop neighbourhoods (or their Bloom filters) for active users: computed by a join of the edge list with itself, restricted to active sources, with hub sampling; stored in a key-value store keyed by user. See Apache Cassandra in Practice.
  • Landmark distances: a multi-source BFS as above, stored as a compact vector per user.
  • Candidate lists for suggestions: Deep Dive 6.

These tables are versioned by snapshot date and swapped atomically, so the serving path always reads a complete version.

Incremental maintenance. Recomputing everything daily makes results up to a day stale. Nearline jobs consume the change log and update affected users: when A and B become friends, A's two-hop set gains B's friends and B's gains A's, and each of their friends' two-hop sets gains the other. That is up to 2 × 200 + 2 × 200 updates, a few hundred writes per new friendship, which at 6,000 friendships per second is a couple of million writes per second. Real systems limit incremental maintenance to the most important structures (the two users themselves) and leave the rest to the daily batch. See Batch vs Stream Processing.

Other offline jobs.

  • Graph partitioning (Deep Dive 4): label propagation over the snapshot, producing new shard assignments that are applied gradually.
  • Community detection for groups suggestions and spam detection: Louvain modularity optimisation or label propagation.
  • Fraud and fake-account clusters: fake accounts tend to form dense clusters with few links to real users; algorithms in the spirit of SybilRank (Cao et al., NSDI 2012) propagate trust from known real users with short random walks and flag accounts that receive little.
  • Analytics: degree distributions, growth, distance distributions with HyperANF (Deep Dive 3).

12. People search ranked by the graph#

The primer frames this problem as "a user searches for someone and sees the shortest path to them". People search ties the graph to search: typing "Ben" should return the Bens you know first, then Bens your friends know, then everyone else.

Two-stage retrieval.

  1. Personal candidates first. Prefix-match the query against the names of the searcher's friends (about 200 names, cached with the friend list) and their two-hop neighbourhood (tens of thousands of names, if precomputed). This takes microseconds and covers most searches, because people mostly look for someone they know.
  2. Global candidates. A search index over all user names (2 billion entries, sharded) returns matches by prefix and popularity. Facebook's Unicorn served this kind of typeahead with posting lists for name prefixes combined with social filters.

Ranking by social distance. Merge personal and global candidates and score them: 1st degree highest, 2nd degree next (weighted by mutual-friend count), then strong non-graph signals (same city, same school), then global popularity. The degree is computed with the cheap checks from Deep Dive 3 for the top 50 candidates only, not for every match. The separate case study Design Search Autocomplete (Typeahead) covers prefix indexes and typeahead serving in depth.

Showing the path. For a selected result, the path service computes one shortest path within the depth and time budget and shows it ("You → Asha → Ben"). The result carries a short TTL in the path cache, because the same searcher often opens the same profile again.

Latency budget. Typeahead must answer each keystroke in under about 100 ms end to end: about 10 ms for the personal candidates, 30–50 ms for the global index in parallel, 10 ms for merging and the cheap degree checks, and the rest for network. The full path is fetched only after a result is chosen.

Privacy. Users can restrict who can find them by search (everyone, friends of friends, friends only). That setting is a graph predicate evaluated per candidate: "is the searcher within distance 2 of this candidate?", which is again the two-hop check.

Bottlenecks and Failure Modes#

Failure / hotspotImpactMitigation
Cache server failureMisses for its keys flood leaders and databasesConsistent hashing spreads keys; leaders coalesce misses; warm replacements from peers; multiple follower tiers
Leader cache for a shard downWrites and misses for that shard stallFail over to a standby leader; followers serve stale reads meanwhile; clients retry with backoff
Database shard primary failureWrites to that shard fail; reads continue from cache and replicasPromote a replica; outbox entries queue and replay; reads unaffected for cached data
Celebrity or viral user hot keyOne cache server overloadedReplicate hot keys, short client-side caching, dedicated hot-key tier, sharded counters
BFS frontier explosion through a supernodePath search slow or out of memorySkip or sample supernodes, expand the smaller frontier, depth and time limits, precomputed landmarks
Fan-out page loads hitting many serversHigh tail latencyBatching per server, hedged requests, partial results, locality-aware placement
One-sided friendship after a failureUser appears in one list but not the otherTransactional outbox with retries, idempotent inverse writes, background consistency checker
Out-of-order add and removeDeleted friendship reappears on one sideOrder changes per pair key, versioned writes and tombstones
Cross-region replication lagStale lists in other regions, read-your-writes broken for travellersRoute recent writers to the primary region, local write-through in the writer's tier, version checks
Stale precomputed two-hop sets or suggestionsWrong degree labels, suggesting existing friendsLive checks for degree 1, filters at serving time, nearline updates for changed users
Block not applied everywhereSafety problem: blocked user visible in paths or suggestionsSingle privacy library, block checks in every query, primary-region reads for blocks when in doubt
Offline job overload on productionSnapshot dumps slow serving databasesDump from dedicated replicas, rate-limit exports, incremental change-log based snapshots

What Interviewers Expect#

Mid-level. Store friendships as adjacency lists sharded by user ID, with two directed edges per friendship. Explain BFS for shortest paths and why it blows up beyond two hops. Add a cache for friend lists and a lookup service mapping users to shards. Expose clear APIs for listing friends, checking friendship and finding a path with a depth limit.

Senior. Quantify the graph (vertices, edges, bytes, read rates) and the BFS frontier growth. Use bidirectional search with batched expansions per shard and per level, expanding the smaller frontier, with depth and time budgets. Cover mutual friends with set intersection and degree-2 checks. Design the cache around edge lists and counts with write-through updates, hot-key handling and tail-latency defences. Handle the two-sided write with an outbox and repairs. Generate friend suggestions from friends of friends with Adamic–Adar-style weighting and a ranking model.

Staff and above. Explain why large networks use a TAO-style architecture (sharded MySQL, leader and follower cache tiers, association API, regional replication with read-after-write) rather than a general graph database, and where a graph database would still fit. Discuss graph partitioning (geography, label propagation, Social Hash) and its real benefits for fan-out and caching. Use small-world facts to drive product limits (exact up to 3, approximate beyond with landmarks), and reason about precomputation versus query-time work with storage numbers. Treat privacy and safety (blocks, hidden lists, sensitive inference) as invariants enforced by one library. Address supernodes, offline graph processing with Pregel-style jobs, and multi-region consistency.

Deep Dive: Sizing every tierShow

All figures use the Capacity Estimation assumptions: 2 billion users, about 400 billion directed edges, tens of millions of graph reads per second, tens of thousands of writes per second.

Edge store. About 8 TB of raw edge data, about 16 TB with indexes and engine overhead, times three replicas plus one copy per extra region: 50–80 TB on flash. At 16,384 logical shards, each holds about 1 GB of primary data; at 500 hosts, each host serves about 32 logical shards (about 32 GB of data per replica), which mostly fits in its buffer pool. Writes: 40,000 edge writes per second at peak plus counts and outbox rows, about 100–200 small transactions per second per host.

Cache tier. Active users' lists (1 billion × about 3 KB) plus counts and objects: about 4 TB per follower tier. With 256 GB servers at about 70% usable, roughly 25 servers per terabyte, so about 100 servers per full tier. Read rate of 30 million per second (each a batched multi-get of a few keys): with a single server handling about 1 million simple operations per second, a region needs 30 or more servers just for throughput. Memory, not throughput, is the binding constraint, and several follower tiers per region multiply capacity for reads. Leaders: one per shard group, a few dozen servers per region.

Lookup service. The logical-shard map is tens of thousands of entries, kilobytes in size, cached in every process. A per-user directory (if used) is 16 GB, replicated on a few servers per region and cached partially by clients.

Path service. 230,000 degree labels per second, mostly answered by one or two list reads and an intersection (about 50 µs of CPU each): about 12 CPU-seconds per second. 10,000 full path searches per second at about 5 ms of CPU each (one batched third level with 200 list reads and set operations): 50 CPU-seconds per second. A few dozen servers per region with headroom, plus the cache reads they cause (about 200 list reads per path search, so 2 million cache reads per second: a significant share of cache traffic, which is why precomputed two-hop sets pay off).

Precomputed data. Two-hop Bloom filters for 1 billion active users at 36–72 KB: 36–72 TB, in a key-value store on flash; read about 230,000 times per second. Landmark vectors: 200 GB. Suggestions: 2 billion × 200 candidates × 12 bytes ≈ 5 TB.

Offline. Daily snapshot of 2–3 TB compressed. Friend-of-friend candidate generation with hub sampling: on the order of 10¹³ pair emissions, which is a large but routine job on a cluster of thousands of cores, taking a few hours. Landmark BFS: about 10 supersteps over 400 billion edges with 100 labels, also a few hours.

Network. A path search that reads 200 lists of 3 KB moves about 600 KB; at 10,000 per second, 6 GB/s across the path service fleet. Feed and privacy batches dominate cache network traffic: 30 million reads per second × 3 KB average is about 90 GB/s across a region's cache tier, about 1 GB/s per server on 100 servers, which fits 25 Gbps network interfaces with room to spare. This is one more reason caches store compressed lists and APIs return only the needed slice.

Takeaway. The design is bound by memory for caching active lists and by fan-out latency, not by database write throughput.

Deep Dive: Real-world social graph systems comparedShow

Facebook: TAO, Unicorn and Social Hash. TAO stores objects and associations in sharded MySQL, with leader and follower cache tiers per region and an association-list API (Bronson et al., 2013). Unicorn indexes edges as posting lists for search and typeahead with set operators (Curtiss et al., 2013). Social Hash assigns related users to the same groups to cut fan-out (Shalita et al., 2016). Giraph handles offline graph processing at the trillion-edge scale (Ching et al., 2015). The overall lesson: simple storage, smart caching, separate systems for search and batch processing.

LinkedIn. Connection degree (1st, 2nd, 3rd) is shown on every profile and search result, so the graph distance service is a core product dependency. LinkedIn has written about an in-memory distributed graph serving system and, more recently, LIquid, a graph database built in-house to serve the economic graph with low-latency multi-hop queries. Its workload is closer to this case study's path queries than Facebook's mostly one-hop reads.

Twitter (X). FlockDB (2010) stored the follow graph as sharded adjacency lists in MySQL, optimised for huge follower lists and set operations such as intersections for "followers you know". For recommendations, the WTF system ran random walks on an in-memory copy of the graph on large single machines with the Cassovary library (Gupta et al., 2013), and later GraphJet (Sharma et al., VLDB 2016) maintained a real-time bipartite user-tweet interaction graph in memory for recommendations.

Pinterest. Pixie (Eksombatchai et al., 2018) runs biased random walks over a graph of pins and boards held entirely in memory on large machines, serving real-time recommendations. It shows that a well-pruned graph can be served from a single machine's memory, with replicas for throughput.

General-purpose graph databases. Neo4j (native graph storage, Cypher query language), JanusGraph (graph layer over Cassandra, HBase or Bigtable), Amazon Neptune (managed, with Gremlin and openCypher), TigerGraph and Dgraph. They are excellent for knowledge graphs, fraud investigation, recommendations on moderate graphs, and analytical multi-hop queries. At the largest social networks, the serving workload is dominated by simple one-hop reads at enormous rates, where a sharded store with a graph-aware cache wins on cost and predictability.

SystemStorageQuery styleStrength
Facebook TAOSharded MySQL plus leader and follower cachesOne-hop association APIBillions of reads per second, read-after-write
Facebook UnicornIn-memory posting listsSet operations, applyTypeahead and graph search
LinkedIn LIquidIn-memory graph databaseMulti-hop queriesConnection degrees, graph queries
Twitter FlockDBSharded MySQLAdjacency lists, set operationsHuge follower lists
Twitter WTF and CassovarySingle-machine in-memory graphRandom walksFollow recommendations
Neo4j and similarNative graph or graph over wide-columnCypher or Gremlin traversalsRich multi-hop queries on moderate graphs
Deep Dive: A 45-minute interview planShow
MinutesFocusWhat to say and draw
0–5ClarifyMutual friendship or follow? Which queries: list friends, check friendship, degree label, full path, mutual friends, suggestions? Path length limit? Freshness after a new friendship? Privacy rules?
5–10EstimateUsers, average and maximum degree, edges, bytes per edge, read and write rates; show that the graph does not fit on one machine and that BFS frontiers grow by about 100–200 times per hop
10–20High-level designClients, API, graph service, lookup service, sharded edge store, cache tier, path service, precompute jobs; walk one write and one path query
20–35Deep divesPick two or three: bidirectional BFS with batching per shard; caching and hot keys; the two-sided write; degree labels with precomputed two-hop sets or landmarks; partitioning for locality
35–42Scale and failuresSupernodes, cache server loss, cross-region lag, one-sided friendships, block enforcement
42–45Wrap-upRestate the trade-offs: exact search up to three hops, approximate beyond, sharded store plus cache instead of a general graph database at this scale

Opening line that works. "The graph is huge but each query touches a tiny part of it, so I will store adjacency lists sharded by user, serve them from memory, and keep every query to a bounded number of batched hops."

Where candidates lose time. Writing full BFS code without asking whether it is wanted; designing a general graph database from scratch; skipping the explosion of the third hop; forgetting that a friendship is two directed edges that must stay in sync.

What to draw. Draw the frontier growth as three circles (200, 40,000, 8,000,000) next to the bidirectional version (200 and 40,000 meeting in the middle). That single picture explains why the design limits depth, searches from both ends and batches by shard.

Deep Dive: Follow-up questions and strong answersShow

"Why not just use Neo4j?" A native graph database is excellent when the graph fits on one cluster with rich multi-hop queries. At billions of users, the workload is mostly one-hop list reads at tens of millions per second. A sharded relational or wide-column store with a graph-aware cache gives predictable latency, mature operations, cheap capacity and simple failure handling. Multi-hop queries spanning shards are slow in any system, so the design limits them anyway. A graph database still fits for internal tools, fraud investigations and moderate-size graphs.

"How do you find the path between two random users in under a second?" Run bidirectional BFS: expand the smaller frontier, batch list reads per shard per level, and stop when the frontiers meet. Most pairs meet within three or four hops, about 40,000 list reads in the worst case. Add a time budget and a hop limit; beyond them, return "more than three degrees" or an approximate distance from landmarks.

"What if both users have 5,000 friends?" The first level is already 5,000 reads on each side. Expand only one side at a time (the smaller), sample or cap frontier members, and skip supernodes when expanding, because they tend to connect to everyone and add little information beyond the first hop.

"How do you show 1st, 2nd, 3rd on every search result?" Check first degree with a point read. For second degree, intersect the viewer's friend set with the target's friend set, or check the target in a precomputed two-hop Bloom filter of the viewer. Mark third degree as "3rd+" when a cheap check fails, rather than running a full search per result. Batch all results in one request.

"A friendship is accepted, but one side's list fails to update. What happens?" The write goes to the requester's shard with an outbox row in the same transaction. A relay applies the inverse edge idempotently with retries. A periodic checker compares both directions and repairs. Clients may see a one-sided state for seconds, which is acceptable; they never see a permanent mismatch.

"How does the cache stay consistent with the database?" Writes go through the leader cache for the shard, which updates the database and then the cache, and sends invalidations to followers. Followers serve reads and ask the leader on a miss. A user's own region gets read-after-write by routing their writes through local tiers and applying the change immediately in their follower cache. Other regions catch up within replication lag.

"How would you suggest friends?" Generate candidates from friends of friends, weighting each mutual friend by the inverse log of their degree (Adamic–Adar), plus signals such as shared schools, workplaces, contact uploads and location (with privacy limits). Rank with a model trained on accepted suggestions. Precompute offline, refresh nearline for users with new friendships, filter at serving time for blocks and existing friends.

"How do you shard to reduce cross-machine hops?" Partition users so friends share shards: by country or region first, then by a community algorithm such as label propagation, balanced by size. The lookup service stores the map. Facebook's Social Hash work reported large reductions in fan-out for some workloads with this approach.

"What happens when a celebrity's account is the target of many queries?" Their edge list is a hot key. Replicate it across several cache servers, cache it briefly in the clients, store counts separately so most reads do not fetch the list, and treat celebrities as followable accounts with one-directional edges rather than mutual friendships.

"How would you remove a user?" Delete or tombstone their object, then remove all incident edges in both directions asynchronously. A deletion job reads their list, deletes the inverse edges shard by shard, then removes the forward list. Caches are invalidated as edges change. Offline snapshots respect deletion within the retention policy.

Deep Dive: Graph database vs sharded store plus TAO-style cacheShow

The choice is not ideological. It follows from the query mix, the graph size and the team's operational skills.

QuestionGraph databaseSharded store plus graph cache
Typical queryMulti-hop pattern matching, path queriesOne-hop lists, counts, existence checks
Graph sizeUp to billions of edges on a well-sized clusterHundreds of billions to trillions of edges
Read rateThousands to hundreds of thousands per secondTens of millions to billions per second
Multi-hop across machinesHandled by the engine but slow when it crosses partitionsDone in the application with explicit batching and limits
OperationsFewer engineers know it; vendor toolingFamiliar SQL or wide-column operations
Schema flexibilityRich labels and properties on edgesFixed association rows with a small data blob
Best fitFraud rings, knowledge graphs, internal analysis, moderate social appsPlanet-scale social graphs

Why multi-hop is hard everywhere. Index-free adjacency (each node points directly to its neighbours) makes a hop a pointer chase in memory, which is fast on one machine. Once the graph is partitioned, a hop crosses the network, and no storage engine hides a network round trip. Partitioning that keeps communities together helps, but social graphs have no clean cuts: a large share of edges always crosses partitions. So the real decision is where to put the hop logic. A graph database puts it in the engine; the sharded design puts it in a path service that can batch, cap, sample and time-limit each step with product knowledge.

A pragmatic hybrid. Many companies run both: a sharded store with caches as the system of record for the serving path, and an exported copy loaded nightly into a graph database or a graph processing engine for analytics, fraud investigations and experimentation. The export is one-way, so the serving path never depends on the analytical system.

When a startup should pick a graph database. With 10 million users and 500 million edges, the whole graph fits in the memory of a few large machines. A graph database replicated for availability answers friend-of-friend queries in milliseconds and needs fewer engineers. Move to a sharded design when the edge count or read rate outgrows a single cluster, using the same entities and APIs so clients do not change.

Deep Dive: The mathematics of small worldsShow

Why paths are short. Imagine every person has k friends chosen at random. After h hops, the number of people reached grows like k to the power h. With k = 100, three hops reach 1 million people and five hops 10 billion, more than the world's population. Real friendships cluster (friends of friends are often friends), which slows this growth, but a few long-range ties (a friend who moved abroad) are enough to keep paths short. Watts and Strogatz (1998) showed that adding a small fraction of random long-range edges to a clustered lattice makes the average path length drop sharply while clustering stays high. They called these networks "small worlds".

Measured distances. Milgram's 1967 letter-forwarding experiment suggested about six steps between people in the United States, which is where "six degrees" comes from. On the 2011 Facebook graph of about 721 million users, Backstrom, Boldi, Rosa, Ugander and Vigna ("Four Degrees of Separation", 2012) measured an average distance of about 4.74 hops, or about 3.74 intermediaries. They computed this with HyperANF, which estimates the neighbourhood function using HyperLogLog counters per node instead of running BFS from every node.

Degree distribution. Social graphs have heavy-tailed degree distributions: most people have a few hundred friends, a few have thousands, and follow graphs have accounts with hundreds of millions of followers. Heavy tails matter in two ways. First, hubs shorten paths, so searching through hubs finds paths quickly (the primer's "start from people with many friends" idea). Second, hubs create load and frontier explosions, so they need special handling in storage and search.

The friendship paradox. Feld (1991) observed that, on average, your friends have more friends than you do. The reason is that people with many friends appear in many friend lists, so a randomly chosen friend is biased towards high degree. For this design, it means friend-of-friend expansion grows faster than the average degree suggests: the second level is often much larger than 200 × 200 = 40,000 when the first level contains a few well-connected users.

Worked example: frontier sizes. Assume an average degree of 200, a clustering overlap of about 40% at the second hop and a high-degree bias of 1.5 times from the friendship paradox. Level 1: 200 people. Level 2: 200 × 200 × 1.5 × 0.6 ≈ 36,000 unique people. Level 3: if expanded, about 36,000 × 300 × 0.3 ≈ 3 million unique people after heavy overlap. A one-sided search to depth 3 reads 36,000 lists (about 108 MB at 3 KB each). A bidirectional search to total depth 4 reads about 200 lists on each side plus one second level, about 36,000 lists in the worst case and usually far fewer, because it expands the smaller side and stops early.

Why landmarks work. Hubs sit close to almost everyone. If d(u, L) is the distance from user u to landmark L, the triangle inequality gives |d(u, L) − d(v, L)| ≤ d(u, v) ≤ d(u, L) + d(L, v). With about 100 well-chosen landmarks, the upper bound is often exact or one hop off for social graphs, which is why it gives a good "about 4 hops" estimate at the cost of 100 small integers per user.

Deep Dive: Privacy, blocking and abuseShow

Graph data is sensitive. A friend list reveals family, employers, religion, health communities and political ties. Studies have shown that sensitive attributes can be inferred from friends alone. Treat the graph as personal data: minimise who can read it, log access, and honour deletion requests.

Visibility rules. Users may hide their friend list, hide specific connections, or restrict who can send requests (for example friends of friends only). Every API that returns graph data (lists, mutual friends, paths, degree labels, suggestions) must apply these rules. Put them in one privacy library called by every service, so rules cannot drift. Path search must not reveal a hidden edge, even indirectly: if Bob hides his friends, a path "you, Bob, Carol" leaks the Bob–Carol friendship. Either skip hidden edges as intermediate hops or show only the degree label without the people.

Blocking. A block must hide the blocker from the blocked user everywhere: search, suggestions, mutual friends, paths, comments and messages. Store blocks per user in both directions (who I block, who blocks me) so checks are point reads. Read blocks from the primary region when freshness is critical, because a stale cache that lets a blocked harasser see a profile is a safety failure, not just a consistency glitch.

Scraping and enumeration. Friend lists, mutual-friend counts and path queries can be abused to reconstruct the graph. Rate-limit per account and per IP, cap list sizes per request, require authentication, detect sequential ID access, and return coarse labels instead of exact paths to unknown viewers. Use non-sequential public IDs so enumeration is harder.

Fake accounts and spam requests. Spam accounts send many friend requests to strangers. Signals: high request rate, low acceptance rate, few mutual friends with targets, new account age, many reports. Throttle requests per day, require mutual friends or phone verification for heavy senders, and down-rank suspicious accounts in suggestions. Graph structure also helps detection: fake account clusters are densely linked to each other but weakly linked to real users. SybilGuard (Yu et al., 2006) and SybilRank (Cao et al., 2012) use random walks or trust propagation from known-good seeds to flag such clusters.

Data retention and deletion. Account deletion removes all edges in both directions. Offline snapshots and derived data (suggestion candidates, landmark labels, two-hop filters) must be rebuilt or purged within the policy window, so derived stores should carry a snapshot date and be regenerated regularly rather than patched forever.

Key Takeaways#

  • A social graph is two simple things at huge scale: user objects and directed edges. Store friendships as two directed edges, as adjacency lists sharded by the source user, with counts stored separately.
  • Most traffic is one-hop: list friends, check friendship, count friends. Serve these from a large graph-aware cache with write-through updates, coalesced misses and hot-key replication. Memory for active lists is the main cost.
  • Multi-hop queries explode: each hop multiplies the frontier by about 100–200 times. Use bidirectional BFS that expands the smaller frontier, batch list reads per shard per level, and set depth and time budgets.
  • Do not compute paths for every request. Answer first and second degree exactly with point reads and set intersections, precompute two-hop filters and landmark distances offline, and show "3rd+" or an approximate distance beyond that.
  • A lookup service maps users to logical shards. Partitioning by region and community keeps friends together and cuts fan-out; logical shards make rebalancing a metadata change.
  • A TAO-style architecture (sharded SQL, leader and follower cache tiers, an association API, asynchronous regional replication with read-after-write for the writer) beats a general graph database at planet scale. A graph database is the right choice for smaller graphs and rich analytical queries.
  • The two-sided write is a consistency problem: use a transactional outbox with idempotent inverse writes and a background checker, so mismatches heal within seconds.
  • Supernodes break naive designs. Model celebrities as follow edges, sample or skip hubs in search, shard huge lists, and cache counts.
  • Friend suggestions come from friends of friends weighted by mutual-friend strength (Adamic–Adar), random walks and a learned ranker, computed offline and filtered at serving time.
  • Privacy and blocking are invariants, not features. Enforce them in one library on every graph read, including paths and suggestions, and protect the graph against scraping and fake accounts.