Mutual-Connection Friend Suggestions and Ranking Evaluation
Medium · ML System Design · Machine Learning Engineer · Onsite
Prompt
A large social network is building a friend-discovery (PYMK — People You May Know) system that identifies prospective connections through shared friends in the social graph and orders them so viewers send invitations that recipients accept.
Design the end-to-end retrieval, scoring, ranking, and evaluation system under these functional and scale constraints:
- Two-hop candidate discovery: Given a viewer
u, surface members who share one or more mutual connections withu, strictly omittinguand all existing 1-hop connections ofu. - Bounded topological proximity: Formulate normalized graph-affinity functions whose outputs map cleanly into
[0, 1]for candidate scoring ahead of or alongside learned ranking. - Learned ranking pipeline: Order candidates using graph structure, shared-connection statistics, historical pair interactions, and member profile signals to maximize accepted connections.
- Offline and online evaluation: Score candidate orderings offline with top-weighted rank metrics (NDCG or MAP) backed by well-justified relevance labels, paired with online A/B testing.
- Scale, degree skew, and latency: Operate across 100 million active members and 10 billion undirected friendship edges—where mean degree is ~200 connections per member but heavy-tailed hubs exceed 10,000+ connections—while returning top-20 suggestions within 100 ms at p99.
Scope & Expectations
- Scalable 2-hop retrieval and hub handling: Architect friends-of-friends candidate generation and show how high-degree hub accounts (
10,000+connections) are contained without combinatorial blowups. - Normalized
[0, 1]graph affinity metrics: Define bounded similarity formulas (such as Jaccard, cosine, or normalized Adamic-Adar) and explain why sorting by raw mutual-friend counts fails. - ML ranking and bias mitigation: Cover feature engineering, positive/negative training label construction, impression/position bias correction, and pointwise calibrated probabilities versus listwise ranking objectives.
- NDCG offline evaluation and live experimentation: Specify non-circular ground-truth labels for NDCG, examine where NDCG's theoretical assumptions (item independence, smooth position discounts) break in real social graphs, and define online A/B metrics.
Step-by-step walkthrough
Clarify the goal, requirements, and problem framing
At first glance, "People You May Know" (PYMK) looks like a pure graph query: find friends of friends and sort them. In practice, a connection only forms when two different people say yes: the viewer
umust choose to send an invitation, and the recommended candidatecmust choose to accept it. Framing PYMK as a two-sided ranking problem right away shapes our training labels, ranking objective, and A/B test metrics.Functional requirements
- Candidate retrieval: Given viewer
u, discover memberscconnected to one or more ofu's friends, while filtering outu, current 1-hop connections, pending invitations in either direction, blocked accounts, and previously dismissed suggestions. - Bounded graph scoring: Define mathematical similarity scores guaranteed to lie in
[0, 1]so topological closeness can be compared fairly across casual users and super-connectors. - ML ranking: Rank retrieved candidates using graph topology, past interactions, and profile attributes, returning the top 20 recommendations.
- Evaluation: Measure ranking quality offline with Normalized Discounted Cumulative Gain (NDCG)—a ranking metric that gives higher credit when relevant items appear near the top of the list—using non-circular outcome labels, and validate online with an A/B test.
Non-functional requirements and scale
- Graph size: 100 million active users and 10 billion undirected friendship edges. Because each undirected edge connects two users, the average user has
(2 * 10B) / 100M = 200friends. - Heavy-tailed degree distribution: A node degree is a user's friend count, and a heavy-tailed distribution means most users have a few dozen to a few hundred friends while a small fraction of "hubs" (recruiters, creators, power connectors) have 10,000+ friends.
- Latency and freshness: Serve the top-20 list in under 100 ms at p99 (meaning 99% of requests finish within 100 ms). Newly accepted friendships or blocks must take effect immediately so we never recommend someone the user just connected with.
- Candidate retrieval: Given viewer
Estimate scale and back-of-the-envelope numbers
Before choosing databases or algorithms, let us check how large the graph is in memory and how much work a 2-hop traversal actually performs.
We can store a static graph snapshot in Compressed Sparse Row (CSR) format—a compact array layout that packs all neighbor IDs into one contiguous array and uses a second
offsetsarray to mark where each user's neighbor list starts and ends.Tiny CSR example (0: [1, 2], 1: [0], 2: [0]): offsets = [0, 2, 3, 4] <- user i's friends live in neighbors[offsets[i] : offsets[i+1]] neighbors = [1, 2, 0, 0] 1. Graph memory footprint Directed entries = 2 * 10B undirected edges = 20B entries neighbors array (uint32) = 20B * 4 bytes = 80 GB (100M user IDs easily fit in 32-bit ints) offsets array (uint64) = 100M * 8 bytes = 0.8 GB (20B > 2^32, so offsets need 64-bit ints) Total read-only CSR graph = ~81 GB -> fits completely in RAM on one 256 GB worker machine! 2. 2-hop traversal cost: uncapped vs. capped Uncapped: every intermediate friend v of degree d(v) connects d(v) * (d(v) - 1) user pairs. - 1 hub with 10,000 friends causes ~10^8 pair updates by itself. - 100,000 such hubs (0.1% of users) cause 10^13 updates -> compute explodes! Capped: expand at most K = 1,000 of viewer u's friends, and at most M = 300 neighbors per friend. - Average user (~200 friends * ~250 capped neighbors) = ~50,000 hash-map updates/user. - All 100M users = 100M * 50,000 = 5 * 10^12 updates per daily batch run. - At ~2 * 10^7 updates/sec/core = 250,000 core-seconds = ~70 core-hours. - Across 64 workers * 32 cores (2,048 cores) = ~2 minutes of pure compute (~15 min with I/O). 3. Precomputed candidate store Keep top 500 candidates per user * 100M users: - Per candidate: 4 B id + 2 B mutual count + 6 B (three uint16 scores) + 12 B (3 mutual IDs) = 24 B - Per user blob: 500 * 24 B = 12 KB - Total storage: 100M * 12 KB = 1.2 TB (easily fits on a small SSD key-value cluster) 4. Online serving QPS Assume 50M daily active viewers open PYMK 3 times/day = 150M requests/day: - Average = 150M / 86,400 s = ~1,740 QPS; 3x peak = ~5,200 QPS - Candidate scorings at peak = 5,200 QPS * 500 candidates = ~2.6M model evaluations/secThree architectural conclusions jump right out of the math: 1. Because 81 GB fits in a single server's RAM, each batch worker can load a full read-only copy of the CSR graph and process 1/64th of the users locally with zero distributed network shuffles. 2. Capping high-degree hubs is mandatory, because hubs contribute
d(v)^2work while carrying the weakest social signal. 3. Traversing 50,000 two-hop paths on every live request at 5,200 QPS would burn hundreds of cores just walking edges, so we precompute the top 500 candidates per user offline and reserve our 100 ms online budget for live delta updates, filtering, feature lookup, and ML ranking.Define APIs and data model
The client needs two endpoints: one to fetch ranked cards (including the "12 mutual friends" social-proof snippet) and one to report viewport impressions—events fired only when a recommendation card is at least 50% visible on screen for at least 1 second. Logging viewport impressions instead of server responses is essential because a mobile carousel usually shows only 3 cards until the user swipes; treating unseen cards at positions 4–20 as "seen and ignored" would poison training data with false negatives.
External APIs GET /v1/pymk?user_id=u&surface=carousel&limit=20&cursor=... -> 200 { request_id: "req_9a8f", items: [ { candidate_id: 849201, rank: 1, reason: { mutual_count: 12, sample_mutual_ids: [104, 592, 991] } } ], next_cursor: "..." } POST /v1/pymk/events { request_id: "req_9a8f", events: [ { candidate_id: 849201, rank: 1, event_type: "viewport_impression" | "invite_sent" | "dismissed" | "profile_click", visible_ms: 1850, client_ts: 1764500012 } ] }Our storage layer separates source-of-truth transactional edges from read-optimized graph and ML stores:
1. Source-of-truth Graph DB (sharded relational/KV store, keyed by user_id) friendships(user_id, friend_id, created_at, interaction_score) PK (user_id, friend_id) invites(sender_id, receiver_id, status, request_id, updated_at) blocks_and_dismissals(user_id, target_id, kind, created_at) 2. Daily CSR Snapshot (in worker RAM, ~81 GB) offsets[100M + 1], neighbors[20B], true_degree[100M] Each user's neighbor slice is pre-sorted by interaction_score DESC, created_at DESC. -> Taking neighbors[:M] automatically selects that node's M closest connections! 3. Live Graph Service (sharded in-memory adjacency, fed by Kafka edge stream) Stores current 1-hop bitmaps/sorted arrays + recent_edges_since_snapshot(user_id). 4. Candidate Store (sharded SSD key-value store, ~1.2 TB) Key: user_id -> Value: 12 KB packed array of up to 500 (candidate_id, cn, jaccard, aa_norm, cosine, sample_mutual_ids[3]), snapshot_ts 5. Feature Store & Training Warehouse Online Feature Store (Redis/RocksDB): user activity counters, profile hashes, pair interactions. Warehouse Logs: impressions joined with outcomes by (request_id, candidate_id), storing exact serving-time feature snapshots to prevent training-serving skew.High-level system architecture
The system combines a daily full-graph batch pipeline for broad 2-hop coverage with a lightweight real-time edge stream so freshly accepted friendships immediately update exclusions and add new 2-hop candidates.
+------------------ Offline Daily Pipeline ------------------+ | | Source Graph DB --+-> CSR Snapshot (81 GB) replicated to 64 Batch Workers | | -> Capped 2-hop + Bounded Scores -> Top 500/user | | -> Write 1.2 TB to Candidate Store | | | Impression & --+-> Join invites/accepts (14d window) -> Feature Snapshot | Outcome Stream | -> Train Two-Head GBDT -> NDCG Eval -> Model Registry | +------------------------------------------------------------+ Real-Time Edge Stream (invite sent / accepted / blocked / dismissed) -> Live Graph Service (updates 1-hop sets & recent_edges in < 2 seconds) -> Invalidates 10-min PYMK response cache for affected user_id Online Request Path (Target: p99 < 100 ms; Budget sum: ~62 ms) Client -> PYMK Service |--(parallel, ~12 ms)--+-> Candidate Store: fetch batch top-500 for u | +-> Live Graph: fetch u's new edges -> 2-hop deltas v Merge & Live Filter (~8 ms): drop 1-hop friends, pending invites, blocks, dismissals v Feature Store Multi-Get (~25 ms): fetch user + pair features for <= 500 candidates v ML Ranker (~12 ms): two-head GBDT -> P(invite | examined) * P(accept | invite) v Re-ranker (~5 ms): community diversity rule + candidate daily impression cap -> Top 20Deep dive 1: 2-hop candidate retrieval and taming hubs
Why do high-degree hubs cause trouble even if we had unlimited CPUs? Consider a small example:
u (200 friends) ---- v1 (close college friend, d = 40) ---- Candidate B \ \------------ v2 (tech influencer hub, d = 15,000) ---- 14,999 strangersSharing
v1is strong evidence thatuand Candidate B move in the same real-world circle. Sharingv2tells us almost nothing, yet without protectionv2floodsu's candidate pool with 14,999 strangers and does the same for all 15,000 of its connections (15,000^2 = 225,000,000pair updates).We contain hubs at four distinct points in the pipeline: 1. Cap intermediate neighbor lists (
M = 300): Because each row in our CSR snapshot is pre-sorted by interaction strength (messages, profile visits, comments) and recency, reading onlyv's firstM = 300neighbors drops weak acquaintances while keepingv's genuine inner circle. 2. Cap the viewer's own expanded friends (K = 1,000): If vieweruis a hub, expanding their 1,000 closest friends already yields up to 300,000 path updates—more than enough to fill 500 slots. 3. Down-weight hubs using their true degree: Even among a hub's top 300 friends,v2is still a public figure. When accumulating Adamic-Adar weights (1 / ln(d(v))), we divide byln(true_degree[v])(ln(15000) = 9.62), neverln(300). 4. Cap candidate exposure at serving time: Hubs share mutual friends with millions of people, so we track a sliding daily impression counter per candidate and demote candidates once they hit an exposure cap, preventing celebrity spam.Here is the core per-user traversal executed by each batch worker on its in-memory CSR slice:
import math def generate_two_hop_candidates( u: int, full_neighbors_of, capped_neighbors_of, true_degree: list[int], max_own_friends: int = 1000, ) -> dict[int, tuple[int, float, list[int]]]: """Accumulate (mutual_count, raw_adamic_adar, sample_mutuals) for u's 2-hop candidates.""" # Load u's current 1-hop friends so we strictly exclude u and existing connections. own_friends = full_neighbors_of(u) excluded_ids = set(own_friends) excluded_ids.add(u) # candidate_id -> [common_neighbor_count, adamic_adar_sum, sample_mutual_ids] accum: dict[int, list] = {} # Expand at most max_own_friends of u's strongest connections. for v in own_friends[:max_own_friends]: # Any mutual friend connects at least u and c, so true_degree[v] >= 2 in undirected graphs; # max(2, ...) guards against any dirty snapshot edge case so log() is always >= ln(2) > 0. hub_weight = 1.0 / math.log(max(2, true_degree[v])) # Traverse at most M = 300 strongest neighbors of intermediate friend v. for c in capped_neighbors_of(v): if c in excluded_ids: continue entry = accum.get(c) if entry is None: accum[c] = [1, hub_weight, [v]] else: entry[0] += 1 entry[1] += hub_weight if len(entry[2]) < 3: entry[2].append(v) return {c: (vals[0], vals[1], vals[2]) for c, vals in accum.items()}Keeping candidates fresh between daily batch runs: When user
uaccepts a friend request from Ana at 2:00 PM, two things must happen right away: Ana must disappear fromu's suggestions, and Ana's friends should become eligible candidates foru. Our request path checks the Live Graph Service to filter out Ana (plus any new blocks or pending invites) and fetchescapped_neighbors_of(Ana)on the fly for the 0–3 friendshipsuformed since midnight, merging them into the 500 batch candidates in ~10 ms.Deep dive 2: Bounded topological affinity scores in [0, 1]
Why can't we simply rank candidates by their raw mutual-friend count
CN(u, c) = |N(u) intersect N(c)|? - Degree bias: A hub with 10,000 friends overlaps with almost everyone by sheer volume, pushing ordinary peers off the list. - No cross-user scale: Sharing 8 mutual friends is huge whenuandceach have 25 friends, and negligible when both have 4,000 friends. - Unbounded drift: As users accumulate friends over years, raw counts grow without an upper bound, breaking fixed retrieval thresholds.To map topological proximity cleanly into
[0, 1], letN(x)be userx's friend set,d(x) = |N(x)|be their true degree, andCN = |N(u) intersect N(c)|:1. Jaccard Similarity (fraction of the combined friend circle that is shared) J(u, c) = CN / |N(u) union N(c)| = CN / (d(u) + d(c) - CN) Why in [0, 1]: 0 <= CN <= min(d(u), d(c)) <= d(u) + d(c) - CN, so 0 <= J(u, c) <= 1. 2. Cosine Similarity of binary adjacency vectors Cos(u, c) = CN / sqrt(d(u) * d(c)) Why in [0, 1]: CN <= min(d(u), d(c)) <= sqrt(d(u) * d(c)) (geometric mean >= minimum). 3. Normalized Adamic-Adar (discounts shared friends who are hubs) Raw Adamic-Adar: AA(u, c) = sum over w in (N(u) intersect N(c)) of 1 / ln(d(w)) Node self-budget: A(x) = sum over w in N(x) with d(w) >= 2 of 1 / ln(d(w)) Normalized score: AA_norm(u, c) = AA(u, c) / sqrt(A(u) * A(c)) Why in [0, 1]: Every mutual friend w has d(w) >= 2 (it connects both u and c), so every 1 / ln(d(w)) term in AA(u, c) appears inside both A(u) and A(c). Therefore 0 <= AA(u, c) <= min(A(u), A(c)) <= sqrt(A(u) * A(c)), guaranteeing 0 <= AA_norm <= 1!Notice that even when
CNandAA(u, c)are computed from our capped 2-hop pass (producing lower boundsCN_hat <= CNandAA_hat <= AA), all three formulas still stay strictly inside[0, 1]because reducing the numerator (and for Jaccard, simultaneously increasingd(u) + d(c) - CN_hat) only moves the ratio closer to0.Concrete comparison—suppose viewer
uhasd(u) = 200friends (A(u) = 38.0):Candidate d(c) CN Raw rank Jaccard Cosine AA_norm A (celebrity hub) 10,000 12 #1 (12) 12 / 10,188 = 0.0012 12 / 1,414 = 0.0085 0.0061 B (college peer) 150 8 #2 (8) 8 / 342 = 0.0234 8 / 173 = 0.0462 0.0495Raw mutual count ranks the hub
#1(12 > 8). Every bounded metric flips the order by a wide margin (20xon Jaccard,5.4xon Cosine,8.1xonAA_norm) because 8 out of 150 friends represents a dense personal overlap, whereas 12 out of 10,000 is background noise.How we combine them: - Jaccard penalizes degree mismatch most aggressively (
d(u) + d(c)in the denominator), which can over-penalize a genuinely relevant senior colleague with 1,500 connections. - Cosine softens that penalty via the square root. -AA_normgoes one step further by asking who the mutual friends are, discounting hubs in the middle. We select the top 500 batch candidates per user usingAA_norm, store all three bounded scores alongside rawCNand both degrees, and pass all of them as features into the ML ranker so the model can learn non-linear combinations.Deep dive 3: ML ranking pipeline and correcting impression bias
Bounded graph scores order neighborhoods well, but they cannot see that
uvisitedc's profile yesterday or worked at the same company in 2024, and a0.049AA_normis not a probability. Our ML ranker turns rich signals into calibrated probabilities—predicted numbers that match real-world rates (when the model predicts0.10, invitations happen about 10% of the time).Two-head ranking objective
Because a connection requires two sequential actions, we train two separate Gradient-Boosted Decision Tree (GBDT) models—ensembles of shallow decision trees trained sequentially so each tree corrects the residual errors of the previous ones—and combine their predictions at serving time:
FinalScore(u, c) = P(invite | u, c, examined) * P(accept | u, c, invite) - alpha * P(dismiss_or_report | u, c, examined) - Invite head training data: logged viewport impressions. y = 1 if u sends an invite to c within 7 days; y = 0 if u sees c and takes no action (or dismisses). - Accept head training data: sent PYMK invitations. y = 1 if receiver c accepts within 14 days; y = 0 if c ignores for 14 days or rejects.Why pointwise calibrated logistic loss instead of listwise learning-to-rank (such as LambdaMART, which optimizes list order directly without calibrated outputs)? 1. Multiplying
P(invite) * P(accept)is mathematically meaningful only when both heads output true probabilities on[0, 1]. 2. Calibrated probabilities let product surfaces enforce absolute quality floors (for example, hide PYMK or suppress push notifications whenever expected connection rate drops below1.5%).Feature engineering (logged at serving time to prevent skew)
- Graph topology: CN, Jaccard, Cosine, AA_norm, d(u), d(c), mutual friends added in last 30d ("fresh social circle" signal), mutuals u messaged in last 7d, shared groups. - Pair interactions: profile views (u -> c and c -> u), co-commented posts, contact-book match. - Profile overlap: exact/fuzzy match on school, employer, city, primary language, graduation year. - Actor priors: viewer's historical invite rate, candidate's historical accept rate, account ages, prior PYMK impressions of (u, c) in last 30d (captures impression fatigue).Correcting impression and position bias
In a horizontal carousel, slot 1 gets far more eyeballs than slot 6. If we train naively on raw clicks, the model confuses "was shown in slot 1" with "is a great candidate." We correct this in three layers: 1. Viewport-filtered negatives: Never use unshown candidates—or cards that stayed off-screen at positions 4–20—as ranking negatives. Only cards meeting the viewport threshold (
>= 50%visible for>= 1 s) enter the invite head's dataset. 2. Factored position debiasing (Position-as-a-Feature): Even among viewport-visible cards, slot 1 is examined more carefully than slot 3. During training we factor the probability into a shallow examination tower (fed only display position, surface, and device) times the relevance tower (fed user/candidate features):logit P(invite | shown at pos k) = examination_bias(k, surface) + relevance_logit(u, c)At serving time we dropexamination_bias(or fixk = 1) and rank purely bysigmoid(relevance_logit(u, c)), keeping predictions cleanly bounded in(0, 1). 3. Randomized swap slice + exploration: On 1% of traffic we randomly swap adjacent pairs(k, k + 1)to measure true examination propensitiesp_k—the probability a user genuinely inspects slotk—for unbiased Inverse Propensity Weighting (IPW) (reweighting observed outcomes by1 / p_k, clipped at10, when scoring candidate models offline or fitting pairwise rankers). On another 2% slice we inject one lower-ranked candidate into slots 3–5 so future models observe outcomes outside the old model's echo chamber.Deep dive 4: Offline evaluation with NDCG and online A/B testing
Non-circular relevance labels
Never define ground-truth relevance using mutual friend counts or graph heuristics—doing so makes NDCG circularly reward any model that memorizes its own input feature! Instead, assign graded labels from actual future connection outcomes:
grade 2 (gain = 2^2 - 1 = 3): Invite accepted (friendship formed) within 14 days grade 1 (gain = 2^1 - 1 = 1): Invite sent, not accepted within 14 days grade 0 (gain = 2^0 - 1 = 0): Viewport-seen and ignored or dismissedWe compute NDCG@k by discounting each slot
ibylog2(i + 1)and dividing by the Ideal DCG (IDCG@k)—the score of sorting those exact same candidates in best-first order:DCG@k = sum_{i = 1..k} (2^grade_i - 1) / log2(i + 1) NDCG@k = DCG@k / IDCG@k Worked mini-trace for k = 5 with served grades [2, 0, 1, 0, 2]: Served DCG@5 = 3/log2(2) + 0/log2(3) + 1/log2(4) + 0/log2(5) + 3/log2(6) = 3/1.000 + 0 + 1/2.000 + 0 + 3/2.585 = 4.661 Ideal order = [2, 2, 1, 0, 0] IDCG@5 = 3/1.000 + 3/1.585 + 1/2.000 + 0 + 0 = 5.393 NDCG@5 = 4.661 / 5.393 = 0.864We track two complementary offline datasets: 1. Logged-impression re-ranking: Re-score historical viewport-seen lists (weighted by inverse examination propensities) to test pure ranking precision. 2. Temporal graph holdout: Freeze the graph at day
T, run full retrieval + ranking, and mark pairs who connected during[T, T + 14d]across any channel as positives. MeasuringRecall@500andNDCG@20against all newly formed friendships catches candidates that retrieval missed, though we read it alongside logged evaluation because historical PYMK impressions helped create some of those[T, T + 14d]edges.Where standard NDCG assumptions break in social networks
- Item independence fails: Standard NDCG assumes slot 4's relevance does not depend on what happened in slot 1. In a social graph, the moment
uacceptsc1in slot 1, a new edge(u, c1)forms, instantly boosting mutual-friend counts forc1's friends while making 10 redundant coworkers from the exact same tight cluster repetitive. Mitigation: add a re-ranking diversity rule (at most 3 candidates from the same detected community or employer in the top 20) and track cluster-coverage metrics alongside NDCG. - Smooth
1 / log2(i + 1)discount vs. UI cliff: A 3-card mobile carousel has sharp visibility drop-off after card 3 (requiring a horizontal swipe), not a smooth logarithmic curve. Mitigation: reportNDCG@3for carousel surfaces and replace1 / log2(i + 1)with measured slot examination propensitiesp_i. - Unbounded additive gain vs. finite invite budget: Most sessions produce at most 2–3 sent invites, so a 15th relevant item adds far less real value than NDCG credits.
Online A/B test, guardrails, and resilience
- Primary online metric: Total new accepted connections per user per week across all channels (search, profile pages, PYMK combined), run for 3–4 weeks to cover the 14-day acceptance window. Counting all channels prevents cannibalization—claiming credit when PYMK merely intercepts friendships users would have searched for anyway.
- Guardrails and network interference: Monitor invitation rejection rate, "I don't know this person" / block reports, notification unsubscribes, and p99 latency. Because treatment viewers send invitations to control-group receivers—a spillover effect called network interference—validate major launches with graph-cluster randomization, assigning tightly connected communities to the same experiment arm.
- Graceful degradation under 100 ms p99: If the Feature Store exceeds its 40 ms timeout, skip GBDT scoring and return candidates ordered by precomputed
AA_normfrom the Candidate Store. If the Live Graph Service is unreachable, point-check the top 30 ranked candidates directly against the shardedfriendships,invites, andblocksprimary keys before returning the first 20 clean items.
- Item independence fails: Standard NDCG assumes slot 4's relevance does not depend on what happened in slot 1. In a social graph, the moment
Summary of key trade-offs and scaling path
- Scaling beyond 100M users: Today the 81 GB CSR graph replicates onto every batch worker with zero network shuffle. If the platform grows 5x (400 GB CSR), partition users across workers and ship only capped neighbor lists (
M = 300) across shards. Even at larger scale, a daily full recompute beats an "incremental 2-hop batch": because each user has ~200 friends, almost every active user has at least one friend who added an edge today, meaning a 2-hop invalidation wave touches nearly 100% of users anyway. - Capping hubs (
M = 300) vs. 2-hop recall: Cuts batch work from10^13+to5 * 10^12updates (~70 core-hours) while dropping only weak hub ties thatAA_normwould heavily discount anyway. - Bounded graph heuristics vs. ML ranking:
AA_norm, Jaccard, and Cosine normalize degree bias cheaply in[0, 1]for top-500 retrieval and timeout fallback, while the two-head GBDT blends interaction history and outputs calibrated probabilities. - Pointwise calibrated two-head GBDT vs. listwise LTR: Calibration lets us multiply
P(invite) * P(accept)and apply minimum quality thresholds to protect receivers from spam, trading away a small amount of pure list-order optimization. - Daily batch retrieval + read-time deltas vs. full streaming fan-out: Pushing every new edge
(u, v)into 2-hop candidate lists would triggerd(u) + d(v)writes per friendship; expandingu's own post-snapshot edges at read time delivers instant freshness foruat tiny cost.
- Scaling beyond 100M users: Today the 81 GB CSR graph replicates onto every batch worker with zero network shuffle. If the platform grows 5x (400 GB CSR), partition users across workers and ship only capped neighbor lists (
Intuition & how it works
Think of recommending friends like hosting a neighborhood party: if your close friend Maya (who only knows 30 people) introduces two guests, there is a high chance they already run in the same circle; if a famous stadium speaker (who has 15,000 connections) knows two people in the crowd, that overlap means almost nothing. Even further, a good introduction requires both people to say yes—the viewer must want to send an invite, and the recommended person must want to accept it—so our system combines degree-normalized graph overlap for fast candidate discovery with a two-sided machine learning model for final ranking.
A naive approach—running a live SQL self-join to find friends-of-friends at request time and sorting by raw mutual-friend count—fails in three ways at 100 million users. First, a single celebrity "hub" with 10,000 connections creates 10,000 * 9,999 (~100 million) 2-hop pairs, blowing past a 100 ms latency budget. Second, raw mutual-friend counts grow with total friend count, so hubs share the most mutual friends with everyone and crowd out genuine peers. Third, optimizing only whether the viewer clicks "Connect" spams popular users with invitations they never accept.
Walk through a tiny concrete example for viewer u (who has 200 friends):
1. Capped 2-hop retrieval: Offline, a batch worker walks u's friends, keeping only each friend's top M = 300 closest connections so hubs cannot explode compute, and finds Candidate A (a public hub with 10,000 friends and 12 mutuals with u) and Candidate B (a college peer with 150 friends and 8 mutuals with u).
2. Bounded scoring in [0, 1]: Raw counts prefer hub A (12 > 8), but Jaccard similarity—the size of the shared friend set divided by the combined friend set, CN / (d(u) + d(c) - CN)—scores peer B at 8 / (200 + 150 - 8) = 0.0234 versus hub A at 12 / (200 + 10000 - 12) = 0.0012, cleanly promoting peer B into u's precomputed top-500 candidate pool.
3. Live filtering + two-head ML ranking: When u opens the app, the server merges any 2-hop candidates from friends u added today, filters out anyone u already connected with or blocked, fetches interaction and profile features, and ranks by P(invite | examined) * P(accept | invite)—putting peer B (0.25 * 0.60 = 0.150) far ahead of hub A (0.08 * 0.02 = 0.0016) well within 100 ms.
Key trade-offs
- Capping hub neighbor lists (
M = 300) vs. full 2-hop recall. Capping each intermediate friend's list to their 300 strongest connections keeps the daily batch job near 70 core-hours instead of lettingd(v)^2hub paths dominate runtime. Because neighbor rows are pre-sorted by interaction strength, the dropped paths are weak acquaintances of hubs—the exact paths Adamic-Adar (a graph score that weights each shared friendwby1 / ln(d(w))so hubs count less) would heavily discount anyway—though mutual counts become slight lower bounds. - Choice of bounded
[0, 1]graph heuristic. Jaccard (CN / (d(u) + d(c) - CN)) penalizes high-degree candidates most harshly, Cosine similarity (CN / sqrt(d(u) * d(c))) softens the degree penalty with a square root, and Normalized Adamic-Adar (AA(u, c) / sqrt(A(u) * A(c))) also discounts shared friends who are hubs themselves. Using Normalized Adamic-Adar for top-500 retrieval while feeding all three plus rawCNinto the ML model avoids forcing a single rigid formula. - Precomputed batch candidates + read-time deltas vs. pure online traversal. Precomputing the top 500 candidates daily in an 81 GB Compressed Sparse Row (CSR) in-memory array (a flat, pointer-free graph layout) removes expensive 2-hop walks from the 100 ms request path, trading up to 24 hours of staleness on distant edges. Expanding only the viewer's own post-snapshot edges at read time and checking exclusions against a live in-memory graph hides that staleness where users actually notice it.
- Pointwise calibrated two-head ranking vs. listwise learning-to-rank. Training Gradient-Boosted Decision Trees (GBDT) (ensembles of shallow trees trained sequentially on residual errors) with pointwise logistic loss produces calibrated probabilities—scores matching true empirical rates—so we can multiply
P(invite) * P(accept)and suppress low-quality suggestions below an absolute threshold. Listwise learning-to-rank (models like LambdaMART that directly optimize list order) can squeeze out slightly higher offline ranking scores, but its uncalibrated scores cannot be multiplied or thresholded across surfaces. - Logged-impression re-ranking vs. temporal holdout evaluation. Re-ranking historical viewport impressions (cards visible at least 50% on screen for at least 1 second) evaluates ordering cleanly on seen items but cannot credit candidates the old policy never showed. A temporal holdout (freezing the graph at time
Tand labeling all friendships formed in[T, T + 14 days]) captures retrieval recall too, at the cost of mild bias toward the incumbent model that helped generate some of those connections.
Common mistakes
- Ranking or retrieving by raw mutual-friend count, which recommends the same high-degree hubs to millions of users and treats 10 mutuals out of 30 identically to 10 out of 10,000.
- Running uncapped friends-of-friends self-joins, where each hub of degree
dtriggersd * (d - 1)pair operations and stalls both batch jobs and live databases. - Filtering existing friends only during the daily batch, causing embarrassing recommendations of people the viewer just connected with, invited, or blocked minutes ago.
- Defining offline NDCG relevance labels from mutual-friend counts, making Normalized Discounted Cumulative Gain (NDCG)—a top-weighted ranking metric normalized to
[0, 1]—circularly reward the model for repeating its own input feature rather than predicting accepted connections. - Treating every server-returned card as a negative training example, ignoring that slots 4–20 in a horizontal carousel are rarely scrolled into view; only logged viewport impressions should become negatives.
- Optimizing invite clicks without modeling receiver acceptance, which boosts short-term invites sent while flooding popular receivers with unwanted requests and driving up blocks and opt-outs.
- Measuring only PYMK-attributed connections in the online A/B test, which mistakes cannibalization (intercepting connections users would have found via search anyway) for true network growth.
Follow-up questions
- How do you generate strong connection suggestions for brand-new members whose friend lists are empty or nearly empty? When a user has zero edges, 2-hop graph traversal returns nothing, so we source candidates from non-graph channels: consented address-book contact uploads (plus "reverse contact" matches where existing members uploaded the new user's email or phone), the inviter who referred them, and profile-attribute cohorts (same school + graduation year, current employer, or city). Our GBDT ranker already takes viewer degree and account age as features, allowing tree splits to shift weight automatically toward profile and contact features when
d(u) < 5, while a small exploration slot gathers fresh feedback. The moment the user accepts even 1–2 connections, our read-time delta path immediately expands those new friends' capped neighbor lists without waiting for the nightly batch, exiting cold start within seconds. - How does slot visibility in horizontal suggestion carousels distort historical training labels, and how do you debias the ranker? In a horizontal carousel showing ~3 cards at a time, slot 1 receives far higher visual attention than slot 3, and slots 4–20 get zero attention unless the user swipes, so historical logs over-label top slots with positives and conflate slot visibility with true candidate affinity. First, log client-side viewport impressions (
>= 50%visible for>= 1 s) so off-screen cards are excluded rather than labeled as negatives. Second, include display position and UI surface in a separate shallow examination branch during pointwise training (logit P(invite | shown at k) = exam_bias(k, surface) + relevance_logit(u, c)) and dropexam_biasat serving time so every candidate is scored as if examined in slot 1. Third, run a 1% randomized adjacent-pair swap slice to measure slot examination probabilitiesp_kdirectly, and apply Inverse Propensity Weighting (IPW)—reweighting observed outcomes by1 / p_k(clipped at10to control variance)—during offline metric evaluation and pairwise ranker training. - How would you update the graph index so newly accepted friendships immediately influence candidate retrieval without expensive write amplification? Publish every edge creation, deletion, invite, block, and dismissal to a user-partitioned event stream (such as Kafka) consumed within seconds by an in-memory Live Graph Service that maintains each user's current 1-hop neighbor set plus a small list of edges added since the last daily CSR snapshot, while simultaneously invalidating both users' cached PYMK responses. Eagerly pushing every new edge
(u, v)to all affected 2-hop lists would required(u) + d(v)candidate-store writes per friendship—which explodes wheneveruorvis a hub—so we only push eagerly whenuorvis a low-degree cold-start user (d < 20). For everyone else, we pull on read: when viewerurequests PYMK, the server fetchesu's batch top-500 candidates in parallel with the capped neighbor lists ofu's own post-snapshot friends (typically 0–3 lists of<= 300IDs), filters against the live 1-hop exclusion set, and feeds the merged pool to the ranker within our 100 ms p99 budget.
Follow-up questions
- How do you generate strong connection suggestions for brand-new members whose friend lists are empty or nearly empty?
- How does slot visibility in horizontal suggestion carousels distort historical training labels, and how do you debias the ranker?
- How would you update the graph index so newly accepted friendships immediately influence candidate retrieval without expensive write amplification?
Similar questions
- Streaming Network Log Intrusion Detection with Sliding Windows
- RAG-Based Product Recommendation API Design
- Integrating Vision-Language Models Safely into Autonomous Driving
- Asynchronous RL Alignment Architecture for Live Chat Models
- Hybrid Talent Search and Ranking Architecture
- Local Document RAG CLI and Streaming Service with Mistral