SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
  • Relational Databases
  • Document Databases
  • Key-Value Databases
  • Full-Text Search Engines
  • Wide Column Databases
  • Time Series Databases
  • Graph Databases
  • Vector Databases
  • NewSQL Databases
  • Columnar Databases
  • In-Memory Databases
Part 5: Architecture
Part 6: Distributed Systems
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/Data and Storage/Database Types (Deep Dive)

Graph Databases

Store things and the links between them, and walk those links quickly (Neo4j).

โฑ 12 min readIntermediateHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

A graph database stores things and the links between them as first-class data. It is built to answer questions like "who are the friends of my friends?" quickly.

  • A node is a thing (a person, a product). An edge (or relationship) is a link (FOLLOWS, BOUGHT).
  • Both can hold properties (name, since=2021).
  • Walking links (traversal) is cheap, even many hops deep, because a node points straight to its neighbours.
  • Examples: Neo4j, Amazon Neptune, JanusGraph, ArangoDB, TigerGraph.

02Concept: What is it?

In a relational database, a link between two rows is rebuilt every time you ask, with a JOIN. The database finds matching ids using an index. One join is fine. Six joins in a row on large tables get slow.

A graph database stores the link itself. Many engines use index-free adjacency: each node keeps direct references to its neighbouring relationships. To move from a person to their friends, the engine follows these references. It does not search a big index at every hop. So the cost of a query depends on how much of the graph you touch, not on how big the whole database is.

The property graph model
๐Ÿ‘คPersonname: Asha
โ†’โ†“FOLLOWS since 2021
๐Ÿ‘คPersonname: Ben
โ†’โ†“WROTE
๐Ÿ“Postid: 42
โ†’โ†“TAGGED
๐Ÿท๏ธTopicdatabases
Nodes Edges (relationships)
Nodes have labels and properties. Edges have a type, a direction and can have properties too.
๐Ÿง Relationships are data, not an afterthought
In a graph, "Asha follows Ben" is a stored object you can query, label and add data to. You do not need a separate join table.

03Real-Life Example

๐ŸตThe Family Tree on the Wall
Imagine a big family tree drawn on a wall, with strings between people. To find a person's cousins, you put a finger on them and follow the strings up to the parents, over to the uncles and aunts, then down to their children. You never look through a phone book. A relational database is the phone book: for each step it must look up names again.
Family wall chart
Graph database
A person on the chart
A node with properties
A string between two people
An edge (relationship) with a type
Label on the string: parent of, married to
Relationship type
Following strings from a person
Traversal
Cousins = up, over, down
A graph pattern in a query
Looking through a phone book for each step
A join that searches an index for each hop
Shortest chain of people between two strangers
Shortest path query
Friends of friends, as strings
๐Ÿ™‹You
โ†’โ†“1 hop
๐Ÿ‘คFriend A
๐Ÿ‘คFriend B
โ†’โ†“2 hops
๐Ÿ‘ฅFriends of friendssuggestions

04Why Do We Need It?

๐Ÿ•ธ๏ธData full of links
When the links matter as much as the things, a graph is the natural shape.
๐ŸƒFast deep traversals
Four or five hops stay quick, while the same query as chained joins can grow very slowly.
๐ŸงฉSimple queries
A pattern like (a)-[:FRIEND]->(b)-[:FRIEND]->(c) is shorter and clearer than many joins.
๐Ÿ”„Flexible shape
Add a new type of node or link without rebuilding a schema.
๐Ÿ”ŽFind hidden patterns
Fraud rings, shortest routes and recommendations come from the shape of the data.
๐Ÿง Knowledge and context
Link facts together so software can answer questions about how things relate.
If your question is about the connections, store the connections.

05Where Do We Use It?

๐Ÿ‘ฅSocial networks
Friends, followers, โ€œpeople you may knowโ€.
๐Ÿ›๏ธRecommendations
People who bought this also bought that, through shared links.
๐Ÿ•ต๏ธFraud detection
Accounts that share a phone, device or address with a known bad account.
๐Ÿ—บ๏ธRoutes and networks
Roads, telecom links and supply chains.
๐Ÿ“šKnowledge graphs
Facts such as โ€œParis is the capital of Franceโ€ linked together.
๐Ÿ”Access and IT maps
Who can reach what, and which service depends on which.

06Types / Parts / How It Works

Models and query languages

