Most candidates, asked to build “the thing that powers friend suggestions,” reach for a graph database and move on. Then the interviewer asks the only question that matters: “You have 3 billion users and 400 billion edges. A single who-knows-whom query touches a user’s friends-of-friends. Walk me through exactly which bytes get read, from which machine, and how you keep it under 10ms.” That is not a database question. That is a storage-layout and traversal-execution question, and the answer is an engine that holds a compressed adjacency list in RAM, sharded across a fleet, with a BFS executor that never touches disk and never scans a table.

This post designs that engine. Not the whole social network, not the feed, not profiles. The engine: given a graph of billions of nodes and edges, answer “are A and B within k hops” and “who are B’s best second-degree candidates” in real time. The product (LinkedIn’s “People You May Know,” Facebook’s friend suggestions) sits on top of it and calls it. I am building the layer underneath, because the layer underneath is where every interesting constraint lives.

Functional Requirements (FR)

In scope:

  • Edge storage. Store a social graph as nodes (users) and edges (symmetric “friend” or directed “follow” relationships). Support edge insert, edge delete, and a node’s full neighbor list read.
  • Who-knows-whom (distance query). Given two user IDs A and B and a bound k, return whether B is reachable from A within k hops, and the actual distance (1, 2, 3, or “beyond k”). This is the hot path.
  • Neighbor expansion. Given a user and a hop count, enumerate the reachable set (used by suggestions and mutual-friend counting).
  • Second-degree suggestions. For a user U, return a ranked list of candidate users at distance 2, scored primarily by the count of mutual connections (common neighbors). This is “People You May Know” reduced to its graph core.
  • Mutual-connection count. Given A and B, return how many common neighbors they share. This powers both the suggestion score and the “14 mutual friends” label.

Explicitly out of scope (naming it means I own the boundary):

  • The product UI, the ranking model’s non-graph features (same school, same employer, profile co-views). The engine returns graph candidates and mutual counts; a downstream ranker adds those features. I will say where the handoff is.
  • Profile storage, authentication, the news feed, messaging. Each is a separate system that calls this one.
  • Edge metadata beyond a type tag and timestamp. No per-edge payloads, no weighted edges in v1 (I note where weights would go).
  • Graph analytics (PageRank, community detection, shortest-path over the whole graph). This engine does bounded local traversal, not global batch analytics. Global analytics is an offline Spark/Giraph job on a dump, not an online query.

The one decision that drives the entire design: this is a read-dominated, latency-bound, bounded-traversal engine, and the graph is too big to traverse from disk. Every hard choice below follows from “it must fit in RAM and expand a frontier in microseconds.”

Non-Functional Requirements (NFR)

  • Scale: ~3B nodes, average degree ~200, so ~600B directed adjacency entries (300B undirected edges). Heavy tail: celebrities and open-networkers with millions of edges; the engine must not let one supernode blow up a query or a shard.
  • Latency: 1-hop neighbor read p99 < 5ms. Distance query (k up to 3) p99 < 15ms. Second-degree suggestion fetch p99 < 50ms (it is precomputed; the fetch is a list read plus a small live exclusion). Mutual-count p99 < 10ms.
  • Throughput: the distance/badge query is rendered on every profile view and every search row. Target ~500K distance QPS at peak across the fleet, plus ~2M 1-hop neighbor reads/sec (they are the building block of everything).
  • Availability: 99.95% on read paths. A missing “2nd degree” badge is a degraded-but-acceptable render; a query that hangs and blocks the page is not. Reads must degrade gracefully, never block.
  • Consistency: eventual is fine for traversal results. A friendship accepted 30 seconds ago not yet reflected in a suggestion list is invisible to users. The one exception: the two parties to a new edge should see each other as 1st-degree quickly (read-your-writes on their own adjacency).
  • Durability: the edge set is the source of truth and must never be lost. The in-RAM structures are derived and rebuildable from a durable log; losing a RAM replica must not lose data.
  • Memory budget: the whole point. The adjacency must fit in the aggregate RAM of the fleet with headroom for query scratch space. This drives the compression deep dive.

Back-of-the-Envelope Estimation (BoE)

Real arithmetic, because the memory number decides the architecture.

