← Building blocks

Deep relationship queries

Storage & data modellingsenior

"Friends of friends who like X" is many joins in SQL.

Say it like this

The hot query is a multi-hop traversal, friends of friends who like this, so I keep the graph in a store that follows adjacency in memory instead of joining the same table three times; for plain followers and following, two indexed tables are enough.

Basic solution

Use a graph database when traversals are the main query; otherwise an adjacency table in SQL is enough.

Neo4jNeptuneadjacency lists in Postgres

Shallow queries on tables, deep traversals on a graph

The follow graph lives in two indexed tables because every query is one hop. The fraud graph is small and the questions are four hops deep, so it goes in a graph store fed by CDC.

How it works

  1. Nodes (users, posts) and edges (follows, likes) are first-class records. Each node stores direct references to its adjacent edges, so following an edge from one node to the next is a pointer hop in memory, not an index lookup.
  2. A traversal starts from one node found by an index on a property such as user id, then walks edges hop by hop, keeping only the edges of the requested type and the nodes whose properties pass the filter at each step.
  3. Cost is proportional to the part of the graph touched, not to the total size, because each hop reads only the neighbours of the current nodes. A join, by contrast, probes an index whose cost grows with the table size at every hop.
  4. Queries are written as patterns (Cypher, Gremlin): match (me)-[:FOLLOWS]->(f)-[:FOLLOWS]->(fof) where not (me)-[:FOLLOWS]->(fof) return fof, count(*). The engine turns the pattern into a traversal plan.
  5. Scaling is hard: a graph has no natural partition key, so most engines keep the whole graph on one node and replicate it for reads. Partitioning the graph cuts edges, and every traversal that crosses a cut pays a network hop.
  6. The alternative for one-hop questions is an adjacency table in SQL: follows(follower_id, followee_id) indexed both ways. "Who does X follow" is one index range scan on follower_id; "who follows X" is one range scan on followee_id.

When the traversal depth decides it

  • One or two hops: relational or key-value, every time.
  • Three or more hops with filtering, or variable depth (shortest path): graph store.

Worked example

News feed follow graph

  • 300M users, average 200 follows: 60B edges. Stored twice (by follower and by followee) at 16 B each ≈ 2 TB. That is a sharded wide-column or relational table, not a graph database, because every query is one hop and 2 TB cannot sit in one graph node's memory.
  • Fan-out needs "followers of X": one partition read, sorted, paged. Feed read needs "who does X follow": the other table. Both one hop, both a single range scan.
  • Recommendation "people you may know": friends of friends. Two hops: 200 × 200 = 40K candidates per user, filter out existing follows, rank by mutual count. Doing this on every page view would be 40K row touches per request; as a nightly batch job over all users it is a joins-in-Spark problem, not a live graph query.
  • Where a graph store pays off: fraud rings in the ride platform. "Riders who share a payment card with drivers who share a device with banned accounts" is 4 hops with filters on a few million nodes; Neo4j answers that in milliseconds where the SQL version is four self-joins on a 100M-row table, each producing a large intermediate result.
  • Sizing that graph: 50M nodes, 300M edges, ~60 GB; it fits one well-provisioned node with read replicas, which is why the graph store is viable here and not for the follow graph.

Variants and when each wins

Adjacency tables in SQL or wide-column

  • One row per edge, follows(follower_id, followee_id), with an index in each direction so either side can be looked up. It wins for social edges at any size, because one hop is a range scan, two hops is a join, and the table shards like any other.

Native graph database (Neo4j, Memgraph)

  • Nodes hold pointers to their edges in memory, and queries are written as patterns with path algorithms built in. It wins for deep traversals on a graph that fits one node; reads scale with replicas, and sharding is weak.

Managed graph (Neptune, Cosmos DB Gremlin)

  • The same model run by a cloud provider, queried with Gremlin, SPARQL or openCypher. It wins when you want the traversal engine without operating it, with scaling limits similar to the native stores.