ModelHow data looksQuery languageExample engines
Property graphNodes and edges, both can have properties and labels.Cypher, openCypher, GQL, GremlinNeo4j, Neptune, Memgraph
RDF (triple store)Facts as subject-predicate-object triples.SPARQLNeptune, GraphDB, Jena
Multi-modelGraph plus documents or key-value in one engine.AQL and othersArangoDB, Azure Cosmos DB (Gremlin API)
Graph analytics engineBig batch jobs over a graph (PageRank, communities).Pregel-style codeSpark GraphX, TigerGraph
A friends-of-friends query in Cypher (Neo4j)
MATCH (me:Person {name: 'Asha'})-[:FRIEND]->(f)-[:FRIEND]->(fof)
WHERE NOT (me)-[:FRIEND]->(fof) AND fof <> me
RETURN fof.name, count(f) AS mutualFriends
ORDER BY mutualFriends DESC
LIMIT 10;
The same idea in SQL needs a self-join per hop
SELECT f2.friend_id, COUNT(*) AS mutual
FROM friends f1
JOIN friends f2 ON f2.user_id = f1.friend_id
WHERE f1.user_id = :me
  AND f2.friend_id <> :me
  AND f2.friend_id NOT IN (SELECT friend_id FROM friends WHERE user_id = :me)
GROUP BY f2.friend_id
ORDER BY mutual DESC
LIMIT 10;
Relational (joins)
Tables and keys
  • Great for tabular data and totals
  • Each hop is an index search
  • Cost grows with table size and hops
  • Mature, universal tools
Graph (traversal)
Nodes and edges
  • Great for connected data
  • Each hop follows a pointer
  • Cost grows with the part of the graph you touch
  • Smaller ecosystem, harder to scale across machines
Where graph shines and where it does not
Good fit
Many hops over links
Shortest path, patterns
Poor fit
Sum / average over millions of rows
Simple key lookups
Pick the engine by the question you ask most.
VisualizerFriends of friends: graph traversal vs repeated joinsRaise the hops from 1 to 4, then grow the user count, then switch the relational side to no index.
Relational side
You1234567891011121314151617
Small sample (18 people). Colour = hops from You: amber 0, cyan 1, purple 2, green 3 or more.
People reached in the sample within 2 hops: 12 of 18
Graph database
Each person stores direct links to their friends. To go one hop you follow the links. No search, so cost does not depend on how big the whole table is.
Relational database
Friendships live in a table (user_id, friend_id). Each hop is a join: find the rows for that user (an index search), then repeat for every friend found.
People reached
10.1k
2 hops, about 100 friends each
Graph: steps
10.1k
pointer hops
SQL: steps (index)
12.8k
27 steps per lookup
SQL / graph
1.3x
Both read about 10.1k people at 2 hops. The graph just follows pointers (10.1k steps). SQL repeats an index search for each of 101 people (12.8k steps, 1.3 times more).

A simplified model with maths only (no random numbers). It ignores caching, overlap between friend lists, and the fact that a modern relational database is very good at shallow queries. The honest lesson: the gap grows with depth and data size, and graph databases shine when you hop many times.

07How to Use It / Steps / Implementation

Modelling and using a graph

  1. 1
    Start from the questions
    Write the questions first: โ€œwho is within 3 hops of this account?โ€ The questions decide what is a node and what is an edge.
  2. 2
    Nouns become nodes, verbs become edges
    Person, Product and Account are nodes. FOLLOWS, BOUGHT and OWNS are edges.
  3. 3
    Give edges a direction and a type
    FOLLOWS goes one way. Model both directions only when the meaning needs it.
  4. 4
    Keep properties small
    Put search keys on nodes (name, id). Keep large blobs elsewhere, such as object storage.
  5. 5
    Index the starting points
    A traversal needs a place to start. Index the properties you use to find the first node (email, id).
  6. 6
    Limit depth and fan-out
    Cap hops and results. A query that fans out through a very popular node can touch millions of edges.
  7. 7
    Plan for size
    Many graph engines run best on one big machine. Test how your engine scales or shards before you rely on it.
โš ๏ธWatch the super-node
A super-node is a node with a huge number of links (a celebrity with 50 million followers). A traversal that passes through it explodes. Limit it, split it, or skip it in queries.
Query cost driversdepth, then fan-out, then super-nodes

08Key Terms to Know

