Video in progress

In a social network, how do you find the "shortest friendship chain between two users" on a graph with 500 million nodes?

A plain BFS multiplies the number of nodes at each layer by the average degree, so in 3-4 steps you have millions of nodes. Bidirectional BFS walks from both ends and meets in the middle, cutting the number of visited nodes to roughly the square root. On top of that you need a depth limit, bypassing hot nodes, and graph sharding.

📖 Answer

With an average of 200 friends, BFS gives: step 1 is 200, step 2 is 40 thousand, step 3 is 8 million, step 4 is 1.6 billion. If we walk from both sides, 2 steps each: 2 × 40 thousand = 80 thousand nodes, not 1.6 billion. The asymptotic difference: O(b^d) versus O(2·b^(d/2)).

The algorithm skeleton:

int distance(long a, long b, Graph g, int maxDepth) {
    if (a == b) return 0;
    Set<Long> seenA = new HashSet<>(Set.of(a)), seenB = new HashSet<>(Set.of(b));
    Set<Long> frontA = Set.of(a), frontB = Set.of(b);
    for (int depth = 1; depth <= maxDepth; depth++) {
        boolean expandA = frontA.size() <= frontB.size();   // we expand the smaller front
        Set<Long> front = expandA ? frontA : frontB;
        Set<Long> mine = expandA ? seenA : seenB, other = expandA ? seenB : seenA;
        Set<Long> next = new HashSet<>();
        for (long u : front)
            for (long v : g.friends(u)) {
                if (other.contains(v)) return depth;
                if (mine.add(v)) next.add(v);
            }
        if (next.isEmpty()) return -1;
        if (expandA) frontA = next; else frontB = next;
    }
    return -1;
}

Expanding the smaller front at each step is an important detail. If one side has a popular account, that side explodes.

The staff-level questions are outside the algorithm:

  • The graph doesn't fit on one machine: 500M nodes × 200 edges × 8 bytes ≈ 800 GB. The graph is sharded by ID, so every friends(u) is a network call. That's why I group the front by partition and send batch requests.
  • Superhubs: through an account with 50 million followers, "everyone is close to everyone in 2 steps". In many products such nodes aren't counted in a friendship chain or are handled separately.
  • The product doesn't show anything "farther than 3 steps". maxDepth = 3 strictly bounds the amount of work.
  • Precomputing a "friends of friends" list offline for every user: reads are cheap, but writes and memory are expensive. Materializing for active users and computing online for the rest is the usual compromise.
  • Privacy: whether the people in the middle of the chain may be visible isn't an algorithm question, but it determines that you need to return the path itself (by keeping a parent map).