The graph, stored naively:

3B nodes, avg degree 200 -> 600B directed adjacency entries.
Naive: each entry = one 8-byte (64-bit) neighbor ID.
600B * 8 bytes = 4.8 TB   just for the neighbor IDs.
Plus per-node index (offset + degree): 3B * 16 bytes = 48 GB.
Total naive in-RAM: ~4.85 TB.

4.85 TB of pointer-heavy pointer-chasing data structures (a HashMap<long, List> in a managed runtime) would balloon to 3-5x that with object headers and references: 15-20 TB. That does not fit a sane fleet cheaply, and pointer chasing destroys cache locality. Compression is not optional; it is the design.

The graph, compressed (preview of the deep dive):

Store adjacency in Compressed Sparse Row (CSR): one flat neighbor array + one offset array.
Sort each neighbor list, delta-encode the gaps, varint-pack them.
Social-graph gaps compress to ~1 byte/edge on average (locality + small gaps).
600B edges * ~1.1 bytes = ~660 GB for edges.
Offset/degree index: 3B nodes * 8 bytes (packed) = 24 GB.
Compressed in-RAM total: ~700 GB.

700 GB fits across ~20-40 machines with room for query scratch. That is a 7x reduction from naive and ~25x from the managed-object version. CSR + delta + varint is what makes the engine affordable.

Sharding:

Shard by node ID (the owner of the adjacency list).
Target ~32 shards, each holding ~700 GB / 32 ≈ 22 GB of compressed adjacency
  + replicas (RF 3) for availability and read scaling.
Each shard: ~3B / 32 ≈ 94M nodes' adjacency lists, all in RAM.

Edge write volume:

3B users, assume each adds ~1 friend/week on average (heavy tail).
3B / 7 / 86,400 ≈ 5,000 edge-accepts/sec average, peak (4x) ≈ 20,000/sec.
Each symmetric accept = 2 directed-edge appends. ~40,000 appends/sec at peak.
Tiny versus reads. Writes are rare; reads are the firehose.

Distance-query reads (the hot path):

Rendered on every profile view and search row.
Say 300M DAU * ~30 badge-worthy renders/day = 9B distance lookups/day
  = 9B / 86,400 ≈ 104K/sec average, peak (5x) ≈ 500K/sec.
Each distance query = a handful of 1-hop neighbor reads (frontier expansion).
A k=2 check with bidirectional expansion = read adj(A) + adj(B) + one intersection.

1-hop neighbor reads (the real firehose):

Every distance query, every suggestion build, every mutual-count issues 1-hop reads.
Estimate ~2M neighbor-list reads/sec at peak across the fleet.
A neighbor-list read is a single-shard, in-RAM, sequential decode of one CSR row.
At ~200 neighbors * ~1 byte, that is ~200 bytes decoded. Microseconds.

Suggestion storage (precomputed 2nd-degree candidates):

Store top ~500 ranked 2nd-degree candidates per active user, as (id, mutual_count).
500 * 10 bytes = 5 KB/user. For 300M DAU = 1.5 TB on a sharded KV serving tier.
Rebuilt daily/continuously off the edge log; not in the hot RAM engine.

Bandwidth: reads are intra-datacenter and in-RAM; the network cost is the scatter-gather of multi-shard frontier expansion, addressed in the deep dive by routing and batching. Edge writes stream to a durable log at ~40K small records/sec ≈ a few MB/sec. Trivial.

High-Level Design (HLD)