TermMeaning in easy words
Node / vertexA thing in the graph, such as a person
Edge / relationshipA link between two nodes, with a type and a direction
PropertyA key=value stored on a node or an edge
LabelA tag that groups nodes, such as Person or Product
TraversalWalking from node to node along edges
HopOne step along an edge
Index-free adjacencyEach node holds direct references to its neighbours, so a hop needs no index search
Cypher / Gremlin / SPARQLQuery languages for graphs
Super-nodeA node with a very large number of edges
Knowledge graphA graph of facts about the world, used to answer questions

09Pros, Cons and Trade-offs

โœ… Pros
  • Deep link queries stay fast
  • Natural model for connected data
  • Short, readable queries
  • Flexible schema
  • Great for recommendations, fraud and paths
โš ๏ธ Cons
  • Weaker for bulk totals and reports
  • Scaling across many machines is harder (cutting a graph cuts edges)
  • Smaller ecosystem and fewer people know it
  • Super-nodes cause hot spots
  • Another system next to your main database

Trade-offs

ChoiceWe gainWe lose
Graph databaseFast many-hop queries, clear modelHarder horizontal scale, narrower use
SQL with joinsOne familiar system, strong for reportsSlow and long queries for deep links
Recursive SQL (CTE)Stay in one database for shallow graphsGets slow at depth and size
Store both directions of an edgeEasy reverse queriesMore storage and writes
Keep graph as a read copyMain database stays simpleSync delay and an extra pipeline

10Common Problems and Mistakes

Common mistakes

  1. Using a graph for everything. If you mostly do key lookups or reports, a graph is the wrong tool.
  2. Modelling attributes as nodes. A colour or a date often belongs as a property, not a new node.
  3. Unbounded traversals. A query without a depth limit can touch the whole graph.
  4. Ignoring super-nodes. One celebrity node can slow every query that passes it.
  5. No start index. Finding the first node by scanning every node ruins the benefit.
  6. Assuming it scales like a key-value store. Partitioning a connected graph is a hard problem.

Things to watch

๐ŸŒŸSuper-nodes
Very popular nodes create hot spots and huge fan-out.
โœ‚๏ธSharding a graph
Any cut separates connected nodes, so queries cross machines.
๐Ÿ”Keeping copies in sync
A graph beside your main database must be fed by events or batch jobs.
๐ŸงฎHeavy analytics
Whole-graph algorithms (PageRank) often run on a separate batch engine.

11Real-World Examples

๐Ÿ’ผProfessional networks
Connection suggestions and shared contacts are graph questions at huge scale (general idea).
๐Ÿ’ณBanks and payments
Graph queries link accounts, devices and cards to spot fraud rings.
๐Ÿ”Knowledge graphs
Search engines and assistants link entities and facts to answer questions.
๐Ÿ›’Retail recommendations
Customer, product and category links drive โ€œyou may also likeโ€.
๐Ÿ“กNetwork and IT maps
Telecom and cloud teams map dependencies to find what breaks if one thing fails.
๐ŸงฌLife sciences
Genes, proteins and drugs are linked to find new connections.
๐Ÿ“Note
These are general ideas. Companies often run a graph store beside a main database, and details differ.
Mini case: fraud ring detection
๐ŸงพNew account
โ†’โ†“uses
๐Ÿ“ฑDevice X
โ†used by
๐ŸšฉKnown fraud account
๐ŸšฉAnother flagged account
Being checked Flagged
Shared devices and phones link accounts that look separate in a normal table.

12Related Topics to Read Next

Common Database Typesโ†’

Where graph sits next to the other database families.

Relational Databasesโ†’

The join-based way to model links, to compare against.

SQL vs NoSQLโ†’

When to leave the relational model.

Indexingโ†’

A graph traversal still needs an index to find its starting node.

Shardingโ†’

Why splitting a connected graph across machines is hard.

Denormalizationโ†’

Another way to speed up link-heavy reads in SQL.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • โœ”What: a database of nodes and edges, with properties on both.
  • โœ”Strength: many-hop queries (friends of friends, paths, patterns).
  • โœ”Why fast: a hop follows a stored reference, not an index search.
  • โœ”Languages: Cypher, Gremlin, SPARQL.
  • โœ”Use for: social, recommendations, fraud, knowledge graphs, networks.
  • โœ”Avoid for: big reports, simple key lookups, easy sharding.
  • โœ”Danger: super-nodes and unbounded depth.
  • โœ”One line: โ€œIf the links are the question, store the links.โ€
โ† Previous
Time Series Databases
Next โ†’
Vector Databases