Graph Databases
"Graph databases do not use JOINs. Rather, relationships are stored natively alongside the data elements (nodes) in a more flexible format, which allows the optimization of data traversing and millions of connections to be accessed per second." — Neo4j, What is a graph database, Getting Started documentation
Summary: A graph database stores things and the typed, directed connections between them as first-class data, so "who is connected to whom, through what, in how many steps" becomes a native operation instead of a chain of joins. Focus: The property graph versus RDF, how native stores make a hop cheap, what a recursive CTE can and cannot do instead, Cypher/GQL/Gremlin/SPARQL, the products (Neo4j, Neptune, Memgraph, TigerGraph, JanusGraph, Apache AGE), algorithms, modeling, sharding limits, and Go and Laravel code. Learning goal: Decide with evidence whether a workload needs a graph engine, model it without the classic traps, and write the same traversal in Cypher, Gremlin, SPARQL and PostgreSQL SQL.
This page is the complete reference for graph databases: the data models (labeled property graph, RDF triples, hypergraphs), the storage idea called index-free adjacency, native versus non-native engines, the query languages (Cypher, openCypher, ISO GQL, Gremlin, SPARQL, SQL/PGQ), the products (Neo4j, Amazon Neptune, Memgraph, TigerGraph, JanusGraph, Apache AGE), the PostgreSQL alternatives (recursive CTEs, ltree, adjacency lists), graph algorithms (shortest path, PageRank, community detection, centrality), modeling, indexes, transactions, why sharding a graph is hard, and where it fits in an architecture. The neighbouring pages hold the surrounding ideas: the map of NoSQL families is NoSQL: Families & Data Models, edge-table design is in Schema Design, the composite index behind every relational hop is in Indexing, join algorithms are in Query Planning, and why one machine eventually is not enough is in Partitioning & Sharding.
Page map
| If you are looking for | Go to |
|---|---|
| Tables you can memorise in one minute | Everything in one minute |
| Why graph databases exist, and the first three misunderstandings | Why graph databases exist |
| History: Cypher, openCypher, GQL, TinkerPop, RDF | Where it comes from |
| One concept with a timeline and code | The concept catalogue |
| Labeled property graph, RDF, SPARQL | Property graph, RDF |
| Index-free adjacency, native vs non-native | Index-free adjacency |
| Graph traversal vs recursive joins and benchmark caveats | Traversal vs joins |
| Cypher, GQL, Gremlin, SPARQL side by side | Query languages |
| Nodes, edges, properties, hyperedges, time | Modeling |
| Indexes, constraints and full-text in a graph store | Indexes |
| Transactions, consistency, supernodes | Transactions, Supernodes |
| Why you cannot just shard a graph | Sharding |
| PageRank, Louvain, shortest path, GDS | Graph algorithms |
| GraphQL is not a graph database | GraphQL |
| Neo4j, Neptune, Memgraph, TigerGraph, JanusGraph, AGE compared | Per-product behaviour |
| Neo4j store files, page cache, transaction log, clustering | Mechanics |
| Friends-of-friends, shortest path, fraud rings, recommendations, impact analysis in SQL, Cypher, Go, Laravel | Solving the classic problems |
| Use cases and when not to use a graph database | Use cases, Choosing |
| Monolith to distributed data | In architecture |
| Reproduce Neo4j vs PostgreSQL timing in Docker | Lab |
| Wrong beliefs, cheat sheet, questions, terms | Misconceptions, Cheat sheet, Self-check, Glossary |
Everything in one minute
The models. Every row is unpacked in the concept catalogue.
| Model | Unit of data | Edge can carry properties? | Typical language | Typical products | Best at |
|---|---|---|---|---|---|
| Labeled property graph (LPG) | Node with labels and key/value properties; relationship with one type, a direction and properties | Yes | Cypher, GQL, Gremlin | Neo4j, Memgraph, TigerGraph, JanusGraph, Neptune, Apache AGE | Application queries that follow paths |
| RDF (triples, quads) | Triple: subject, predicate, object (plus a graph name in quads) | Not in the basic model (reification, RDF-star, named graphs) | SPARQL | Neptune (SPARQL), Apache Jena, Stardog, GraphDB, Oracle RDF Graph | Interchange, ontologies, reasoning, linked data |
| Relational tables with edge tables | Rows; edges are rows in a join table | Yes, as columns | SQL, recursive CTEs | PostgreSQL, MySQL, SQL Server, Oracle, SQLite | Data that is mostly tabular with some shallow graph questions |
| Document with references | Documents; edges are ids or $graphLookup | Yes, inside the document | MongoDB aggregation | MongoDB | Occasional bounded traversal inside documents |
| Hypergraph | Edge that connects more than two nodes | Yes | Rare natively; modeled as an extra node | HyperGraphDB (rare) | N-ary relationships |
The things you keep reading.
| Keyword | In plain words | Tiny example | Where it matters |
|---|---|---|---|
| Index-free adjacency | A node points straight at its relationships; no index lookup per hop | Ann's record holds the address of her first FOLLOWS record | Deep traversals |
| Native vs non-native graph storage | Storage laid out for graphs, or a graph API on top of another store | Neo4j (native) vs JanusGraph on Cassandra (non-native) | Latency, operations |
| Recursive CTE | A SQL query that feeds its own output back in until nothing new appears | WITH RECURSIVE reach ... | Graph questions in PostgreSQL, MySQL, SQL Server, SQLite |
| Variable-length path | A pattern with a hop range | (a)-[:FOLLOWS*1..3]->(b) | Cypher, Gremlin repeat().times() |
| Quantified path pattern | The GQL-aligned spelling of the same idea | (a)-[:FOLLOWS]->{1,3}(b) | Cypher 25 / Neo4j 5.9+ |
| Shortest path | Fewest hops (or lowest cost) between two nodes | Six degrees of separation | Routing, social, network |
| Supernode (dense node) | A node with millions of edges | A celebrity, a country, a popular tag | Traversal blow-ups |
| Edge cut | The edges severed when you split a graph across machines | Friend edges crossing two shards | Why graph sharding is hard |
| Property graph vs GraphQL | A data model vs an API query language | GraphQL can sit on top of PostgreSQL | Naming confusion |
The three things to do.
| Situation | Do this |
|---|---|
| The question is a shallow, bounded hierarchy (categories, org chart) | Adjacency list or ltree in PostgreSQL; no new database |
| The data is already in PostgreSQL and traversals are occasional | WITH RECURSIVE with a depth bound or CYCLE clause, or Apache AGE; measure first |
| Paths across many relationship types are the core workload, or you need graph algorithms | A native graph database (Neo4j, Memgraph, Neptune, TigerGraph) fed from the system of record |
Why graph databases exist
Relational databases are excellent at "give me rows that match this condition" and at set operations across tables. They are clumsy at questions whose shape is a walk: "who are the friends of my friends who also bought this", "which accounts share a device with a known fraudster, up to four steps away", "every service that breaks if this library breaks". In SQL each step of the walk is a join, the number of joins is fixed when you write the query, and the planner must estimate how large each intermediate result will be. A graph database makes the relationship a stored, typed, directed object and gives you a language where the walk is the query.
| SQL / relational | Graph database |
|---|---|
| Relationships are derived at query time by joining on foreign keys | Relationships are stored and traversed |
| Depth is fixed by the number of joins you write (or by a recursive CTE you bound) | Depth is a range in the pattern: *1..5, {1,5}, repeat().times(5) |
| New relationship type: new table or new foreign key plus migration | New relationship type: just create it; schema is optional |
| Strong at aggregates over millions of rows, reporting, constraints | Strong at paths, neighbourhoods, patterns, algorithms |
| One mature, well-tooled model for tabular data | A second system with its own backup, security and tooling |
The analogy we reuse on this page: a rail map and a timetable. The rail map is a graph: stations are nodes, lines are edges, and "can I get from A to D with at most three changes" is tracing a finger along lines. The timetable is a table: perfect for "list every departure from X between nine and ten", clumsy for multi-change routes because you keep looking up the next leg. Neither is wrong; they answer different questions.
Three common misunderstandings, up front
- "A graph database is just a faster way to do JOINs." It is a different data model with a different query language and, in native engines, a different storage layout. For one hop or a whole-table aggregate it is often slower than a well-indexed relational table. See Traversal vs joins.
- "Graph databases and GraphQL are the same thing." GraphQL is an API query language for clients. It can be served from PostgreSQL, MongoDB or a graph store. See GraphQL.
- "A graph database scales out like Cassandra or DynamoDB." Graphs have no natural partition key: edges cross every cut. Most graph engines scale reads with replicas and scale writes by a bigger machine or a distributed engine with real trade-offs. See Sharding.
Where it comes from
Two strands meet in graph databases. The first is the data model. Apache TinkerPop's reference documentation says that when a mathematical graph is used for real data it "is extended to support both labels and key/value properties. This structure is known as a property graph. More formally, it is a directed, binary, attributed multi-graph." The second strand is the query language. Neo4j's Cypher appeared in 2010 and was later opened as the openCypher specification. In April 2024 ISO published GQL as ISO/IEC 39075:2024; Neo4j's announcement calls it "a peer language to SQL and the first new ISO database language since 1987". (The ISO page itself returned a bot challenge from the environment used to write this page, so the standard number and date rest on Neo4j's post and Wikipedia's Graph Query Language article, which give April 2024 and ISO/IEC 39075:2024.) The same family of ideas reached SQL as SQL/PGQ, Property Graph Queries, added to the SQL standard in 2023 and supported by some engines such as Oracle Database 23ai; this chapter does not rely on it, and you should check your database's release notes before using it.
RDF is a separate lineage from the W3C semantic web work (RDF 1.1 Concepts, 2014; SPARQL 1.1). Its unit is the statement, not the node. Gremlin comes from Apache TinkerPop and takes the opposite approach to Cypher: a query is a chain of traversal steps, an imperative-looking pipeline, instead of a declarative pattern.
| Year | Event | Why it matters |
|---|---|---|
| 1999 to 2004 | W3C RDF and the semantic web family; RDF 1.0 in 2004 | Origin of triples, URIs and ontologies |
| 2007 onward | Neo4j property graph engine (Java), native storage | The first widely used native LPG database |
| 2010 | Cypher | Declarative ASCII-art pattern matching |
| 2009 to 2015 | Apache TinkerPop and Gremlin; Titan, then JanusGraph | A vendor-neutral traversal API on top of many stores |
| 2013 | SPARQL 1.1 | Property paths (+, *), updates, federation |
| 2015 | openCypher open specification | Cypher implemented by Memgraph, Neptune, TigerGraph, AGE and others |
| 2023 | SQL/PGQ in the SQL standard | Graph pattern matching inside SQL |
| April 2024 | ISO/IEC 39075:2024 GQL | First standalone ISO graph query language |
The concept catalogue
Labeled property graph Must-know
In plain words: a graph where every thing is a node, every connection is a directed edge with one type, and both can carry labels and key/value properties.
Common misunderstanding: "An edge is just a foreign key." A foreign key has no type of its own, no direction you can reverse cheaply, and no properties. An edge in a property graph is a stored object: (ann)-[:KNOWS {since: 2019}]->(bob) keeps the since on the edge, not in a join table.
Definition: a directed, attributed multigraph. Neo4j states the rules: relationships "must always have a start node, an end node, and exactly one type"; nodes may have zero or more labels; both carry properties. Multiple edges of the same type between the same two nodes are allowed.
┌────────────┐ KNOWS {since: 2019} ┌────────────┐
│ :Person │ ──────────────────────▶ │ :Person │
│ name: Ann │ │ name: Bob │
└─────┬──────┘ └─────┬──────┘
│ WORKS_AT {role: 'CTO'} │ WORKS_AT {role: 'Dev'}
▼ ▼
┌──────────────────────────────────────────────────┐
│ :Company name: Acme │
└──────────────────────────────────────────────────┘Real scenarios: an identity graph (person, email, phone, device, card), a service dependency graph, a product catalogue with SIMILAR_TO edges, a permission graph (user, group, role, resource).
| Model feature | Neo4j | Memgraph | Neptune | TigerGraph | JanusGraph | Apache AGE |
|---|---|---|---|---|---|---|
| Labels on nodes | Many labels per node | Many labels per node | One label in Gremlin, openCypher labels | Vertex types (schema first) | Vertex label (one) | Label (one per vertex) |
| Edge properties | Yes | Yes | Yes | Yes | Yes | Yes (agtype) |
| Schema | Optional; constraints available | Optional | Schema-less | Schema-first (GSQL) | Optional, recommended | Schema-less in agtype |
Fix / how to use it: model nouns as nodes, verbs as relationship types, adjectives and quantities as properties; see Modeling. In SQL the same facts are three tables:
CREATE TABLE person (id bigint PRIMARY KEY, name text NOT NULL);
CREATE TABLE company (id bigint PRIMARY KEY, name text NOT NULL);
CREATE TABLE knows (
a_id bigint NOT NULL REFERENCES person(id),
b_id bigint NOT NULL REFERENCES person(id),
since date,
PRIMARY KEY (a_id, b_id)
);
CREATE TABLE employment (
person_id bigint NOT NULL REFERENCES person(id),
company_id bigint NOT NULL REFERENCES company(id),
role text,
PRIMARY KEY (person_id, company_id)
);RDF, triples and SPARQL Important
In plain words: RDF stores everything as three-part statements, "subject predicate object", such as "Ann knows Bob", where every name is a global identifier (an IRI).
Common misunderstanding: "RDF and property graphs are the same thing with different syntax." They are both graphs, but an RDF statement is a binary relation and cannot carry a property of its own in the basic model. The W3C spec says that "relations that involve more than two entities can only be indirectly expressed in RDF". Edge properties need reification, named graphs, or RDF-star.
Definition: an RDF graph is a set of triples; a triple "encodes a statement—a simple logical expression, or claim about the world" (W3C, RDF 1.1 Concepts and Abstract Syntax). A dataset adds named graphs (quads). SPARQL queries match a basic graph pattern of triples.
# Turtle
@prefix ex: <http://example.org/> .
@prefix foaf: <http://xmlns.com/foaf/0.1/> .
ex:ann foaf:knows ex:bob .
ex:ann foaf:name "Ann" .
ex:bob foaf:name "Bob" .-- Not SQL: SPARQL 1.1 (Neptune, Apache Jena, Stardog, GraphDB, Oracle RDF Graph).
-- "+" is a property path: one or more foaf:knows hops.
-- PREFIX foaf: <http://xmlns.com/foaf/0.1/>
-- PREFIX ex: <http://example.org/>
-- SELECT ?friend ?name WHERE { ex:ann foaf:knows+ ?friend . ?friend foaf:name ?name }Real scenarios: publishing open data (Wikidata is an RDF dataset), merging vocabularies across companies, ontologies and inference (OWL, RDFS reasoners), life-science knowledge bases, enterprise data catalogues.
| Concern | Property graph (Cypher, Gremlin) | RDF (SPARQL) |
|---|---|---|
| Edge properties | Native | Reification, named graphs or RDF-star |
| Identity | Local ids, application keys | Global IRIs |
| Reasoning/inference | Not built in | RDFS/OWL entailment in many triple stores |
| Schema | Optional constraints | Ontologies (OWL, SHACL for validation) |
| Interchange | Vendor formats, CSV, GraphML | Standard serializations (Turtle, N-Triples, JSON-LD) |
| Application traversals | Primary use case | Possible, less ergonomic |
Fix / how to use it: choose RDF when standards-based interchange and reasoning matter more than application traversal speed. Amazon Neptune supports both models in one service (Gremlin and openCypher for property graphs, SPARQL for RDF), but a dataset is one model or the other.
Index-free adjacency and native vs non-native storage Must-know
In plain words: in a native graph store a node keeps a direct pointer to its relationships, and each relationship points to the next node, so moving one hop is following a pointer, not asking an index.
Common misunderstanding: "Index-free adjacency means graph databases have no indexes." They have many: you still need an index (or constraint) to find the starting node, User {id: 1}. "Index-free" means only that hops from a known node do not go through an index.
Definition: Wikipedia's Graph database article (a secondary source) states that graph databases "typically implement index-free adjacency, in which nodes store direct references to other nodes in the database, as opposed to a relational database, which uses a single global database index"; direct references typically give O(1) access to adjacent nodes against O(log n) for an index, so query times are proportional to how much of the graph is queried rather than to the size of the graph. Native engines (Neo4j, Memgraph, TigerGraph) store the graph in a layout designed for this. Non-native engines put a graph API on another store: JanusGraph on Cassandra, HBase or BerkeleyDB; Apache AGE on PostgreSQL heap tables; Neptune on its own purpose-built cluster volume.
Relational hop (one level of friends-of-friends):
1 probe index follows(follower_id) for Ann -- O(log n)
2 fetch heap pages for each matching edge row -- random I/O
3 for each followee_id probe index again -- k probes for k edges
Native hop:
1 read Ann's node record -- already located by the starting index
2 follow first-relationship pointer, then the chain -- sequential records, page cache hits
3 each relationship record names the neighbour -- no global lookupReal scenarios: a three-hop recommendation on a social graph; an impact-analysis query across a dependency graph; a fraud query that follows USED, OWNS, SHARES_ADDRESS edges four deep.
| Engine | Native graph layout? | Where hops resolve |
|---|---|---|
| Neo4j | Yes: record stores (aligned) or block format | Pointers in relationship records, via the page cache |
| Memgraph | Yes, in-memory | Pointers in RAM |
| TigerGraph | Yes (native parallel graph) | Own storage engine, MPP |
| Amazon Neptune | Purpose-built graph engine on a shared cluster volume | Engine indexes over the cluster volume |
| JanusGraph | No: backed by Cassandra, HBase or BerkeleyDB JE | Backend key lookups per adjacency list |
| Apache AGE | No: PostgreSQL tables per label | SQL joins over ag_catalog tables |
Fix / how to use it: do not pick a product because of the phrase; test your own hops. The benefit appears when depth and fan-out are large and the working set sits in the page cache.
Traversal vs recursive joins, and benchmark caveats Must-know
In plain words: a recursive SQL query and a graph traversal do the same walk; what differs is how cheaply the engine takes each step.
Common misunderstanding: "PostgreSQL cannot do graph queries." The PostgreSQL documentation says that "while RECURSIVE allows queries to be specified recursively, internally such queries are evaluated iteratively". WITH RECURSIVE plus an index on (follower_id, followee_id) walks a graph in one statement. The cost is that you must stop it yourself.
Definition: a recursive CTE has an anchor query, a recursive query that reads the working table, and UNION (deduplicate) or UNION ALL. PostgreSQL warns that the recursive part must eventually return no rows "or else the query will loop indefinitely", and shows two defences: UNION, and the CYCLE clause (PostgreSQL 14 and later) that tracks visited values.
iteration working table (frontier) result so far
0 anchor 10 followees of user 1 10
1 recursive step ~100 rows (10 x 10) ~110
2 recursive step ~1000 rows ~1100 (UNION drops repeats of (user, depth))
3 recursive step 0 new rows or depth bound hit stopReal scenarios: an org chart under a manager (recursive CTE is enough), category breadcrumbs, bill of materials, friends within three hops on a mid-sized table, dependency closure for a package.
Benchmark caveats. Vendor claims of "1000x faster than joins" typically compare a cold, poorly indexed relational schema against a warmed graph cache, at depth 5 to 8, on tuned data. Before you trust any number, ask:
| Question | Why it changes the result |
|---|---|
| Is the relational side indexed on the edge table's source and target columns? | Without (follower_id, followee_id) the join is a scan |
Are both caches warm (PostgreSQL shared_buffers and OS cache, Neo4j page cache)? | A cold run measures disk, not the model |
| What are depth and fan-out? | Cost is roughly fan-out to the power of depth for both; the engines differ in the constant |
| Is the result deduplicated by node or by path? | Cypher variable-length matches enumerate paths; UNION in SQL dedupes rows |
| Does the data fit in memory? | Neo4j's page cache and Memgraph's RAM only help if the graph fits |
| Is it one query or concurrent load? | Throughput, latency percentiles and locking differ from a single-run time |
| Same hardware, same version, same data? | Obvious, but vendor posts often skip it |
What our own run showed (single laptop, Docker, warm caches, 100,000 users and about 1,000,000 random follow edges, user 1, counting distinct users within N hops). Both engines returned the same counts: 1,105 users within 3 hops, 10,470 within 4, 64,921 within 5. Times, rounded and from a handful of repeats:
| Depth | PostgreSQL 16 recursive CTE | Neo4j 5.26 variable-length MATCH |
|---|---|---|
| 3 hops | about 3 ms | about 2 to 5 ms |
| 4 hops | about 11 ms | about 6 ms |
| 5 hops | about 65 ms | about 50 to 90 ms |
At this size the two are in the same order of magnitude. That is the honest finding: a well-indexed PostgreSQL is competitive on a mid-sized graph, and a native graph engine pays off when the graph is much larger, the depth or fan-out is higher, the pattern is not a simple walk (several relationship types, filters on edges), or you need the algorithms and the language. Run the lab on your own data; do not copy these numbers.
Fix / how to use it: the same query in both worlds, below in Solving the classic problems.
Query languages: Cypher, openCypher, GQL, Gremlin, SPARQL, SQL/PGQ Must-know
In plain words: Cypher draws the pattern you want with ASCII art; Gremlin describes the steps a walker takes; SPARQL matches triples; GQL is the ISO standard that grew out of Cypher's ideas.
Common misunderstanding: "Cypher, GQL and Gremlin are interchangeable, so I can pick later." Cypher and GQL are declarative patterns; Gremlin is a step pipeline. Rewriting a codebase from one to another is real work, and not every product speaks every language. Neptune speaks Gremlin, openCypher and SPARQL; Neo4j speaks Cypher; JanusGraph speaks Gremlin; TigerGraph speaks GSQL (and openCypher in GSQL); Memgraph speaks Cypher.
Definition: Cypher is Neo4j's declarative language; openCypher is the open specification of it, implemented by several vendors; GQL (ISO/IEC 39075:2024) is the ISO property-graph query language and a peer to SQL; Neo4j's manual notes that new Cypher features are added to Cypher 25 while Cypher 5 is frozen as of Neo4j 2025.06, and that the old * syntax for variable-length paths is still available but "not GQL conformant". Gremlin is the traversal language of Apache TinkerPop, run by many stores through the Gremlin Server. SPARQL is the W3C language for RDF.
The same question, "everyone within three follows of user 1":
-- SQL (PostgreSQL)
WITH RECURSIVE reach(user_id, depth) AS (
SELECT followee_id, 1 FROM follows WHERE follower_id = 1
UNION
SELECT f.followee_id, r.depth + 1
FROM reach r JOIN follows f ON f.follower_id = r.user_id
WHERE r.depth < 3
)
SELECT DISTINCT user_id FROM reach WHERE user_id <> 1;// Cypher 5 (Neo4j): variable-length relationship, "*" syntax
MATCH (u:User {id: 1})-[:FOLLOWS*1..3]->(f:User) WHERE f <> u RETURN DISTINCT f.id
// Cypher / GQL style: quantified path pattern
MATCH (u:User {id: 1})-[:FOLLOWS]->{1,3}(f:User) WHERE f <> u RETURN DISTINCT f.id
// Gremlin (TinkerPop; JanusGraph, Neptune): repeat().times()
g.V().has('User', 'id', 1).repeat(out('FOLLOWS')).times(3).emit().dedup().values('id')
// SPARQL 1.1 (RDF stores): property path "+"
SELECT DISTINCT ?f WHERE { ex:user1 ex:follows+ ?f }Timeline of one Cypher query inside the engine (planning is declarative)
1 parse the pattern, bind $id -- parameters are never concatenated
2 plan: NodeIndexSeek on :User(id), then VarLengthExpand -- the starting node uses an index
3 expand along FOLLOWS relationship chains, depth 1..3 -- pointer walk
4 filter f <> u, project f.id, DISTINCT
5 stream rows to the driver over BoltReal scenarios: an analytics team writes Cypher in Neo4j Browser; a platform team keeps TinkerPop code so it can move between JanusGraph and Neptune; a data team publishes SPARQL endpoints for linked data.
| Language | Style | Standard | Used by | Variable-length idiom |
|---|---|---|---|---|
| Cypher 5 / 25 | Declarative pattern | Neo4j product language | Neo4j, Memgraph (dialect), Neptune (openCypher subset) | *1..3 or {1,3} |
| openCypher | Declarative pattern | Open specification | Neptune, TigerGraph, Apache AGE, Memgraph | *1..3 |
| GQL | Declarative pattern | ISO/IEC 39075:2024 | Aligning products (Neo4j, Google Spanner Graph) | quantified paths {1,3}, +, * |
| Gremlin | Imperative traversal steps | Apache TinkerPop (not a formal standard) | JanusGraph, Neptune, Azure Cosmos DB for Gremlin | repeat(...).times(3) |
| SPARQL 1.1 | Triple patterns | W3C Recommendation | Neptune, Jena, GraphDB, Stardog | property paths + * |
| GSQL | Declarative, accumulators | TigerGraph product language | TigerGraph | ACCUM, POST-ACCUM, hop blocks |
| SQL/PGQ | GRAPH_TABLE match in SQL | SQL:2023 Part 16 | Oracle Database 23ai (verify others) | path quantifiers |
| Recursive CTE | SQL | SQL:1999, all major engines | PostgreSQL, MySQL 8, SQL Server, Oracle, SQLite, CockroachDB | WITH RECURSIVE |
Fix / how to use it: decide the language with the product, keep queries behind a repository interface, and always use parameters: in Cypher a parameter is $name. One trap verified against Neo4j 5.26: a parameter cannot be used as a variable-length bound (*1..$d fails to compile); format a validated integer into the text, or use a fixed set of queries.
Modeling: nodes, edges, properties, hyperedges and time Must-know
In plain words: nouns become nodes, verbs become relationship types, and a value that is just a detail of one thing becomes a property.
Common misunderstanding: "Whatever I can put in a property I should, and graphs are schemaless so there is nothing to design." A graph with a hairball of untyped RELATED_TO edges answers nothing. Modeling decides query cost: if you often filter by country, a Country node you can jump from beats a country string you scan for.
Definition: the model-from-questions rules practitioners use:
| Decision | Rule of thumb |
|---|---|
| Node or property? | If you traverse through it, filter on it constantly, or it connects things (country, tag, device, address), make it a node; otherwise a property |
| Relationship type | Specific and verb-like (PURCHASED, REPORTS_TO), not RELATED_TO |
| Direction | Store one direction that reads naturally; you can traverse both ways; do not duplicate edges |
| Edge or intermediate node? | If the relationship has its own relationships (a Purchase that has items, a payment, a refund), make it a node |
| Hyperedge (relationship among 3 or more things) | No native n-ary edge in an LPG: reify it as a node (:Meeting with PARTICIPATED_IN edges, each with a role) |
| Time | Put valid_from and valid_to on relationships, or model versions as nodes with NEXT/SUPERSEDES edges |
| Supernode risk | Do not hang a million edges off one node if you can fan out by bucket (Day, Region) |
Hyperedge as a node: (:Person)-[:ATTENDED {role: 'chair'}]->(:Meeting {date: '2026-11-25'})<-[:ATTENDED {role: 'minutes'}]-(:Person)
Time on the edge: (:Employee)-[:WORKS_AT {valid_from: date('2021-02-01'), valid_to: date('2024-06-30')}]->(:Company)-- "Where did Ann work on 2023-01-01?" in Cypher (as comments, then SQL for the relational model)
-- MATCH (:Person {name:'Ann'})-[w:WORKS_AT]->(c:Company)
-- WHERE w.valid_from <= date('2023-01-01') AND (w.valid_to IS NULL OR w.valid_to > date('2023-01-01'))
-- RETURN c.name
SELECT c.name
FROM employment e JOIN company c ON c.id = e.company_id
WHERE e.person_id = 1
AND e.valid_from <= DATE '2023-01-01'
AND (e.valid_to IS NULL OR e.valid_to > DATE '2023-01-01');Real scenarios: temporal org charts and permissions ("who could access this on the day of the breach"), price and ownership history, versioned knowledge graphs.
| Pattern | Use when | Cost |
|---|---|---|
| Time-stamped relationship | Few changes per edge, point-in-time questions | Every traversal filters on the stamps |
| Version node chain | Whole entity versions are audited | More nodes, more hops |
| Snapshot graphs per period | Heavy analytics per period | Storage duplication |
| Event nodes (events as nodes in a timeline) | Event sourcing into a graph | Needs a good timeline index |
Fix / how to use it: write the ten questions the graph must answer first, draw the pattern for each, and let the patterns decide nodes and edges. Keep ids stable and unique (a uniqueness constraint) so MERGE is safe.
Indexes and constraints in a graph store Important
In plain words: indexes in a graph database find the starting nodes; the edges themselves are followed without an index.
Common misunderstanding: "Because adjacency is index-free, I do not need indexes." Without an index on User.id, MATCH (u:User {id: 1}) scans every :User node, and every traversal starts with that scan.
Definition: Neo4j (Cypher 5) index categories: range, text, point and token lookup indexes (the always-on label and relationship-type lookups), plus full-text indexes for lexical search and vector indexes for similarity search. Constraints (uniqueness, existence, key) also create their backing index.
// Cypher (Neo4j 5)
CREATE CONSTRAINT user_id IF NOT EXISTS FOR (u:User) REQUIRE u.id IS UNIQUE; // unique + index
CREATE INDEX person_name IF NOT EXISTS FOR (p:Person) ON (p.name); // range index
CREATE FULLTEXT INDEX person_ft IF NOT EXISTS FOR (p:Person) ON EACH [p.name]; // lexical search
CALL db.index.fulltext.queryNodes('person_ft', 'Ann') YIELD node, score RETURN node.name, score;
// Verify the plan uses it: EXPLAIN MATCH (p:Person {name:'Ann'}) RETURN p -- look for NodeIndexSeek| Index type (Neo4j 5) | Good for | Notes |
|---|---|---|
| Range | Equality, ranges, prefix, ordering | The default CREATE INDEX |
| Text | CONTAINS, ENDS WITH on strings | Not for ordering |
| Point | Spatial lookups | Needs point properties |
| Token lookup | Label and relationship-type scans | On by default |
| Full-text | Lexical search with scoring | Queried through a procedure |
| Vector | Similarity search over embeddings | Vector index memory lives outside the page cache per the Neo4j docs; see Vector Search |
| Engine | Where indexes live |
|---|---|
| Neo4j | Property indexes and constraints per label; token lookups |
| Memgraph | Label and label-property indexes, plus constraints |
| Neptune | Built-in indexes over the graph; you do not create them |
| JanusGraph | Composite and mixed indexes; mixed indexes delegate to Elasticsearch, Solr or Lucene |
| TigerGraph | Vertex/edge attribute indexes through the schema |
| Apache AGE | PostgreSQL indexes (B-tree, GIN) on label tables |
Fix / how to use it: index the properties you start queries from and unique ids you MERGE on; verify with EXPLAIN/PROFILE that you see an index seek and not a label scan.
Transactions and consistency Important
In plain words: most graph databases give you ACID transactions on one machine, just like a relational database; what varies is how they behave across a cluster.
Common misunderstanding: "NoSQL means no transactions." Neo4j, Memgraph (in its default transactional mode), TigerGraph and Neptune are transactional; JanusGraph inherits the guarantees of its storage backend (Cassandra is eventually consistent, HBase favours consistency). See ACID & Transactions and Isolation Levels.
Definition: in Neo4j a transaction is committed through the transaction log (the write-ahead log) before it is acknowledged. In a cluster, the Neo4j docs say a client "is guaranteed to read at least its own writes" (causal consistency): after a commit the client may ask for a bookmark and present it to the next transaction so only servers that have processed that transaction run it. Memgraph's IN_MEMORY_TRANSACTIONAL mode is the default and IN_MEMORY_ANALYTICAL "speeds up import and data analysis but offers no ACID guarantees besides manually created snapshots".
Read-your-writes in a Neo4j cluster
1 client -> writer (primary): CREATE edge ... COMMIT -- returns a bookmark b1
2 client -> secondary: MATCH ... with bookmark b1 -- the secondary waits until it has applied b1
3 secondary -> client: rows that include the new edge -- never a stale view of own writeReal scenarios: a "follow" button that must show immediately after click even if the read goes to a replica; a money transfer between accounts represented as nodes; a bulk import in the analytical mode followed by switching back.
| Engine | Transactions | Isolation (documented behaviour) | Distribution |
|---|---|---|---|
| Neo4j | ACID, transaction log | Read committed (default) with locks on written entities | Primaries (Raft) plus secondaries, causal consistency via bookmarks |
| Memgraph | ACID in IN_MEMORY_TRANSACTIONAL | SNAPSHOT_ISOLATION default; READ_COMMITTED and READ_UNCOMMITTED selectable | Replication; see its docs for HA |
| Amazon Neptune | ACID | Defined in Neptune's transaction-semantics page (isolation levels per query type); check it before relying on a level | One writer, up to 15 replicas on a shared cluster volume |
| TigerGraph | ACID transactions ("Transaction and ACID" in its Architecture docs) | See that page | Distributed MPP |
| JanusGraph | Depends on backend | Backend-defined | Cassandra, HBase, BerkeleyDB JE |
| Apache AGE | PostgreSQL transactions | PostgreSQL isolation levels apply | Whatever PostgreSQL gives you |
Fix / how to use it: keep write transactions short, retry transient errors (the Neo4j drivers do this inside transaction functions, which is why their bodies must be idempotent; use MERGE), and use bookmarks (the drivers manage them for you in a session) when reading from secondaries after a write.
Supernodes (dense nodes) Important
In plain words: one node with millions of relationships makes every traversal that passes through it enormous.
Common misunderstanding: "Traversal cost depends only on depth." It depends on fan-out too, and a single celebrity account or a Country node can turn a three-hop query into a scan of the whole graph.
Definition: a supernode is a node whose degree is orders of magnitude above the median. Neo4j's record formats keep relationship groups per type for dense nodes (a running Neo4j 5.26 database shows neostore.relationshipgroupstore.db and neostore.relationshipgroupstore.degrees.db), so an expansion that names a type does not walk edges of other types.
Query: friends of friends of Ann, one friend is a celebrity with 50,000,000 followers
1 expand Ann -> 300 friends
2 expand each friend -> 300 each, but one friend has 50,000,000 FOLLOWS edges
3 the traversal touches 50,000,000 relationships for one hopReal scenarios: a verified celebrity in a social graph; the Unknown device id shared by thousands of fraud events; a public IP address of a corporate NAT; a "male/female" or "country" node.
| Mitigation | How | Trade-off |
|---|---|---|
| Filter by relationship type and direction | -[:FOLLOWS]-> not -- | Cheapest and always first |
| Bucket nodes | Celebrity -> Day bucket -> followers | More modeling |
| Limit and sample | LIMIT per hop; algorithms with a sampling size | Approximate answers |
| Exclude from fraud joins | Ignore known shared devices/IPs by a flag property | Needs a maintained list |
| Degree property | Store degree and skip nodes above a threshold | Must be kept up to date |
Fix / how to use it: profile with PROFILE and watch db hits; model high-degree entities as bucketed structures.
Sharding a graph is hard Must-know
In plain words: you cannot cut a graph into pieces without cutting edges, and every cut edge is a network call during a traversal.
Common misunderstanding: "Shard by user id like any other table." In a key-value store a request touches one partition. A graph query touches the neighbours of the neighbours, which live in other partitions, so one query becomes many network hops and the latency advantage of local pointers is gone.
Definition: graph partitioning tries to minimise the number of edges that cross partitions (the edge cut) while keeping partitions balanced; for general graphs the optimal partitioning is NP-hard, and real graphs (social networks) have no clean cut because they have supernodes and small-world structure.
shard A: Ann, Bob, Carol shard B: Dan, Eve
Ann -> Bob (local) Carol -> Dan (crosses the cut, one network hop)
query: friends of friends of Ann, 3 hops: A -> A -> B -> A = 2 network round tripsReal scenarios: a social network that outgrows one machine; a knowledge graph with trillions of edges; a fraud graph that must stay consistent.
| Strategy | How | Advantage | Cost |
|---|---|---|---|
| Vertical scale and RAM | One big machine, graph in memory or page cache | Local pointers, simple | Machine limit |
| Read replicas | Neo4j secondaries; Neptune up to 15 replicas | Read scale-out, availability | Writes still hit one writer |
| Federation / multiple graphs | One database per tenant or domain (Neo4j multi-database) | Natural boundaries, no cut | No cross-graph traversal |
| Distributed engine | TigerGraph MPP, JanusGraph on Cassandra, Spanner Graph | Scales storage and writes | Network hops per cut edge, complexity |
| Property or workload sharding | Split properties from topology (newer in some engines) | Scales properties | Topology still on one side; check vendor docs |
Fix / how to use it: exhaust vertical scale, read replicas and per-tenant graphs first. A multi-tenant SaaS that gives each customer its own graph avoids the cut entirely; see Multi-Tenancy. For the key-based sharding that does work for relational data, see Partitioning & Sharding and Consistent Hashing.
Graph algorithms: shortest path, PageRank, community detection, centrality Important
In plain words: besides finding patterns, graph engines can compute whole-graph scores: who is most central, which groups cluster together, what the cheapest route is.
Common misunderstanding: "I will write PageRank in my application loop." It is an iterative computation over every edge; run it where the graph lives, in a library that projects the graph into memory.
Definition: Neo4j Graph Data Science (GDS) projects a named in-memory graph into the graph catalog and runs algorithms in modes such as stream, stats, mutate, write and estimate. Memgraph (MAGE), Neptune Analytics and TigerGraph (graph algorithm library) offer comparable sets.
GDS pipeline (Neo4j)
1 project: gds.graph.project('social', source, target) -- the named in-memory graph
2 estimate: gds.pageRank.stream.estimate(...) -- memory first
3 run: gds.pageRank.stream('social') YIELD nodeId, score
4 persist: gds.pageRank.write('social', {writeProperty: 'rank'})// Neo4j GDS, aggregation-function projection as in the GDS manual
MATCH (s:User)-[r:FOLLOWS]->(t:User)
RETURN gds.graph.project('social', s, t)
CALL gds.pageRank.stream('social') YIELD nodeId, score
RETURN gds.util.asNode(nodeId).id AS user, score ORDER BY score DESC LIMIT 10
CALL gds.louvain.stream('social') YIELD nodeId, communityId
RETURN communityId, count(*) AS size ORDER BY size DESC LIMIT 10
CALL gds.betweenness.stream('social') YIELD nodeId, score
RETURN gds.util.asNode(nodeId).id AS broker, score ORDER BY score DESC LIMIT 10| Family | Algorithm | Answers | GDS procedure (stream mode) |
|---|---|---|---|
| Path finding | Shortest path, Dijkstra, A*, Yen's k shortest, BFS/DFS | Cheapest or fewest-hop route | gds.shortestPath.dijkstra.stream |
| Centrality | PageRank, betweenness, closeness, degree | Who is important or a broker | gds.pageRank.stream, gds.betweenness.stream |
| Community detection | Louvain, Leiden, label propagation, weakly connected components | Which groups cluster | gds.louvain.stream |
| Similarity | Node similarity, k-nearest neighbours | Who is alike | gds.nodeSimilarity.stream |
| Embeddings | FastRP, node2vec | Vectors for ML | gds.fastRP.stream |
Real scenarios: PageRank to rank pages or accounts; Louvain to find communities for fraud-ring candidates; betweenness to find the single service whose failure partitions the network; Dijkstra for route cost. GDS is a separate plugin on Neo4j Community and Enterprise; availability of some algorithms and parallelism depends on licence, so check the GDS docs.
Fix / how to use it: for a single shortest path in plain Cypher you do not need GDS: shortestPath() or the GQL-aligned SHORTEST 1.
// Verified on Neo4j 5.26: fewest hops from user 1 to user 99999, both spellings
MATCH p = SHORTEST 1 (a:User {id: 1})-[:FOLLOWS]->+(b:User {id: 99999}) RETURN length(p), [n IN nodes(p) | n.id]
MATCH p = shortestPath((a:User {id: 1})-[:FOLLOWS*..6]->(b:User {id: 99999})) RETURN length(p)GraphQL is not a graph database Good to know
In plain words: GraphQL is how a client asks a server for exactly the fields it wants; a graph database is where data is stored.
Common misunderstanding: "GraphQL means I need a graph database" or "a graph database gives me a GraphQL API for free". GraphQL runs happily on PostgreSQL, MongoDB or REST backends; its "graph" is the shape of the schema (types that reference each other), not a storage model. Neo4j does ship a GraphQL library that maps a GraphQL schema onto a Neo4j graph, which is a convenience, not an identity.
Definition: GraphQL is a query language and runtime for APIs (see GraphQL); a graph database is a DBMS with a graph data model. A GraphQL resolver can issue SQL, Cypher or a cache lookup.
Client --GraphQL--> resolver --SQL--> PostgreSQL
Client --GraphQL--> resolver --Cypher--> Neo4j
Client --GraphQL--> resolver --HTTP--> three microservicesReal scenarios: a GraphQL API whose resolvers trigger N+1 queries against PostgreSQL (see ORM Pitfalls) has nothing to do with graph storage; a recommendation endpoint backed by Neo4j can be exposed as REST or gRPC.
| Question | GraphQL | Graph database |
|---|---|---|
| What is it? | API query language and runtime | DBMS |
| Who calls it? | Browser and mobile clients | Your services |
| Traversal | Declared by the client, executed by resolvers | Executed by the engine |
| Replaces PostgreSQL? | No | Sometimes, for graph workloads |
Fix / how to use it: pick them independently; if you use both, put the graph query behind a resolver or data loader that batches.
Per-product behaviour
Rule on this page: never name a feature without the product. Everything below is from the vendor documentation unless marked as our measurement or our judgement.
| Product | Model and storage | Languages | Transactions and scale | Notes |
|---|---|---|---|---|
| Neo4j | Native labeled property graph; record formats aligned (Community default) and block (Enterprise, recommended); standard and high_limit deprecated in 5.23 | Cypher 5 / Cypher 25, Bolt protocol | ACID, transaction log; cluster of primaries and secondaries, causal consistency with bookmarks | Graph Data Science, APOC, Browser, Bloom; drivers in Go, PHP (community), Java, Python, JavaScript, .NET |
| Amazon Neptune | Fully managed purpose-built engine; Neptune Analytics for in-memory analytics | Gremlin, openCypher, SPARQL | One primary writer plus up to 15 replicas on a shared cluster volume across Availability Zones; point-in-time recovery, S3 backup, encryption at rest and in transit | Property graph and RDF in one service, not mixed in one dataset |
| Memgraph | In-memory native property graph; storage modes IN_MEMORY_TRANSACTIONAL (default), IN_MEMORY_ANALYTICAL, ON_DISK_TRANSACTIONAL | Cypher over Bolt | Default isolation SNAPSHOT_ISOLATION | MAGE algorithm modules, streaming ingestion |
| TigerGraph | Native parallel (MPP) graph database | GSQL, openCypher in GSQL | Distributed, ACID transactions documented in its architecture section | Schema-first; strong on deep multi-hop analytics at scale |
| JanusGraph | Graph layer on a storage backend (Apache Cassandra, Apache HBase, BerkeleyDB JE) plus mixed indexes (Elasticsearch, Solr, Lucene) | Gremlin (TinkerPop) | "Graphs so large that they require storage and computational capacities beyond what a single machine can provide"; guarantees come from the backend | The Titan successor; non-native |
| Apache AGE | PostgreSQL extension; Cypher inside SQL; "single storage that can handle both relational and graph model data" | openCypher via cypher() function, returns agtype | PostgreSQL's transactions, MVCC, replication, backup | Smaller ecosystem than Neo4j |
| ArangoDB | Multi-model (document, key/value, graph) | AQL | Cluster with auto-sharding | Graph traversals in AQL |
| Google Spanner Graph | Graph on Spanner | GQL, openCypher | Global consistency | Managed |
| Oracle Database 23ai | Property graph views over relational tables, SQL/PGQ; also RDF Graph with SPARQL | SQL/PGQ, SPARQL, PGQL | Oracle's transaction engine | Graph over relational data you already hold |
| SQL Server | NODE and EDGE tables with the MATCH clause (since 2017) | T-SQL | SQL Server | Graph tables are ordinary tables with hidden columns; check your edition |
| MongoDB | Documents; $graphLookup aggregation stage walks references | MQL | Replica sets and sharded clusters | Recursive lookup inside one collection, bounded maxDepth; sharded collections have restrictions |
| MySQL (InnoDB) | Tables | SQL with recursive CTEs (8.0 and later) | InnoDB | No graph engine; cte_max_recursion_depth guards loops |
| SQLite | Tables | SQL with recursive CTEs | Single writer | Fine for small embedded graphs |
| CockroachDB | Tables | PostgreSQL-compatible SQL with recursive CTEs | Distributed SQL | A graph engine is not part of it |
| Redis | Key-value; the RedisGraph module was retired and a fork continues as FalkorDB | Cypher (module) | In-memory | Check current status before adopting |
Choosing a native engine, in one table:
| If you need | Look at | Why |
|---|---|---|
| The largest ecosystem, tools and algorithms | Neo4j | GDS, Browser, drivers, community |
| A managed service on AWS, with SPARQL too | Amazon Neptune | Shared storage, replicas, no operations |
| Low latency on a graph that fits in RAM and streaming ingest | Memgraph | In-memory engine |
| Deep multi-hop analytics across a cluster | TigerGraph | MPP engine |
| An existing Cassandra or HBase, Gremlin code | JanusGraph | Reuses the backend |
| Graph queries inside PostgreSQL, one operational surface | Apache AGE or recursive CTEs | No second database |
Mechanics
Neo4j store files and the page cache Important
A Neo4j database is a directory of store files. In the aligned format of a running Neo4j 5.26 Community database (checked inside a container for this page) the files include neostore.nodestore.db, neostore.relationshipstore.db, neostore.relationshipgroupstore.db, neostore.propertystore.db with .strings and .arrays overflow files, label, relationship-type and property-key token stores, neostore.schemastore.db for indexes and constraints, and neostore.counts.db. Nodes, relationships and properties are fixed-size or dynamic records that point at each other: a node record points to its first relationship and first property; relationship records are chained and name both end nodes. That chain of pointers is index-free adjacency. The Neo4j manual describes the newer block format (recommended for Enterprise) as using "advanced data structures and inlining techniques" so that properties are stored "with their nodes and relationships drastically reducing the amount of pointer chasing" and "a few pages need to be loaded to serve a query".
Neo4j memory and I/O (single instance)
Cypher planner ──▶ runtime ──▶ page cache (server.memory.pagecache.size) ──▶ store files on disk
▲ ▲
transactions ──▶ transaction log (neostore.transaction.db.N) ── checkpoint ───┘
JVM heap holds query state, transaction state and caches; it is NOT the page cache.| Knob (Neo4j 5) | Meaning | Default seen in the 5.26 container |
|---|---|---|
server.memory.pagecache.size | Memory used to cache graph data and indexes from disk; the manual recommends defining it explicitly | 512.00MiB (set by the image) |
server.memory.heap.initial_size / max_size | JVM heap | Unset in the container |
db.format | Store format for a new database | aligned in Community |
db.tx_log.rotation.size | When the transaction log file rotates | 256.00MiB |
db.checkpoint.interval.time | How often a checkpoint flushes pages | 15m |
db.checkpoint.interval.tx | Checkpoint after this many transactions | 100000 |
db.checkpoint.interval.volume | Checkpoint after this much log volume | 250.00MiB |
dbms.memory.transaction.total.max | Cap on transaction memory | Unset |
Sizing rule: the page cache should hold the hot part of the store plus indexes; if the graph is larger than the cache, hops cause page faults and the index-free advantage turns into disk reads. Estimate from the store file sizes (neostore.* files), then add growth.
Transaction log, checkpoint and recovery Important
Neo4j writes each transaction to the transaction log before acknowledging the commit; a checkpoint flushes dirty pages from the page cache to the store files so recovery after a crash replays only the log after the last checkpoint. The idea is the same write-ahead logging described in Durability, WAL & Crash Recovery; the files are neostore.transaction.db.N and checkpoint.N.
Neo4j commit
1 client sends CREATE edge in a transaction
2 engine takes locks on the touched nodes and relationships
3 writes commands to neostore.transaction.db.N, flushes (fsync)
4 commit acknowledged
5 later: page cache flushed to store files, checkpoint record written
6 crash? replay the log from the last checkpointClustering: primaries, secondaries, Raft and bookmarks Important
A Neo4j cluster is a pool of servers hosting databases; each database has its own topology of primaries (fault tolerance, transaction processing) and secondaries (read scale). Only primaries can be the writer; one primary is elected writer; the writer "synchronously pushes writes to other primaries and does not allow a commit to be completed until it receives confirmation that the data has been written to enough members". A database stays writable while a simple majority of its primaries is alive; if the Raft leader stops responding, followers elect a new one. Causal consistency ("causal clustering" in Neo4j 3.x and 4.x docs) is delivered with bookmarks: a client passes the bookmark of its last transaction and the cluster routes it to a server that has applied it. Drivers do this for you inside a session. The neo4j:// URI scheme asks the driver to fetch a routing table and route reads and writes; bolt:// connects to one server.
| Concept | Neo4j term | Notes |
|---|---|---|
| Write replica set with consensus | Primaries (Raft group) | One writer at a time |
| Read scale-out | Secondaries | Eventually catch up; use bookmarks for read-your-writes |
| Read-your-writes | Bookmark / causal consistency | Handled by the driver session |
| Routing | neo4j:// URI, routing table | bolt:// is direct |
| Whole-graph sharding | Not part of the cluster model | Use multiple databases or federation; see Sharding |
Memgraph, Neptune, TigerGraph, JanusGraph and AGE internals in brief Good to know
| Product | What to know |
|---|---|
| Memgraph | "Built natively for in-memory data analysis"; storage modes are switched with STORAGE MODE IN_MEMORY_ANALYTICAL;; analytical mode "speeds up import and data analysis but offers no ACID guarantees besides manually created snapshots" |
| Amazon Neptune | Primary instance writes to a cluster volume that stores copies across Availability Zones; replicas attach to the same volume; supports Gremlin, openCypher, SPARQL; Neptune Analytics analyses graphs in memory |
| TigerGraph | Native parallel graph; GSQL with accumulators; openCypher support inside GSQL; GraphStudio visual tools |
| JanusGraph | Adjacency lists are stored as rows in Cassandra/HBase (wide rows); mixed indexes via Elasticsearch/Solr/Lucene; Gremlin Server |
| Apache AGE | Creates a schema per graph and a table per label under ag_catalog; cypher() function returns a set of records typed agtype; the planner treats it as SQL |
Error codes you will catch Important
| Where | Code or message | Meaning | Retry? |
|---|---|---|---|
| Neo4j | Neo.ClientError.Schema.ConstraintValidationFailed ("Node(0) already exists with label User and property id = 1" seen in our run) | Uniqueness constraint violated | No: fix data or use MERGE |
| Neo4j | Neo.ClientError.Statement.SyntaxError ("Invalid input 'MATC'...") | Cypher does not parse | No |
| Neo4j | Neo.ClientError.Statement.ParameterMissing | A $param was not supplied | No |
| Neo4j | Neo.TransientError.Transaction.DeadlockDetected | Two transactions locked in opposite order | Yes, in a transaction function (the driver does) |
| Neo4j | Neo.TransientError.General.DatabaseUnavailable or leader switch | Cluster failover | Yes, with backoff |
| Neo4j | Neo.ClientError.Security.Unauthorized | Bad credentials | No |
| PostgreSQL | No error: the query runs until cancelled or statement_timeout fires | A recursive CTE with a cycle, UNION ALL, and no bound or CYCLE clause | Fix the query; set statement_timeout |
| PostgreSQL | SQLSTATE 40001 / 40P01 | Serialization failure or deadlock | Yes; see Isolation Levels and Deadlocks |
| MySQL 8 | ERROR 3636 (HY000) "Recursive query aborted after N iterations" governed by cte_max_recursion_depth | Recursion cap hit (MySQL 8.0) | Raise the cap or bound the query |
| Neptune | ConcurrentModificationException (Gremlin) | Write conflict between concurrent mutations | Yes, with backoff |
Solving the classic problems
One subsection per classic problem, with the solution table first, then SQL (PostgreSQL), Cypher, Go and Laravel.
| Problem | Preferred solution | How | Advantage | Cost or limitation |
|---|---|---|---|---|
| Friends within N hops | Recursive CTE or MATCH ... *1..N | Bound the depth; dedupe by node | One statement, no application loop | Fan-out to the power of depth |
| Shortest path | SHORTEST 1 / shortestPath() / GDS Dijkstra | BFS or Dijkstra in the engine | Engine-optimised | SQL needs a path array and a bound |
| Fraud rings | Shared-identifier pattern or Louvain / weakly connected components | (a)-[:USED]->(d)<-[:USED]-(b) | Reads like the question | Supernode devices must be excluded |
| Recommendations | Collaborative filtering pattern, node similarity | Two-hop co-purchase pattern, count distinct peers | Real time | Needs a feed from the system of record |
| Impact analysis | Reverse transitive closure | (d)-[:DEPENDS_ON*1..]->(p) | Whole closure in one query | Cycles in dependency data |
| Hierarchy and breadcrumbs | ltree or recursive CTE | Materialised path, GiST index | No second database | Single-parent trees only for ltree |
Friends of friends, three ways: N+1 loop, recursive SQL, Cypher
The first version walks the graph in a Go loop and issues one query per visited user. This is "bad design, never broken": it works and does not scale.
// Package before shows multi-hop reachability done the way many services
// start out: one SQL round trip per user, driven by a loop in Go.
package before
import (
"context"
"database/sql"
"fmt"
"sort"
)
// Reachable returns every user within maxHops follows of userID, excluding
// userID itself. It issues one query per visited user, so the number of round
// trips grows with the size of the neighbourhood, not with the depth.
func Reachable(ctx context.Context, db *sql.DB, userID int64, maxHops int) ([]int64, error) {
if maxHops < 1 {
return nil, fmt.Errorf("maxHops must be at least 1, got %d", maxHops)
}
visited := map[int64]bool{userID: true}
frontier := []int64{userID}
var result []int64
for hop := 0; hop < maxHops && len(frontier) > 0; hop++ {
var next []int64
for _, id := range frontier {
// One query per node: this is the cost that grows with the graph.
rows, err := db.QueryContext(ctx,
`SELECT followee_id FROM follows WHERE follower_id = $1`, id)
if err != nil {
return nil, err
}
for rows.Next() {
var followee int64
if err := rows.Scan(&followee); err != nil {
rows.Close()
return nil, err
}
if !visited[followee] {
visited[followee] = true
next = append(next, followee)
result = append(result, followee)
}
}
if err := rows.Err(); err != nil {
rows.Close()
return nil, err
}
rows.Close()
}
frontier = next
}
sort.Slice(result, func(i, j int) bool { return result[i] < result[j] })
return result, nil
}The relational fix is one recursive query. The depth bound makes it finite; UNION removes duplicate (user_id, depth) rows. Note the limit stated in the diagram: UNION compares whole rows, so a densely connected graph still grows with the number of distinct (user, depth) pairs. Use the CYCLE clause or a visited-set trick for large fan-out.
-- PostgreSQL: the supporting index is the primary key (follower_id, followee_id).
CREATE TABLE follows (
follower_id int NOT NULL REFERENCES users(id),
followee_id int NOT NULL REFERENCES users(id),
since date NOT NULL DEFAULT current_date,
PRIMARY KEY (follower_id, followee_id)
);
CREATE INDEX follows_followee_idx ON follows (followee_id); -- reverse direction ("who follows me")
-- Cycle-safe variant, PostgreSQL 14 and later: the CYCLE clause marks rows that revisit a node.
WITH RECURSIVE walk(user_id, depth) AS (
SELECT followee_id, 1 FROM follows WHERE follower_id = 1
UNION ALL
SELECT f.followee_id, w.depth + 1
FROM walk w JOIN follows f ON f.follower_id = w.user_id
WHERE w.depth < 4
) CYCLE user_id SET is_cycle USING path
SELECT count(DISTINCT user_id) FROM walk WHERE NOT is_cycle; -- 10470 on our lab data// Package after expresses the same multi-hop reachability as one recursive
// query. The database does the traversal; Go only sends the parameters and
// reads the rows.
package after
import (
"context"
"database/sql"
"fmt"
)
// reachableSQL walks the follows table up to $2 hops from $1. The UNION
// removes duplicate (user, depth) rows, and the depth bound guarantees the
// recursion stops even when the follow graph contains cycles.
const reachableSQL = `
WITH RECURSIVE reach(user_id, depth) AS (
SELECT followee_id, 1
FROM follows
WHERE follower_id = $1
UNION
SELECT f.followee_id, r.depth + 1
FROM reach r
JOIN follows f ON f.follower_id = r.user_id
WHERE r.depth < $2
)
SELECT DISTINCT user_id
FROM reach
WHERE user_id <> $1
ORDER BY user_id`
// Reachable returns every user within maxHops follows of userID, excluding
// userID itself, using a single round trip.
//
// The equivalent Cypher, for a property graph store such as Neo4j:
//
// MATCH (u:User {id: $userID})-[:FOLLOWS]->{1,3}(other:User)
// WHERE other <> u
// RETURN DISTINCT other.id AS id
// ORDER BY id
func Reachable(ctx context.Context, db *sql.DB, userID int64, maxHops int) ([]int64, error) {
if maxHops < 1 {
return nil, fmt.Errorf("maxHops must be at least 1, got %d", maxHops)
}
rows, err := db.QueryContext(ctx, reachableSQL, userID, maxHops)
if err != nil {
return nil, err
}
defer rows.Close()
var result []int64
for rows.Next() {
var id int64
if err := rows.Scan(&id); err != nil {
return nil, err
}
result = append(result, id)
}
if err := rows.Err(); err != nil {
return nil, err
}
return result, nil
}Cypher for a graph store, verified on Neo4j 5.26 (1,105 users at three hops on our lab data, matching the SQL):
MATCH (u:User {id: $id})-[:FOLLOWS*1..3]->(other:User)
WHERE other <> u
RETURN DISTINCT other.id AS id ORDER BY idGo against Neo4j with the official driver (github.com/neo4j/neo4j-go-driver/v6; the current Go manual installs v6 and creates a driver with neo4j.NewDriver; the earlier v5 module used NewDriverWithContext). The code was compiled with go vet and run against a Neo4j 5.26 container:
// Package neo4j runs graph queries against Neo4j with the official Go driver
// (github.com/neo4j/neo4j-go-driver/v6). The driver speaks Bolt, routes reads
// and writes in a cluster, and retries transient errors inside transaction
// functions.
package neo4j
import (
"context"
"fmt"
neo "github.com/neo4j/neo4j-go-driver/v6/neo4j"
)
// NewDriver builds the long-lived, concurrency-safe driver. Create one per
// process, not one per request, and close it on shutdown.
func NewDriver(ctx context.Context, uri, user, password string) (neo.Driver, error) {
driver, err := neo.NewDriver(uri, neo.BasicAuth(user, password, ""))
if err != nil {
return nil, err
}
if err := driver.VerifyConnectivity(ctx); err != nil {
_ = driver.Close(ctx)
return nil, err
}
return driver, nil
}
// Reachable returns the ids of every user within maxHops follows of userID.
// Cypher 5 does not accept a parameter as a variable-length bound, so the
// depth is formatted into the text after it is checked to be a small integer.
// Everything user-controlled (the id) stays a parameter.
func Reachable(ctx context.Context, driver neo.Driver, userID int64, maxHops int) ([]int64, error) {
if maxHops < 1 || maxHops > 6 {
return nil, fmt.Errorf("maxHops must be between 1 and 6, got %d", maxHops)
}
query := fmt.Sprintf(`
MATCH (u:User {id: $id})-[:FOLLOWS*1..%d]->(other:User)
WHERE other <> u
RETURN DISTINCT other.id AS id
ORDER BY id`, maxHops)
// ExecuteQuery opens a session, runs one managed transaction (retried on
// transient errors) and returns the whole result.
result, err := neo.ExecuteQuery(ctx, driver, query,
map[string]any{"id": userID},
neo.EagerResultTransformer,
neo.ExecuteQueryWithReadersRouting(),
)
if err != nil {
return nil, err
}
ids := make([]int64, 0, len(result.Records))
for _, record := range result.Records {
// The bool is "isNil" (the column was null), not "found".
id, isNil, err := neo.GetRecordValue[int64](record, "id")
if err != nil {
return nil, err
}
if isNil {
continue
}
ids = append(ids, id)
}
return ids, nil
}
// Follow creates the edge once. MERGE makes the write idempotent, which matters
// because a transaction function may be run again after a transient failure.
func Follow(ctx context.Context, driver neo.Driver, follower, followee int64) error {
session := driver.NewSession(ctx, neo.SessionConfig{AccessMode: neo.AccessModeWrite})
defer session.Close(ctx)
_, err := session.ExecuteWrite(ctx, func(tx neo.ManagedTransaction) (any, error) {
result, err := tx.Run(ctx, `
MATCH (a:User {id: $follower}), (b:User {id: $followee})
MERGE (a)-[r:FOLLOWS]->(b)
ON CREATE SET r.since = date()`,
map[string]any{"follower": follower, "followee": followee})
if err != nil {
return nil, err
}
return result.Consume(ctx)
})
return err
}Laravel with PostgreSQL: one raw recursive query, positional bindings, nothing interpolated. Eloquent models one relationship level at a time and cannot say "follow follows until nothing new appears", so multi-hop queries are either fixed-depth with() chains (the Before) or raw SQL.
<?php
// app/Models/User.php (excerpt) — follows is a self-referencing many-to-many
// relationship through the `follows` pivot table.
namespace App\Models;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
public function follows(): BelongsToMany
{
return $this->belongsToMany(User::class, 'follows', 'follower_id', 'followee_id');
}
}
// app/Services/FollowGraph.php — three hops, written as nested eager loading.
namespace App\Services;
use App\Models\User;
final class FollowGraph
{
/**
* Returns the ids of every user within three follows of $user.
*
* Each extra hop means another level in with(), another nested loop, and
* another set of fully hydrated User models in memory. The depth is fixed
* in the code, and changing it means rewriting the loops.
*
* @return list<int>
*/
public function reachable(User $user): array
{
$user->load('follows.follows.follows');
$ids = [];
foreach ($user->follows as $hop1) {
$ids[$hop1->id] = true;
foreach ($hop1->follows as $hop2) {
$ids[$hop2->id] = true;
foreach ($hop2->follows as $hop3) {
$ids[$hop3->id] = true;
}
}
}
unset($ids[$user->id]);
return array_keys($ids);
}
}<?php
// app/Services/FollowGraph.php — the same three-hop reachability as one
// recursive query. The database walks the graph; PHP only reads the ids.
namespace App\Services;
use Illuminate\Support\Facades\DB;
use InvalidArgumentException;
final class FollowGraph
{
// The UNION removes duplicate (user_id, depth) rows. The depth bound stops
// the recursion even when the follow graph contains cycles.
private const REACHABLE_SQL = <<<'SQL'
WITH RECURSIVE reach (user_id, depth) AS (
SELECT followee_id, 1
FROM follows
WHERE follower_id = ?
UNION
SELECT f.followee_id, r.depth + 1
FROM reach r
JOIN follows f ON f.follower_id = r.user_id
WHERE r.depth < ?
)
SELECT DISTINCT user_id
FROM reach
WHERE user_id <> ?
ORDER BY user_id
SQL;
/**
* Returns the ids of every user within $maxHops follows of $userId.
*
* @return list<int>
*/
public function reachable(int $userId, int $maxHops = 3): array
{
if ($maxHops < 1) {
throw new InvalidArgumentException("maxHops must be at least 1, got {$maxHops}.");
}
$rows = DB::select(self::REACHABLE_SQL, [$userId, $maxHops, $userId]);
return array_map(static fn (object $row): int => (int) $row->user_id, $rows);
}
}
// Note: this is still relational SQL. For a real graph store, with its own
// query language and traversal engine, the laudis/neo4j-php-client package
// (composer require laudis/neo4j-php-client) talks to Neo4j and runs Cypher:
//
// use Laudis\Neo4j\ClientBuilder;
//
// $client = ClientBuilder::create()
// ->withDriver('bolt', 'bolt://neo4j:password@127.0.0.1:7687')
// ->withDefaultDriver('bolt')
// ->build();
//
// $result = $client->run(
// 'MATCH (u:User {id: $id})-[:FOLLOWS]->{1,3}(other:User)
// WHERE other <> u
// RETURN DISTINCT other.id AS id ORDER BY id',
// ['id' => $userId]
// );Laravel with Neo4j, using the community package laudis/neo4j-php-client (Packagist; README shows composer require laudis/neo4j-php-client, ClientBuilder::create()->withDriver('bolt', ...)->withDefaultDriver('bolt')->build(), readTransaction / writeTransaction taking a closure that receives a TransactionInterface, and run($query, $params) returning rows with get()). The README notes that transaction functions are retried automatically, so the function must be idempotent, and that the HTTP drivers were removed in 3.3.0; use bolt:// or neo4j://. We could not run PHP on the machine used to write this page, so treat the PHP as reviewed against the README rather than executed.
<?php
// app/Providers/GraphServiceProvider.php: one client per process, built from config.
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Laudis\Neo4j\Contracts\ClientInterface;
use Laudis\Neo4j\ClientBuilder;
final class GraphServiceProvider extends ServiceProvider
{
public function register(): void
{
$this->app->singleton(ClientInterface::class, static function (): ClientInterface {
// config/services.php: 'neo4j' => ['url' => env('NEO4J_URL', 'bolt://neo4j:secret@127.0.0.1:7687')]
return ClientBuilder::create()
->withDriver('bolt', (string) config('services.neo4j.url'))
->withDefaultDriver('bolt')
->build();
});
}
}
// app/Services/Neo4jFollowGraph.php: friends-of-friends and an idempotent follow.
namespace App\Services;
use InvalidArgumentException;
use Laudis\Neo4j\Contracts\ClientInterface;
use Laudis\Neo4j\Contracts\TransactionInterface;
final class Neo4jFollowGraph
{
public function __construct(private readonly ClientInterface $client)
{
}
/**
* Ids of every user within $maxHops follows of $userId.
*
* Cypher 5 does not accept a parameter as a variable-length bound, so the
* (validated) integer is formatted into the text. The id stays a parameter.
*
* @return list<int>
*/
public function reachable(int $userId, int $maxHops = 3): array
{
if ($maxHops < 1 || $maxHops > 6) {
throw new InvalidArgumentException("maxHops must be between 1 and 6, got {$maxHops}.");
}
$query = sprintf(
'MATCH (u:User {id: $id})-[:FOLLOWS*1..%d]->(other:User)
WHERE other <> u
RETURN DISTINCT other.id AS id
ORDER BY id',
$maxHops,
);
// A transaction function: the driver retries it on transient errors,
// so the body must be safe to run twice.
$ids = [];
$this->client->readTransaction(static function (TransactionInterface $tsx) use ($query, $userId, &$ids): void {
$ids = [];
foreach ($tsx->run($query, ['id' => $userId]) as $row) {
$ids[] = (int) $row->get('id');
}
});
return $ids;
}
/** MERGE makes the write idempotent, so a retried transaction does no harm. */
public function follow(int $followerId, int $followeeId): void
{
$this->client->writeTransaction(static function (TransactionInterface $tsx) use ($followerId, $followeeId): void {
$tsx->run(
'MATCH (a:User {id: $follower}), (b:User {id: $followee})
MERGE (a)-[r:FOLLOWS]->(b)
ON CREATE SET r.since = date()',
['follower' => $followerId, 'followee' => $followeeId],
);
});
}
}Shortest path
-- PostgreSQL: breadth-first with a path array; cycles are excluded by <> ALL (path).
WITH RECURSIVE bfs(user_id, depth, path) AS (
SELECT followee_id, 1, ARRAY[1, followee_id] FROM follows WHERE follower_id = 1
UNION ALL
SELECT f.followee_id, b.depth + 1, b.path || f.followee_id
FROM bfs b JOIN follows f ON f.follower_id = b.user_id
WHERE b.depth < 5 AND f.followee_id <> ALL (b.path)
)
SELECT depth, path FROM bfs WHERE user_id = 99999 ORDER BY depth LIMIT 1;
-- depth 5, {1,11353,92446,65865,17410,99999} on our lab dataNeo4j returned the same path with MATCH p = SHORTEST 1 (a:User {id: 1})-[:FOLLOWS]->+(b:User {id: 99999}) RETURN length(p), [n IN nodes(p) | n.id]. The SQL version enumerates all paths up to the bound before LIMIT 1 takes the first; a graph engine stops at the first shortest. For weighted routes use GDS Dijkstra (gds.shortestPath.dijkstra.stream).
Fraud rings: shared devices, addresses, cards
// Accounts that share two or more devices (Cypher, verified on a tiny dataset)
MATCH (a:Account)-[:USED]->(d:Device)<-[:USED]-(b:Account)
WHERE a.id < b.id
WITH a, b, count(d) AS shared
WHERE shared >= 2
RETURN a.id, b.id, shared ORDER BY shared DESC-- The same in SQL: self-join through the edge table, no depth needed for one shared device.
SELECT u1.account_id AS a, u2.account_id AS b, count(*) AS shared
FROM account_device u1
JOIN account_device u2 ON u2.device_id = u1.device_id AND u1.account_id < u2.account_id
GROUP BY 1, 2 HAVING count(*) >= 2 ORDER BY shared DESC;At one or two hops SQL is just as good (and the relational version needs device_id indexed). The graph version wins when the ring is found by following accounts, devices, addresses and cards four steps out, and with community detection (gds.louvain.stream, weakly connected components) over the whole graph. Exclude known shared devices (public Wi-Fi, a corporate NAT) or a supernode will connect everyone.
Recommendations and impact analysis
// People who bought what I bought also bought... (Cypher)
MATCH (me:User {id: $id})-[:BOUGHT]->(:Product)<-[:BOUGHT]-(peer:User)-[:BOUGHT]->(rec:Product)
WHERE NOT (me)-[:BOUGHT]->(rec)
RETURN rec.sku, count(DISTINCT peer) AS peers ORDER BY peers DESC LIMIT 10
// Everything that depends, directly or transitively, on a package (verified on a tiny dataset)
MATCH (p:Package {name: $name})<-[:DEPENDS_ON*1..]-(d:Package) RETURN DISTINCT d.name-- Impact analysis in PostgreSQL: reverse closure with UNION (not UNION ALL) so cycles terminate.
WITH RECURSIVE impacted(pkg_id) AS (
SELECT dependent_id FROM depends_on WHERE dependency_id = $1
UNION
SELECT d.dependent_id FROM impacted i JOIN depends_on d ON d.dependency_id = i.pkg_id
)
SELECT p.name FROM impacted i JOIN package p ON p.id = i.pkg_id;Here UNION on a single column does dedupe by node, so recursion ends on cycles without a depth bound; this is the case where the recursive CTE is as good as a graph engine.
Hierarchies with ltree and adjacency lists
For a single-parent tree (categories, an org chart) PostgreSQL's ltree extension stores the path as a label chain and indexes it with GiST.
CREATE EXTENSION ltree;
CREATE TABLE cat (id serial PRIMARY KEY, path ltree NOT NULL);
CREATE INDEX cat_path_gist ON cat USING gist (path);
INSERT INTO cat (path) VALUES ('Top'), ('Top.Science'), ('Top.Science.Astronomy'), ('Top.Hobbies');
SELECT path FROM cat WHERE path <@ 'Top.Science' ORDER BY path; -- Top.Science, Top.Science.Astronomy
SELECT path FROM cat WHERE path ~ 'Top.*{1}'; -- direct children of Top| Option | Good for | Limit |
|---|---|---|
Adjacency list (parent_id) + recursive CTE | Any depth, easy writes | Each level is a join |
ltree materialised path | Subtree and ancestor queries with one indexed operator | One parent per node; moving a subtree rewrites paths |
| Closure table | Fast ancestor/descendant, any DAG | Quadratic rows in the worst case |
| Nested set | Read-heavy fixed trees | Expensive writes |
| Graph database | Many relationship types, DAGs and cycles | A second system |
Apache AGE: Cypher inside PostgreSQL
CREATE EXTENSION age;
LOAD 'age';
SET search_path = ag_catalog, "$user", public;
SELECT create_graph('social');
SELECT * FROM cypher('social', $$
CREATE (:Person {name: 'Ann'})-[:KNOWS]->(:Person {name: 'Bob'})
$$) AS (result agtype);
SELECT * FROM cypher('social', $$
MATCH (a:Person {name: 'Ann'})-[:KNOWS*1..3]->(b:Person) RETURN b.name
$$) AS (name agtype);The AGE manual shows exactly this shape: cypher('graph_name', $$ ... $$) AS (result agtype). AGE is attractive when you want Cypher and your data is already in PostgreSQL; it is not a native graph store (the work is SQL over label tables), and its ecosystem and tooling are smaller than Neo4j's. We did not run AGE for this page; the statements are from its manual. Docker image: apache/age.
Use cases, and when not to use a graph database
| Use case | Why a graph fits | Typical pattern | Products used in practice |
|---|---|---|---|
| Social networks | Friends-of-friends, mutual follows, feeds from the neighbourhood | (u)-[:FOLLOWS*1..2]->() | Neo4j, Memgraph, TigerGraph |
| Fraud rings | Shared devices, cards, addresses link accounts | Shared-identifier pattern, community detection | Neo4j, TigerGraph, Neptune |
| Recommendations | Co-purchase and similarity over multi-hop paths | Collaborative filtering pattern | Neo4j, Memgraph, Neptune |
| Knowledge graphs | Entities and typed relationships from text and sources | RDF or LPG, linked data, GraphRAG | Neptune, Neo4j, GraphDB, Stardog |
| Dependency and impact analysis | Transitive closure over services, packages, tables | DEPENDS_ON* | Neo4j, AGE |
| Identity resolution and access graphs | Who can reach what through groups and roles | Reachability over MEMBER_OF, CAN edges | Neo4j, Neptune |
| Network and IT topology | Path, impact and root cause | Shortest path, centrality | Neo4j, TigerGraph |
| Supply chain and routing | Paths with costs | Dijkstra, A* | Neo4j GDS, TigerGraph |
When not to use one:
| Situation | Use instead | Reason |
|---|---|---|
| Mostly tabular data with occasional single-hop joins | PostgreSQL with an index | No new system to run |
| Whole-table aggregates and reporting | PostgreSQL, a columnar engine; see OLTP vs OLAP | Graph engines are not built for scans |
| Shallow bounded hierarchy (3 levels) | Adjacency list, ltree, closure table | Complexity not justified |
| Key lookups at massive scale and simple access patterns | Redis, DynamoDB, Cassandra; see Wide-Column & Key-Value | Partitionable by key |
| Write-heavy logs and time series | A log store or time-series store | Graph writes are heavier |
| Search by text | Full-Text Search | Different index structure |
| Embedding similarity only | Vector Search | Graph is optional |
| You cannot staff a second database | Apache AGE or recursive CTEs | Operational cost |
Choosing
| Workload | Recommendation | Extra technique | Reason |
|---|---|---|---|
| Category tree, breadcrumbs, org chart under 10 levels | PostgreSQL adjacency list or ltree | Index the parent and path columns | Nothing a graph engine adds is needed |
| Friends within 2 to 3 hops on a mid-sized social table | PostgreSQL recursive CTE | (follower_id, followee_id) primary key, depth bound | Measured on our lab at 3 to 11 ms |
| Deep or variable-depth paths over many edge types | Neo4j, Memgraph, Neptune or TigerGraph | Index the start property; profile | Path patterns are the language |
| Fraud detection on a growing identity graph | Neo4j or TigerGraph, fed by events | Community detection, exclude supernodes | Algorithms and multi-hop reach |
| Standards-based knowledge sharing and reasoning | RDF store with SPARQL (Neptune, GraphDB, Stardog, Jena) | SHACL, ontologies | Interchange and inference |
| Graph already in Cassandra or HBase | JanusGraph | Mixed index on Elasticsearch | Reuses the backend |
| Want Cypher but only PostgreSQL | Apache AGE | Index label tables | One database |
| Graph algorithms over a huge static graph | Neptune Analytics, Neo4j GDS, TigerGraph | Project and run in memory | Whole-graph computation |
In architecture: from a single process to a distributed system
Monolith: one process, one database
A Laravel or Go monolith with PostgreSQL stores users and follows. Friends-of-friends is a recursive CTE with a depth bound of three; category pages use ltree. No new infrastructure. This is the right design until a measured query is too slow or a new question (fraud rings, recommendations across five relationship types) becomes the product.
Modular monolith and multiple databases
A graph module owns a Neo4j (or AGE) database for one bounded context, for example "identity and risk". The relational database remains the system of record; the graph is a projection built from it. Each module talks through a repository interface (FollowGraph), so a PostgreSQL implementation and a Cypher implementation can be swapped and compared. Schema ownership and migrations for the relational side stay in Schema Migrations.
Microservices: events feed the graph
account-service --AccountCreated, DeviceUsed--> Kafka / RabbitMQ --> graph-projector --> Neo4j
payment-service --CardAdded, PaymentMade------> ^
risk-service --Cypher over Bolt--------------------------------------------------------+Services publish domain events (see Outbox Pattern); a projector consumes them and writes MERGE statements, which are idempotent, so at-least-once delivery is fine. The graph can be rebuilt by replaying events. The risk service reads the graph; it never writes the system of record. Cross-service transactions with the graph are eventual: a fraud check sees the device edge a few hundred milliseconds late, and the design must tolerate that.
Distributed data: replicas, caches and clusters
| Layer | What happens | Mitigation |
|---|---|---|
| Neo4j secondary | Read may lag the writer | Bookmarks (drivers manage them in a session) |
| Neptune replica | Reads from replicas see slightly stale data | Read from the primary for read-your-writes |
| Cache in front (Redis) | Top-N results cached per user | TTL, invalidate by event |
| PostgreSQL read replica | The projection source lags | Treat the graph as eventually consistent; see Replication |
| Cross-region | A single writer region | Regional graphs per tenant instead of one global graph |
Recommendation: do not distribute one graph if you can avoid it; see Sharding.
Scaling path: 1x, 10x, 100x
| Load | Design | Example |
|---|---|---|
| 1x | Recursive CTEs and ltree in PostgreSQL | 100k users, 1M edges: 3 to 65 ms for 3 to 5 hops on a laptop |
| 10x | Add the right composite index, depth bound and CYCLE; or add Neo4j or AGE for the hot query; cache top-N | 1M users: a projection graph in Neo4j |
| 100x | Neo4j cluster with secondaries or Neptune with up to 15 replicas; per-tenant graphs; GDS for batch scores; precompute | Fraud graph per region; nightly PageRank/Louvain written back |
Lab
Two Docker containers, the same graph in both, same question in SQL and Cypher. The numbers you get will differ from ours; the point is the method.
Setup.
docker run -d --name gdb-pg -e POSTGRES_PASSWORD=pg -p 55432:5432 postgres:16-alpine
docker run -d --name gdb-neo -p 57474:7474 -p 57687:7687 -e NEO4J_AUTH=neo4j/lab-password-1 neo4j:5
# wait until Neo4j answers: docker exec gdb-neo cypher-shell -u neo4j -p lab-password-1 "RETURN 1"-- docker exec -i gdb-pg psql -U postgres
CREATE TABLE users (id int PRIMARY KEY, name text NOT NULL);
CREATE TABLE follows (
follower_id int NOT NULL REFERENCES users(id),
followee_id int NOT NULL REFERENCES users(id),
since date NOT NULL DEFAULT current_date,
PRIMARY KEY (follower_id, followee_id)
);
CREATE INDEX follows_followee_idx ON follows (followee_id);
INSERT INTO users SELECT g, 'user' || g FROM generate_series(1, 100000) g;
SELECT setseed(0.42);
INSERT INTO follows (follower_id, followee_id)
SELECT g, 1 + floor(random() * 100000)::int
FROM generate_series(1, 100000) g, generate_series(1, 10) k
ON CONFLICT DO NOTHING;
DELETE FROM follows WHERE follower_id = followee_id;
ANALYZE follows;
SELECT count(*) FROM follows; -- about 999,945 rowsExport the exact same graph and load it into Neo4j:
docker exec gdb-pg psql -U postgres -c "\copy (SELECT id FROM users ORDER BY id) TO '/tmp/users.csv' CSV HEADER" \
-c "\copy (SELECT follower_id, followee_id FROM follows) TO '/tmp/follows.csv' CSV HEADER"
docker cp gdb-pg:/tmp/users.csv . && docker cp gdb-pg:/tmp/follows.csv .
docker exec gdb-neo mkdir -p /var/lib/neo4j/import
docker cp users.csv gdb-neo:/var/lib/neo4j/import/users.csv
docker cp follows.csv gdb-neo:/var/lib/neo4j/import/follows.csv// docker exec -i gdb-neo cypher-shell -u neo4j -p lab-password-1 (about 40 seconds on our machine)
CREATE CONSTRAINT user_id IF NOT EXISTS FOR (u:User) REQUIRE u.id IS UNIQUE;
LOAD CSV WITH HEADERS FROM 'file:///users.csv' AS row
CALL (row) { CREATE (:User {id: toInteger(row.id)}) } IN TRANSACTIONS OF 10000 ROWS;
LOAD CSV WITH HEADERS FROM 'file:///follows.csv' AS row
CALL (row) {
MATCH (a:User {id: toInteger(row.follower_id)}), (b:User {id: toInteger(row.followee_id)})
CREATE (a)-[:FOLLOWS]->(b)
} IN TRANSACTIONS OF 10000 ROWS;
MATCH ()-[r:FOLLOWS]->() RETURN count(r) AS edges; // 999945Experiment 1: friends of friends, depth 3, 4, 5 in PostgreSQL.
\timing on
WITH RECURSIVE reach(user_id, depth) AS (
SELECT followee_id, 1 FROM follows WHERE follower_id = 1
UNION
SELECT f.followee_id, r.depth + 1 FROM reach r JOIN follows f ON f.follower_id = r.user_id WHERE r.depth < 3
)
SELECT count(DISTINCT user_id) FROM reach WHERE user_id <> 1;
-- depth 3 -> 1105 users, a few ms | depth 4 -> 10470, about 10 ms | depth 5 -> 64921, about 65 ms (our run)Experiment 2: the same in Cypher.
MATCH (u:User {id: 1})-[:FOLLOWS*1..3]->(f:User) WHERE f <> u RETURN count(DISTINCT f) AS n;
// 1105 | 10470 | 64921, with --format verbose cypher-shell prints "results consumed after another N ms"
// depth 3 -> a few ms | depth 4 -> about 6 ms | depth 5 -> about 50 to 90 ms (our run)Experiment 3: look at the plans. PostgreSQL: EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF) on the CTE shows Recursive Union, WorkTable Scan and Index Only Scan using follows_pkey; the cost per iteration is one index probe per working-table row. Neo4j: PROFILE shows NodeUniqueIndexSeek on :User(id) and VarLengthExpand, with db hits as the cost.
Experiment 4: shortest path. In SQL use the path-array query above; in Cypher MATCH p = SHORTEST 1 (a:User {id: 1})-[:FOLLOWS]->+(b:User {id: 99999}) RETURN length(p). Both returned 5 hops and the same node sequence on our data.
Experiment 5: break the SQL. Remove WHERE r.depth < 3 and run with UNION ALL on a graph with a cycle (insert INSERT INTO follows VALUES (2, 1)): the query never ends. Set SET statement_timeout = '5s' first. Then fix it with UNION, a depth bound, or the CYCLE clause.
Experiment 6: run Go. cd docs/snippets/database/graph-databases/go && go vet ./..., then call Reachable from neo4j/follows.go with neo4j://localhost:57687 and the lab credentials.
Clean up. docker rm -f gdb-pg gdb-neo.
Common misconceptions
| Belief | Reality |
|---|---|
| Graph databases are always faster than SQL | Faster for deep, variable-length, multi-type traversals at scale; on a 100k-user, 1M-edge graph PostgreSQL was within the same order of magnitude in our run |
| Index-free adjacency means no indexes | You still index the starting nodes; only hops avoid the index |
| Recursive CTEs cannot do graphs | They can, if bounded and cycle-safe; they just have no graph-native planner |
| GraphQL needs a graph database | GraphQL is an API layer over any store |
| A graph database scales out like Cassandra | Graphs have no natural partition key; edge cuts cost network hops |
| Property graph and RDF are the same | Different models: RDF has global identifiers, reasoning and no native edge properties |
| Cypher and Gremlin are interchangeable | Declarative pattern vs traversal steps, with different product support |
| Graph databases have no transactions | Neo4j, Memgraph and others are ACID; JanusGraph follows its backend |
| Schemaless means no modeling | The model decides query cost; poor modeling is the main failure |
| You can parameterise any part of a Cypher query | Not the variable-length bound in Cypher 5 (*1..$d fails); validate and format an integer |
| A graph database replaces my relational database | It is usually a projection or a specialised store beside the system of record |
Cheat sheet
| Topic | What to remember |
|---|---|
| Model | Labeled property graph: nodes with labels, relationships with one type, direction and properties |
| RDF | Triples with IRIs, queried with SPARQL; no native edge properties |
| Index-free adjacency | Hops follow pointers; the start node still needs an index |
| Native vs non-native | Native: Neo4j, Memgraph, TigerGraph; non-native: JanusGraph, Apache AGE |
| Recursive SQL | WITH RECURSIVE plus depth bound, UNION or CYCLE clause |
| Cypher | MATCH (a)-[:T*1..3]->(b) or -[:T]->{1,3}; MERGE is idempotent |
| GQL | ISO/IEC 39075:2024, Cypher-aligned |
| Gremlin | g.V().repeat(out()).times(n); TinkerPop; JanusGraph, Neptune |
| Neo4j | Store files, page cache (server.memory.pagecache.size), transaction log, primaries and secondaries |
| Algorithms | GDS: project, then PageRank, Louvain, betweenness, Dijkstra |
| Modeling | Nouns to nodes, verbs to relationships, hyperedge to a node, time on the edge |
| Supernodes | Filter by type and direction, bucket, exclude |
| Sharding | Edge cuts make traversals cross the network; prefer vertical scale, replicas, per-tenant graphs |
| Drivers | Go neo4j-go-driver/v6, PHP laudis/neo4j-php-client; transaction functions are retried, keep them idempotent |
| Decision | Start with PostgreSQL; move when the hot query is a deep path and you have measured |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — What does "index-free adjacency" mean, and does it mean a graph database needs no indexes? Important
Answer
Answer: Nodes store direct references to their relationships, so a hop from a known node does not go through an index. You still need an index or constraint to find the starting node. See Index-free adjacency.
2 — Give three differences between a labeled property graph and RDF. Good to know
Answer
Answer: An edge can carry properties in an LPG; RDF triples cannot without reification, named graphs or RDF-star. RDF uses global IRIs and supports reasoning; LPG uses local ids. Cypher/Gremlin versus SPARQL. See Labeled property graph and RDF.
3 — Why can a recursive CTE loop forever, and what are two ways to stop it? Must-know
Answer
Answer: If the recursive part keeps returning rows (a cycle), nothing ends it. Use UNION (deduplicate rows), a depth bound in the WHERE, or the CYCLE clause (PostgreSQL 14 and later). See Traversal vs joins.
4 — In our lab, how did PostgreSQL's recursive CTE compare with Neo4j at three to five hops, and what should you conclude? Good to know
Answer
Answer: Same order of magnitude on 100,000 users and about one million edges. Conclude that a graph engine's advantage depends on size, depth, fan-out and pattern complexity, and measure your own data.
5 — Why can you not use a parameter for the hop count in a Cypher 5 variable-length pattern, and what do you do instead? Good to know
Answer
Answer: Neo4j 5.26 rejects *1..$d at compile time. Validate an integer in application code and format it into the query text; keep every user value as a parameter. See Query languages.
6 — What is the difference between Cypher, GQL and Gremlin? Important
Answer
Answer: Cypher is Neo4j's declarative pattern language (openCypher is the open spec); GQL is the ISO/IEC 39075:2024 standard aligned with it; Gremlin is TinkerPop's step-by-step traversal language.
7 — What are a supernode and one mitigation? Important
Answer
Answer: A node with a huge number of relationships, making any traversal through it very expensive. Filter by relationship type and direction, bucket it, or exclude it from joins. See Supernodes.
8 — Why is sharding a graph hard? Important
Answer
Answer: Edges cross every partition cut, so a multi-hop query becomes network round trips, and optimal partitioning is NP-hard. Prefer vertical scale, replicas and per-tenant graphs. See Sharding.
9 — Name four GDS algorithm families and one procedure each. Good to know
Answer
Answer: Path finding (gds.shortestPath.dijkstra.stream), centrality (gds.pageRank.stream, gds.betweenness.stream), community detection (gds.louvain.stream), similarity (gds.nodeSimilarity.stream). See Graph algorithms.
10 — Is GraphQL a graph database? Must-know
Answer
Answer: No. It is an API query language; it can sit on PostgreSQL, MongoDB or Neo4j. See GraphQL.
11 — Why must the body of a Neo4j transaction function be idempotent? Important
Answer
Answer: The driver retries transaction functions after transient errors, so the body can run more than once. Use MERGE instead of CREATE for writes. See Transactions.
12 — When would you not use a graph database? Must-know
Answer
Answer: Shallow bounded hierarchies, single-hop joins, whole-table aggregates, key lookups at scale, or when you cannot operate a second database. See Use cases.
Glossary
| Term | Meaning |
|---|---|
| Graph database | A DBMS whose data model is nodes and relationships |
| Property graph / labeled property graph (LPG) | Directed, attributed multigraph with labels and key/value properties on nodes and edges |
| Node (vertex) | An entity in the graph |
| Relationship (edge) | A directed, typed connection with optional properties |
| Label | A tag on a node, such as :User |
| Relationship type | The single name of an edge, such as FOLLOWS |
| Property | A key/value on a node or relationship |
| RDF | Resource Description Framework: data as subject-predicate-object triples |
| Triple / quad | A statement; a quad adds the named graph |
| IRI | Global identifier used in RDF |
| SPARQL | The W3C query language for RDF |
| Property path | A SPARQL pattern for repeated predicates, such as foaf:knows+ |
| Reification / RDF-star | Ways to attach data to an RDF statement |
| Index-free adjacency | A node holds direct references to its neighbours or relationships |
| Native graph storage | Storage designed for graphs (Neo4j, Memgraph, TigerGraph) |
| Non-native graph | A graph layer over another store (JanusGraph, Apache AGE) |
| Traversal | Walking the graph from a starting node along relationships |
| Hop | One relationship step |
| Variable-length path | A pattern with a hop range, *1..3 |
| Quantified path pattern | GQL/Cypher 25 form of a variable-length path, {1,3} |
| Recursive CTE | WITH RECURSIVE query that feeds its output back until no new rows |
CYCLE clause | PostgreSQL 14+ syntax that marks revisited values in a recursive query |
| Cypher | Neo4j's declarative graph query language |
| openCypher | Open specification of Cypher |
| GQL | Graph Query Language, ISO/IEC 39075:2024 |
| SQL/PGQ | Property Graph Queries, SQL:2023 Part 16 |
| Gremlin | Apache TinkerPop's traversal language |
| Apache TinkerPop | Vendor-neutral graph computing framework and Gremlin |
| Gremlin Server | The server that executes Gremlin traversals |
| GSQL | TigerGraph's query language |
| Bolt | Neo4j's binary client protocol (bolt://, neo4j://) |
MERGE | Cypher clause: match or create; idempotent writes |
| Transaction function | A driver callback that is committed or retried automatically |
| Bookmark | Token that lets a cluster route a read after a given transaction (causal consistency) |
| Page cache | Neo4j's memory cache of store files and indexes |
Store format (aligned, block) | How Neo4j lays out data on disk |
| Primary / secondary | Neo4j database roles: transaction processing vs read scale |
| Raft | Consensus protocol used among primaries |
| Causal consistency | A client always reads at least its own writes |
| Supernode (dense node) | A node with a huge number of relationships |
| Edge cut | Edges crossing a partition boundary when a graph is split |
| Hyperedge | A relationship connecting more than two nodes |
| Reified relationship | A relationship turned into a node so it can carry its own relationships |
| GDS (Graph Data Science) | Neo4j's library for graph algorithms |
| Graph projection / catalog | The named in-memory graph GDS algorithms run on |
| PageRank | Centrality by incoming links weighted by the importance of linkers |
| Betweenness centrality | How often a node lies on shortest paths between others |
| Louvain | Community detection by modularity optimisation |
| Shortest path / Dijkstra | Fewest hops or lowest cost route |
| Weakly connected components | Groups of nodes connected ignoring direction |
| Fraud ring | A group of accounts linked by shared identifiers |
| Knowledge graph | A graph of entities and typed relations, often RDF or LPG |
ltree | PostgreSQL extension for label-path hierarchies |
| Adjacency list / closure table | Relational encodings of trees and DAGs |
| Apache AGE | PostgreSQL extension adding openCypher and agtype |
agtype | AGE's JSON-like result type |
$graphLookup | MongoDB aggregation stage for recursive reference lookups |
| GraphQL | An API query language; not a database |
neo4j-go-driver | Neo4j's official Go driver (github.com/neo4j/neo4j-go-driver/v6) |
laudis/neo4j-php-client | Community PHP Bolt client for Neo4j |
References
- Neo4j, "What is a graph database", Getting Started. neo4j.com/docs/getting-started/graph-database
- Neo4j, Cypher Manual: Introduction, Variable-length patterns, Indexes
- Neo4j, "ISO GQL: A defining moment in the history of database innovation". neo4j.com/blog/cypher-and-gql/gql-international-standard
- Wikipedia, "Graph Query Language" (ISO/IEC 39075:2024) and "Graph database" (secondary). en.wikipedia.org/wiki/Graph_Query_Language, en.wikipedia.org/wiki/Graph_database
- Neo4j Operations Manual: Store formats, Memory configuration, Clustering introduction
- Neo4j Graph Data Science: PageRank, Louvain, Betweenness, Dijkstra source-target
- Neo4j Go Driver manual. neo4j.com/docs/go-manual/current; package pkg.go.dev/github.com/neo4j/neo4j-go-driver/v6/neo4j
laudis/neo4j-php-client: Packagist, README- Apache TinkerPop, Reference Documentation. tinkerpop.apache.org/docs/current/reference
- W3C: RDF 1.1 Concepts and Abstract Syntax, SPARQL 1.1 Query Language
- openCypher. opencypher.org
- Amazon Neptune, "What is Amazon Neptune?" and transactions. docs.aws.amazon.com/neptune/latest/userguide/intro.html, transactions
- Memgraph documentation: overview, storage memory usage, transactions
- TigerGraph DB documentation. docs.tigergraph.com/tigergraph-server/current/intro
- JanusGraph documentation. docs.janusgraph.org
- Apache AGE manual: Overview, Cypher query format, Setup
- PostgreSQL documentation: 7.8 WITH Queries, ltree
- Laravel 13 documentation: Database: Running Queries, Query Builder
- Go documentation:
database/sql