Three planes: the durable edge log (source of truth, Kafka + a sharded KV store), the in-RAM graph engine (the compressed adjacency served from a sharded fleet, the hot path), and the offline suggestion pipeline (batch friend-of-friend computation feeding a serving KV tier). The traversal coordinator stitches multi-shard queries together.

                     ┌───────────────────────────────┐
                     │   Clients / upstream services  │
                     │  (profile view, search, PYMK)  │
                     └───────────────┬────────────────┘
                                     │  distance(A,B,k) / neighbors(U) / pymk(U)
                     ┌───────────────▼────────────────┐
                     │      Traversal Coordinator      │   stateless, horizontally scaled
                     │  (query planner + scatter/gather│
                     │   + frontier manager + cache)   │
                     └───┬───────────────┬─────────────┘
          1-hop reads    │               │   suggestion fetch
          (scatter by    │               │
           node-id shard)│               │
        ┌────────────────▼───────┐   ┌───▼────────────────────┐
        │   In-RAM Graph Shards   │   │   Suggestion Serving    │
        │  shard_0 .. shard_31    │   │   KV (user -> [cand])   │
        │  ┌───────────────────┐  │   │   (Redis / RocksDB)     │
        │  │ CSR adjacency      │  │   └───────────▲────────────┘
        │  │ (delta+varint,     │  │               │ precomputed lists
        │  │  in RAM, RF 3)     │  │   ┌───────────┴────────────┐
        │  │ + hot-node cache   │  │   │  Offline FoF Pipeline   │
        │  └───────────────────┘  │   │ (Spark/Giraph: common-  │
        └────────────▲────────────┘   │  neighbor count + rank) │
                     │ load / rebuild  └───────────▲────────────┘
                     │ from log                    │ reads edge log
        ┌────────────┴─────────────────────────────┴────────────┐
        │   Durable Edge Log + Edge KV (source of truth)          │
        │   Kafka (edge events, CDC)  +  sharded KV (edges table)  │
        └─────────────────────────────▲──────────────────────────┘
                                       │ POST edge / accept
                     ┌─────────────────┴──────────────┐
                     │        Edge Write Service        │
                     └─────────────────────────────────┘

Edge write flow:

  1. Client (friend accept) calls the Edge Write Service. It writes the symmetric edge - (A->B) and (B->A) - to the durable Edge KV in one write, and appends an edge event to the Kafka log. This is the only durable path; the KV + log are the source of truth.
  2. The in-RAM Graph Shards subscribe to the Kafka log. Each shard applies edge events for the node IDs it owns, appending to its in-RAM adjacency (with the compaction/segment trick in the deep dive, because CSR is read-optimized and not append-friendly).
  3. The offline Friend-of-Friend pipeline also consumes the log (or periodic dumps) to recompute suggestion lists.

Distance query flow (the hot path):

  1. Coordinator receives distance(A, B, k=3). It plans a bidirectional BFS: expand from A and from B toward the middle, meeting at hop ceil(k/2).
  2. It reads adj(A) from A’s shard and adj(B) from B’s shard (two single-shard, in-RAM CSR decodes). If B is in adj(A): distance 1. If adj(A) and adj(B) intersect: distance 2.
  3. If not, it expands the smaller frontier one more hop: scatter 1-hop reads for the frontier nodes across their owning shards, gather, intersect with the other side. Return the first distance at which an intersection appears, else “beyond k.”
  4. Early-exit the instant an intersection is found. Never materialize a full neighborhood.

Suggestion flow: pymk(U) is a single read from the Suggestion Serving KV (user -> [(candidate, mutual_count)]), minus a live exclusion set (already-friends and dismissed, kept small in Redis). O(1) at read time; all the graph work happened offline.

Component Deep Dive

The hard parts, naive-first then evolved: (1) the compressed in-RAM adjacency layout, (2) sharding and the supernode problem, (3) the multi-hop BFS executor, (4) second-degree suggestions offline. The feed and profile systems are not here; they are callers.

1. In-RAM compressed adjacency storage

This is the heart of the engine. The entire design exists to make the graph fit in RAM and decode fast.

Naive approach: a hash map of lists

Map<UserId, List<UserId>> in the service’s heap. Insert appends to a list; neighbor read returns the list.

Where it breaks: three ways, all fatal at 600B edges.

  • Memory blowup. In a managed runtime, every Long is a boxed object (16 bytes), every ArrayList has headers and capacity slack, every map entry has its own object graph. The 4.8 TB of raw IDs becomes 15-20 TB of objects. You cannot afford it, and GC on a 15 TB heap is its own catastrophe.
  • Pointer chasing. Walking a List<Long> dereferences a pointer per element across random heap addresses: a cache miss per neighbor. Expanding a 200-neighbor frontier is 200 cache misses. The CPU stalls, not computes.
  • No compression. Neighbor IDs are stored full-width (8 bytes) even though a sorted list of a user’s friends has small gaps between consecutive IDs that could be a byte each.