Graph processing offline (Spark GraphX, Pregel-style)

  • Whole-graph algorithms (PageRank, communities, connected components) run as batch jobs over the edge list in object storage. It wins for computations that touch every node, and is useless for live queries.

Keep edges in tables unless live queries go three hops deep or need paths; use a graph store for fraud, knowledge graphs and dependency analysis; use batch processing for whole-graph algorithms.

Failure modes

Using a graph database for a one-hop workload

  • You notice follower lists being slower than expected and the cluster unable to grow past one node. It happens because the data is huge and the queries are shallow, so the engine's strength (deep traversal in memory) is unused while its weakness (no sharding) is hit. Move the edges to a partitioned table, and keep the graph store for the deep queries only.

Supernodes

  • You notice any traversal that passes through a celebrity node (50M followers) taking seconds. It happens because one node has millions of edges, so every hop through it expands to millions of candidates. Cap or sample the edges taken from a supernode in the query, or precompute the aggregates that queries need from it.

Unbounded traversal

  • You notice a variable-length path query running until it is killed. It happens because the query has no depth limit or no filter on edge type, so the search space grows exponentially with each hop. Always bound the depth, filter on edge type at the first hop, and use bidirectional search for shortest-path queries.

Graph bigger than one machine

  • You notice memory pressure, cache misses and climbing latency on the graph store. It happens because graph stores need the adjacency structure in memory to be fast, and the graph has outgrown it. Prune old edges, keep only the subgraph the live queries need, and replicate for reads; if it still does not fit, the workload belongs in batch processing.

Consistency with the source of truth

  • You notice the graph saying A follows B while the application says otherwise. It happens because the graph is a derived copy fed by events, and some events were lost or applied out of order. Feed it from change data capture with idempotent upserts, and rebuild it from the source tables on a schedule.

Interviewer follow-ups

Answer out loud before you open each one.

Why is a join not a traversal?

A join scans or probes an index whose cost grows with table size, and three hops is three joins each producing an intermediate set. A traversal follows pointers from the start node and its cost depends only on the neighbourhood it visits. For small neighbourhoods on a huge graph the difference is orders of magnitude.

How would you store the follow graph for Twitter?

Two partitioned tables or one wide-column table with two layouts: by follower for the feed read and by followee for fan-out, written together. Billions of edges, one hop each way, no graph database needed.

How do you shard a graph?

You mostly do not. Partitioning cuts edges and a traversal that crosses a cut pays a network hop per edge. Practical answers are replicate the whole graph for reads, keep it small enough to fit, or partition by a community structure the data happens to have, like tenant.

Where do graph databases earn their keep?

Fraud and risk (shared devices, cards, addresses across accounts), knowledge graphs, recommendations computed live over a few hops, dependency and impact analysis. Common thread: deep, filtered traversals over a graph that fits in memory.

Connections

Pairs with
Default to a relational database · Append-heavy, time-ordered rows · Precompute on write, read cheaply · Process large data offline · React to database changes
Pulls against
Partition the data
Used in
News Feed (Twitter / X timeline)

The same parts on other clouds

The diagrams above name AWS services as one concrete example. Every part has a close equivalent elsewhere. In an interview, name the role first, such as “a managed Redis cache”, then the product you would pick.

AWSUsed here asGoogle CloudMicrosoft AzureOpen source and others
Amazon EC2 Auto ScalingFeed service, Fan-out workers, Risk serviceCompute Engine managed instance groupsVirtual Machine Scale SetsKubernetes Deployment with a HorizontalPodAutoscaler, Nomad
Amazon NeptuneFraud graph (Neo4j)Spanner GraphCosmos DB for Apache GremlinNeo4j, JanusGraph
Amazon AuroraAccounts, payments, devicesAlloyDB for PostgreSQL, Cloud SQLAzure Database for PostgreSQL or MySQLPostgreSQL, MySQL, CockroachDB
Amazon EMRNightly Spark jobDataprocAzure Databricks, HDInsightApache Spark, Databricks