Course contentsShow
← System Design
Lesson 472 of 1,91913. NoSQL: Graph DatabasesFree lesson

Social Networks and Friend-of-Friend Queries

Designing social graphs where multi-hop friend connections are first-class queries requiring efficient traversal.

Social Networks and Friend-of-Friend Queries

You'll learn why social network data models require efficient multi-hop traversal through relationship chains.

The Relationship Challenge

In social networks like LinkedIn or Facebook, one of the most common queries is "who are my friends' friends?" or "how am I connected to this person?" These multi-hop queries traverse relationship chains: you → your friend → their friend. In a relational database, this requires self-joins for each hop, which becomes exponentially slower as you go deeper (friends of friends of friends...).

Graph databases treat relationships as first-class citizens. Instead of storing friendship as rows in a junction table and reconstructing paths through joins, graphs store direct pointers between nodes. When you query "friends of friends," the database follows pre-existing edges, making traversal nearly instant regardless of depth.

Why This Matters for Design

Consider finding everyone within 3 degrees of separation from you. In SQL, that's three self-joins on a users table:

SELECT u3.* FROM users u1
JOIN friends f1 ON u1.id = f1.user_id
JOIN users u2 ON f1.friend_id = u2.id
JOIN friends f2 ON u2.id = f2.user_id
JOIN users u3 ON f2.friend_id = u3.id

Each hop adds complexity and scans millions of rows. In a graph database using index-free adjacency, each node directly links to its neighbors, so traversing 3 hops means following 3 pointers—a fundamentally O(k) operation per path, not O(n³).

Social Graph Patterns

Friend-of-friend queries enable features like mutual friends, suggested connections, network reach analysis, and influence scoring—all relationship-centric operations that are natural graph traversals but painful relational queries.

Key Takeaway: Social networks demand efficient multi-hop traversal through relationship chains, making graph databases ideal because they store connections as navigable edges rather than reconstructed joins.