Evolved approach: Compressed Sparse Row + delta + varint

Store the graph as CSR (Compressed Sparse Row): two flat primitive arrays, no per-element objects.

node_index[]   : for node i, the offset into neighbors[] where its list starts.
                 node i's degree = node_index[i+1] - node_index[i].
                 3B+1 entries. Pack as 40-bit offsets -> ~5 bytes each -> ~15-24 GB.

neighbors[]    : one giant flat byte array. Each node's neighbor list is:
                 1. sorted ascending by neighbor ID,
                 2. delta-encoded: store gaps, not absolute IDs
                    [1000, 1005, 1200, 5000] -> [1000, 5, 195, 3800],
                 3. varint-packed: small gaps take 1 byte, larger take 2-3.

Why each step pays off:

  • Flat arrays, zero objects. neighbors[] is one contiguous byte[] (or several segment arrays off-heap). No headers, no boxing, no GC pressure over the hot data. A neighbor list is a sequential scan of contiguous bytes: cache-friendly, prefetcher-friendly, decode-in-a-tight-loop fast.
  • Delta encoding. A user’s friends cluster (people who joined near each other, from the same region, have nearby IDs). Sorted, the gaps are small. Storing the gap instead of the absolute 64-bit ID is the first big win.
  • Varint. A gap of 5 fits in 1 byte; a gap of 3800 fits in 2. Average social-graph edge lands near ~1.1 bytes. That is the 4.8 TB -> 660 GB collapse.

Decoding a neighbor list: seek to node_index[i], read varints, running-sum the deltas back into absolute IDs, stop at node_index[i+1]. Pure sequential memory reads, no pointer chasing. A 200-neighbor list is ~220 bytes decoded in a few microseconds.

Further squeeze (mention it, do not over-engineer v1): gap-distribution-aware codecs (reference-encoding against a similar node’s list, like WebGraph’s technique) and frontier bitsets - for a dense frontier, a roaring bitmap over the ID space beats a list. v1 ships CSR + delta + varint; those are the 80% win.

The cost of CSR: it is read-optimized and immutable. You cannot cheaply insert into the middle of a flat packed array. That is the write problem, handled next.

Handling writes against an immutable CSR: segments + compaction

CSR is built once, read forever, but friendships are added continuously. Use an LSM-style layering:

- Base segment: the big immutable CSR snapshot (rebuilt periodically from the log).
- Delta segments: recent edge additions/deletions kept in a small, mutable,
  per-shard append structure (a simple per-node append list + a tombstone set).
- Read = merge: decode base CSR row, then overlay the node's delta adds and
  remove tombstoned edges. Deltas are tiny, so the merge is cheap.
- Compaction: periodically fold deltas into a fresh base CSR (background job),
  then drop the deltas. Same idea as an LSM-tree flush.

A 30-second-old friendship lives in a delta segment and is visible immediately to the two parties; it is folded into the base CSR at the next compaction. This preserves the read-optimized CSR while supporting a live write stream. Deletes are tombstones until compaction physically removes them.

LayoutRAM for 600B edgesNeighbor-read costWrite supportVerdict
Map<Id, List>15-20 TBcache miss per edgeeasyImpossible at scale
Flat CSR, full-width IDs4.85 TBsequential, fastimmutableToo big
CSR + delta + varint~700 GBsequential decodeimmutableThe storage
CSR base + delta segments~700 GB + smallbase + tiny overlaylive writesThe answer

2. Sharding and the supernode problem

700 GB does not fit one machine’s RAM comfortably alongside query scratch and the OS. Shard it.

Naive approach: shard by hashing the edge

Hash (A, B) to a shard. Spreads edges evenly.

Where it breaks: reading one user’s neighbor list now scatters across every shard, because A’s edges are hashed individually to different machines. A 1-hop read - the single most common operation, 2M/sec - becomes an all-shards scatter-gather. You have destroyed locality, which is the entire reason to shard.

Evolved approach: shard by node ID (adjacency locality)

Shard by the owning node ID. A node’s entire adjacency list lives on one shard (and its replicas). shard = hash(user_id) % N.

