Graph Databases

Difficulty: Intermediate

Question

When would you use a graph database like Neo4j instead of a relational database?

Answer

Use a graph database when the relationships between records are the main thing you query, especially multi-hop traversals of unknown depth such as "friends of friends", "accounts linked to this fraud ring", or "shortest path between two stations". Graph databases store edges as first-class data, so following a relationship is a direct pointer hop instead of a join that gets more expensive at each level.

How a graph database models data

  • Nodes are entities: User, Account, Device, Merchant.
  • Relationships (edges) connect two nodes, have a type and direction, and can carry properties: (:User)-[:PAID {amount_paise: 50000}]->(:Merchant).
  • Properties are key-value pairs on both.

This is the labeled property graph model used by Neo4j, Memgraph and Amazon Neptune (which also supports RDF). Queries use Cypher or openCypher, Gremlin, or the newer ISO standard GQL published in 2024.

Why traversals are cheap

In a relational database, "friends of friends of friends" is three self-joins on a friendships table, and each join probes an index, so cost grows with the size of the intermediate result sets. Neo4j uses index-free adjacency: each node record points directly to its relationships, so a traversal cost depends on how many edges you actually walk, not on the total size of the table. Variable-length patterns like -[:KNOWS*1..4]-> are natural to write.

Good use cases

  • Fraud detection: in UPI or card payments, link accounts, phone numbers, devices and IP addresses, then look for rings where many "different" users share one device.
  • Recommendations: "people who bought this also bought", or course recommendations based on what similar learners completed.
  • Social networks: mutual connections, degrees of separation.
  • Knowledge graphs, identity and access graphs, network topology, supply chains where dependencies chain many levels deep.

When a relational database is still better

SituationBetter fit
Aggregations, reports, sums over many rowsRelational or columnar
Fixed shape, shallow relationships (orders and items)Relational
Strong multi-table transactions and mature toolingRelational
Deep or variable-depth relationship queriesGraph
Path finding, centrality, community detectionGraph

PostgreSQL can handle moderate graph needs with recursive CTEs (WITH RECURSIVE), and the Apache AGE extension adds openCypher. The SQL:2023 standard also added property graph queries (SQL/PGQ). Many teams keep the system of record in PostgreSQL and project relationship data into a graph store for the specific traversal workloads.

Gotchas

  • Very high-degree "supernodes" (a celebrity with millions of followers) can make traversals slow; you need direction and type filters.
  • Horizontal sharding of graphs is hard because traversals cross partitions.
  • Choosing a graph database just because data "has relationships" is a mistake; all relational data has relationships.
A fraud ring query as graph traversal. Each hop follows stored edges directly instead of running another join.
  1. Start at a flagged account: Lookup by indexed property such as account id.
  2. Hop to devices it used: Follow USED_DEVICE edges.
  3. Hop to other accounts on those devices: Follow USED_DEVICE edges backwards.
  4. Hop to shared payees: Follow PAID edges to merchants or VPAs.
  5. Score the connected cluster: Ring size and shared links drive the risk score.

Code examples

Cypher: accounts sharing a device with a flagged account

// Neo4j Cypher (run in cypher-shell or Neo4j Browser)
MATCH (flagged:Account {id: 'ACC-1001'})-[:USED_DEVICE]->(d:Device)
      <-[:USED_DEVICE]-(other:Account)
WHERE other <> flagged
RETURN other.id AS suspect, count(DISTINCT d) AS shared_devices
ORDER BY shared_devices DESC
LIMIT 20;

// Friends of friends up to 3 hops
MATCH (me:User {id: 42})-[:FOLLOWS*1..3]->(u:User)
RETURN DISTINCT u.name LIMIT 50;

Patterns describe the shape of the connection; variable-length hops replace a stack of self-joins.

Same 3-hop traversal with a recursive CTE in PostgreSQL

WITH RECURSIVE reach AS (
  SELECT followee_id AS user_id, 1 AS depth
  FROM follows WHERE follower_id = 42
  UNION
  SELECT f.followee_id, r.depth + 1
  FROM follows f
  JOIN reach r ON f.follower_id = r.user_id
  WHERE r.depth < 3
)
SELECT DISTINCT user_id FROM reach;

Works fine for small graphs, but intermediate result sets grow quickly with depth and fan-out.

Key points

  • Graph databases store nodes, typed relationships and properties as first-class data.
  • Index-free adjacency makes each hop cost proportional to edges walked, not table size.
  • Best for deep or variable-depth traversal: fraud rings, recommendations, social graphs.
  • Relational is better for aggregations, reporting and shallow fixed relationships.
  • PostgreSQL recursive CTEs or Apache AGE can cover modest graph needs.

Common follow-up questions

  • What is index-free adjacency and why does it matter?
  • How would you model a UPI fraud detection graph?
  • What is the supernode problem and how do you mitigate it?
  • Why is sharding a graph database harder than sharding a key-value store?

Interview tips

  • Anchor the answer in a query shape (multi-hop, unknown depth) rather than "data with relationships".
  • Give a concrete Indian-context example like UPI fraud rings sharing devices; it makes the use case memorable.
  • Mention that relational databases can still do this with recursive CTEs, and explain where they stop scaling.

Concepts covered

Graph Database, Neo4j, Cypher, Index-Free Adjacency, Traversal

More Database Design questions