neighbors(U)        -> single shard: hash(U) -> read U's CSR row. One hop, one machine.
distance(A, B)      -> read adj(A) on A's shard, adj(B) on B's shard. Two shards.
frontier expansion  -> scatter 1-hop reads to the shards owning the frontier nodes,
                       gather results at the coordinator.

The building block - “give me U’s neighbors” - is a single-shard, in-RAM read. Multi-hop queries scatter only the frontier, and the coordinator gathers. This is the right locality: co-locate a node with its edges.

The supernode problem. Shard by node ID and most shards are balanced, but a celebrity with 50M followers has a 50MB+ adjacency list on one shard, and every query that expands through them tries to read 50M neighbors. Two failures: a hot, oversized partition, and a frontier explosion when BFS hits the supernode and tries to enumerate 50M nodes.

Fixes, layered:

  • Degree cap on expansion. BFS does not need to enumerate a 50M-degree node’s full list to answer a distance query. For the “is B reachable” check, expand from B’s side (likely small) and test membership against the supernode rather than enumerating it. Never materialize a frontier through a supernode; test the other side’s small set against the supernode’s presence.
  • Adjacency-list partitioning for supernodes. Split a supernode’s list into chunks across several shards ((user_id, chunk_id) as the key) so no single shard holds the whole 50MB and membership tests can hit the relevant chunk. A directory maps a supernode to its chunks.
  • Separate the asymmetry. For directed follow graphs, store out-edges (who U follows, bounded, ~hundreds) separately from in-edges (U’s followers, unbounded for celebrities). Suggestions and most traversals walk the bounded out-edge direction. The unbounded in-edge list is only needed for specific features and is partitioned.
  • Hot-node cache. The coordinator caches decoded neighbor sets for the hottest nodes (the supernodes and trending users) so repeated expansions through them skip the shard read entirely.

3. The multi-hop BFS executor

Answer “distance(A, B, k)” and “nodes within k hops” in real time without scanning anything.

Naive approach: one-directional BFS from A

Expand A’s neighbors, then their neighbors, until B appears or k hops are exhausted.

Where it breaks: the neighborhood explosion. With average degree 200:

1 hop:  ~200 nodes
2 hops: ~200 * 200 = 40,000 (minus overlap, realistically 10K-30K distinct)
3 hops: ~200^3 = 8,000,000 in the worst case

A one-directional 3-hop expansion touches millions of nodes, scatters millions of 1-hop reads across every shard, and you do this 500K times/sec. The cluster melts. Worse, if B is simply far away, you pay the full 8M-node expansion to conclude “not within 3.”

Evolved approach: bidirectional BFS with frontier management

Expand from both ends toward the middle. To check distance <= k, grow A’s frontier and B’s frontier alternately; they only need to meet in the middle, so each side expands at most ceil(k/2) hops.

distance(A, B, k=3):
  if B in adj(A):                         return 1          # one shard read
  fA = adj(A); fB = adj(B)                                  # two shard reads
  if fA ∩ fB != ∅:                        return 2          # intersect 1st degrees
  # expand ONE more hop from the SMALLER frontier only:
  if |fA| <= |fB|:  f2 = expand(fA)       # scatter reads for fA's nodes
  else:             f2 = expand(fB)
  if (other side) ∩ f2 != ∅:             return 3
  return "beyond_k"

Why bidirectional is the whole game: one-directional k=3 touches b^3 ≈ 8M. Meeting in the middle, each side goes ~1.5 hops, so you intersect a ~200-set against a ~40K-set: O(b^{k/2}) instead of O(b^k), the classic square-root reduction. An impossible query becomes a few shard reads plus a set intersection. Always expand the smaller frontier to keep the scatter small (expanding a 200-set beats expanding a 40K-set).

Frontier-management details that make it real at 500K QPS:

  • Early exit. The instant any intersection is non-empty, return. Most “2nd degree” answers resolve after two reads and one intersection - no third hop.
  • Dedup the frontier. Use a visited set (a bitset or hash set over seen IDs) so you never re-expand a node reached by two paths. Without it, overlap re-does work.
  • Batch the scatter. When expanding a frontier, group the frontier node IDs by owning shard and send one batched multi-get per shard, not one RPC per node. A 200-node frontier spread over 32 shards is 32 batched reads, not 200 RPCs.
  • Bound and degrade. Cap total nodes visited and wall-clock per query. If a query would exceed the budget (it passed through dense regions), return “beyond_k / unknown” rather than blowing the latency SLA. A missing badge is acceptable; a 2-second query is not.
  • Membership over enumeration for the deep check. For k=3, instead of enumerating A’s full 2nd degree, enumerate B’s 1st degree (small) and test each against A’s 2nd-degree presence via the other frontier. Enumerate the small side, test against the big side.

For the ubiquitous 1st/2nd-degree badge specifically, this live bidirectional check is fast enough, but it can be made nearly free by caching per-user 2nd-degree membership. The engine supports an optional 2nd-degree Bloom/roaring sketch per active user (built off the same offline pipeline) so the common “is X my 2nd degree” check is an O(1) sketch lookup, falling back to live bidirectional BFS only for the rarer 3rd-degree / beyond case. That is the same move as the suggestion precompute: push neighborhood math offline, keep the read O(1).

4. Second-degree suggestions (friend-of-friend, offline)

“People you may know” is, at its graph core, “rank my distance-2 users by how many friends we share.”

Naive approach: compute friend-of-friend on request

On page load, expand U’s friends’ friends, count occurrences (that count is the mutual-connection score), drop existing friends, sort, return top 20.

Where it breaks: this is the 2nd-degree explosion on the hot path - a 10K-40K-entry gather with counting, per request, scattered across shards, at DAU scale. It melts the engine for data that does not need to be live: an hour-old suggestion is perfectly fine, and the ranking needs non-graph features (same company, same school) that live elsewhere. Live FoF is the wrong place to do this.

Evolved approach: offline common-neighbor computation, serve precomputed

Move the graph-heavy work into a batch pipeline over the edge log, serve a precomputed ranked list.

  1. Candidate + mutual-count generation (batch, graph-parallel). Over the full edge list in Spark/Giraph, for each user U compute the multiset of distance-2 users and the count of distinct common neighbors to each (the mutual-friends score). The efficient formulation: for each node v, every unordered pair of v’s neighbors (a, b) contributes one shared neighbor (v) to the pair; sum over all v to get common-neighbor counts. This is a common-neighbor / triangle-adjacent computation, run daily or incrementally off the log. Cap to the top few hundred candidates per user by mutual count.
Batch:
  for each node v:                       # v is a shared friend
    for each pair (a, b) in neighbors(v): # a and b are 2nd-degree to each other
      mutual_count[(a, b)] += 1
  # then per user U: top-K candidates by mutual_count, excluding existing friends
  output: pymk_candidates[U] = [(candidate_id, mutual_count), ...]
  1. Feature enrichment (downstream, out of this engine’s scope but named). Join candidates against profile data for same-company, same-school, same-location, co-view signals. The engine hands off graph candidates + mutual counts; a ranking service adds these.

  2. Ranking. A model scores candidates: mutual count dominates, but “3 mutuals + same employer” can outrank “8 mutuals at random.” Output the ranked top-K per user to the Suggestion Serving KV.

  3. Serving. pymk(U) reads the precomputed list from KV, then subtracts a live exclusion set (already-friends, dismissed) kept small in Redis and updated in real time. O(1) read; the only live piece is the exclusion filter.

The exclusion set is the sole real-time component; everything expensive is precomputed. The supernode guard applies here too: skip ultra-high-degree shared nodes in candidate generation (two strangers both following a celebrity is not a signal), which also keeps the pair-enumeration from exploding on supernodes.

API Design & Data Schema

API

# Edge writes (called by the friend/follow service)
POST /api/v1/edges
Body:   { "from": "123", "to": "999", "type": "friend" }   # friend = symmetric
Resp 202: { "status": "applied", "symmetric": true }

DELETE /api/v1/edges
Body:   { "from": "123", "to": "999", "type": "friend" }
Resp 200: { "status": "removed" }

# Neighbor read (the building block)
GET  /api/v1/neighbors?user=123&limit=500&cursor=<opaque>
Resp 200: { "user":"123", "neighbors":["999","1000",...], "next_cursor":"..." }
         # cursor-paginated for supernodes; p99 < 5ms for normal users

# Distance / who-knows-whom (the hot path)
GET  /api/v1/distance?a=123&b=999&max_hops=3
Resp 200: { "a":"123", "b":"999", "distance":2, "within":true }
         # distance in {1,2,3,"beyond"}; p99 < 15ms

# Mutual connections
GET  /api/v1/mutual?a=123&b=999
Resp 200: { "count":14, "sample":["5","42","88"] }   # count exact, sample bounded

# Second-degree suggestions
GET  /api/v1/suggestions?user=123&limit=20
Resp 200: { "suggestions":[ {"user":"777","mutual_count":9}, ... ] }
         # precomputed list minus live exclusions; p99 < 50ms

# Bounded neighborhood expansion (for internal callers / ranking)
GET  /api/v1/expand?user=123&hops=2&limit=5000
Resp 200: { "nodes":[...], "truncated":false }       # bounded, degrades if dense

Pagination is cursor-based everywhere because neighbor lists (supernodes) and expansions can be large and shift under concurrent writes; the cursor encodes a stable position in the sorted list.

Data stores and schema

1. Edge KV / log - source of truth (sharded KV + Kafka), NOT a native graph DB. The access pattern is single-partition adjacency reads and symmetric edge appends, which is a wide-column/KV sweet spot that shards cleanly by node ID. A native graph database cannot shard 300B edges without cross-partition traversals destroying latency at this QPS; the traversal smarts live in our coordinator, not in the storage engine.

Table: edges                         (durable source of truth, sharded by from_id)
  from_id    BIGINT   PARTITION KEY
  to_id      BIGINT   CLUSTERING KEY
  type       TINYINT  (friend | follow)
  created_at TIMESTAMP
  Symmetric friend A-B stored as (A,B) and (B,A).
  "neighbors of U" = single-partition scan of edges[U].

Kafka topic: edge_events   (from_id, to_id, type, op=add|remove, ts)
  Consumed by: in-RAM shards (apply to CSR delta), FoF pipeline, any CDC subscriber.

2. In-RAM Graph Shards - the engine. Compressed CSR (delta + varint) base segment plus mutable delta segments per node, rebuilt/compacted from the edge log. Keyed and sharded by node ID. This is derived state - if a replica dies, reload its shard’s adjacency from the durable edges table / log.

Per shard, in RAM:
  node_index[]  : packed offsets, node_id -> (offset, degree) into neighbors[]
  neighbors[]   : flat byte array, per-node sorted delta+varint neighbor gaps
  deltas        : recent adds (per-node append) + tombstones (recent removes)
  hot_cache     : decoded neighbor sets for supernodes / trending nodes

3. Suggestion Serving KV (Redis / RocksDB). user_id -> [(candidate_id, mutual_count)], precomputed top-K, rebuilt by the offline pipeline. Plus a small user_id -> {excluded_ids} real-time set (already-friends + dismissed).

4. (Optional) 2nd-degree sketch tier. user_id -> roaring_bitmap / bloom of distance-2 members, built offline, to make the common 2nd-degree badge an O(1) lookup. Rebuildable; not durable.

Why specialized in-RAM over one SQL/graph box: the workload is billions of partition-scoped neighbor reads feeding bounded local traversals plus precomputed-list serving. None of it is cross-entity ACID. The single atomicity need - writing a symmetric edge as both rows - is a single-shard two-row write on the durable KV. SQL joins and global transactions, and a native graph DB’s cross-partition traversal engine, are exactly the machinery we do not want on this path.

Bottlenecks & Scaling

Where it breaks first, in order, and the fix:

1. Memory - the graph does not fit (breaks before anything else). Naive adjacency is 15-20 TB of objects. Fix: CSR flat arrays + delta encoding + varint packing -> ~700 GB. No per-element objects, sequential cache-friendly decode, GC kept off the hot data (off-heap byte arrays). This single choice is what makes an in-RAM engine affordable.

2. 1-hop neighbor read at 2M QPS (the building block). Fix: shard by node ID so a node’s whole adjacency is one single-shard, in-RAM, sequential CSR decode. RF 3 replicas spread read load and provide failover. Never hash edges individually - that would scatter every neighbor read across all shards.

3. The neighborhood explosion on distance queries. One-directional k=3 touches ~8M nodes. Fix: bidirectional BFS (meet in the middle, O(b^{k/2})), always expand the smaller frontier, early-exit on intersection, dedup with a visited set, batch the scatter per shard, and cap/degrade on budget overrun. Optionally a per-user 2nd-degree sketch makes the common badge O(1).

4. Supernodes (celebrities) - hot partition + frontier explosion. A 50M-degree node overloads one shard and blows up any BFS passing through it. Fix: partition a supernode’s adjacency into chunks across shards; use membership tests instead of enumerating through a supernode; separate bounded out-edges from unbounded in-edges; cache decoded hot-node neighbor sets at the coordinator; skip supernodes as “shared friends” in suggestion generation.

5. Writes against an immutable CSR. You cannot insert into a packed flat array. Fix: LSM-style base CSR + mutable delta segments; reads merge base + deltas + tombstones; background compaction folds deltas into a fresh base. New edges are visible immediately via deltas; the read-optimized CSR is preserved.

6. Suggestion compute cost. Live friend-of-friend is a 10K-40K-entry per-request gather. Fix: offline common-neighbor batch over the edge log producing ranked top-K lists; serve as an O(1) KV read minus a small live exclusion set. Shares the 2nd-degree computation with the sketch tier.

7. Scatter-gather tail latency on multi-shard expansion. A frontier spread over 32 shards is as slow as its slowest shard. Fix: batch per shard (one multi-get, not N RPCs), hedge requests to replicas on a slow shard, cap frontier size, and degrade gracefully to “unknown” past the latency budget rather than blocking the render.

8. Consistency and read-your-writes. A new friend not yet in the base CSR. Fix: the delta segment reflects the new edge immediately for the two parties (read-your-writes on their own adjacency); everyone else’s derived views (sketches, suggestions) update eventually off the log. Deletes are tombstoned at once and physically removed at compaction.

9. Single points of failure and multi-region. The coordinator is stateless and horizontally scaled; shards are RF 3; the edge log and KV are replicated; the offline pipeline is restartable and idempotent. Deploy the read engine per region, route via GeoDNS, replicate the edge log across regions; because traversal results are eventual, cross-region lag is forgiving. No single box whose loss stops badges from rendering - a degraded badge still lets the page load.

Wrap-Up

The trade-offs that define this engine:

  • Compressed in-RAM CSR over a native graph database. We give up a graph engine’s rich traversal language and cheap deep paths (which we refuse to run live anyway) to get a flat, object-free, delta+varint adjacency that fits ~600B edges in ~700 GB of RAM and decodes a neighbor list in microseconds. The traversal intelligence lives in our coordinator, not the store.
  • Shard by node ID, not by edge. Co-locating a node with its adjacency makes the 2M-QPS building-block read a single-shard in-RAM decode; hashing edges would have scattered every read and defeated the purpose.
  • Bidirectional BFS with aggressive frontier management. Meet in the middle to turn O(b^k) into O(b^{k/2}), expand the smaller side, early-exit, batch the scatter, and degrade on budget - so a who-knows-whom query is a few shard reads and a set intersection, not a million-node walk.
  • Tame supernodes explicitly. Chunk their adjacency, test membership instead of enumerating, split in-edges from out-edges, cache the hot ones. The heavy tail is where naive designs die.
  • Everything graph-heavy is offline; everything on the read path is O(1)-ish. Second-degree suggestions and optional 2nd-degree sketches are precomputed off the edge log; the live reads are a neighbor decode, a bounded intersection, or a list fetch.

One-line summary: a social graph traversal engine is a memory-layout problem first and a traversal problem second - store the adjacency as a delta+varint-compressed CSR that fits in RAM sharded by node ID, answer who-knows-whom with bidirectional BFS that expands the smaller frontier and early-exits, tame supernodes with chunking and membership tests, and precompute second-degree suggestions offline so the hot path is always just a neighbor decode and a set intersection across billions of users and edges.