Skip to content

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 forGo to
Tables you can memorise in one minuteEverything in one minute
Why graph databases exist, and the first three misunderstandingsWhy graph databases exist
History: Cypher, openCypher, GQL, TinkerPop, RDFWhere it comes from
One concept with a timeline and codeThe concept catalogue
Labeled property graph, RDF, SPARQLProperty graph, RDF
Index-free adjacency, native vs non-nativeIndex-free adjacency
Graph traversal vs recursive joins and benchmark caveatsTraversal vs joins
Cypher, GQL, Gremlin, SPARQL side by sideQuery languages
Nodes, edges, properties, hyperedges, timeModeling
Indexes, constraints and full-text in a graph storeIndexes
Transactions, consistency, supernodesTransactions, Supernodes
Why you cannot just shard a graphSharding
PageRank, Louvain, shortest path, GDSGraph algorithms
GraphQL is not a graph databaseGraphQL
Neo4j, Neptune, Memgraph, TigerGraph, JanusGraph, AGE comparedPer-product behaviour
Neo4j store files, page cache, transaction log, clusteringMechanics
Friends-of-friends, shortest path, fraud rings, recommendations, impact analysis in SQL, Cypher, Go, LaravelSolving the classic problems
Use cases and when not to use a graph databaseUse cases, Choosing
Monolith to distributed dataIn architecture
Reproduce Neo4j vs PostgreSQL timing in DockerLab
Wrong beliefs, cheat sheet, questions, termsMisconceptions, Cheat sheet, Self-check, Glossary

Everything in one minute ​

The models. Every row is unpacked in the concept catalogue.

ModelUnit of dataEdge can carry properties?Typical languageTypical productsBest at
Labeled property graph (LPG)Node with labels and key/value properties; relationship with one type, a direction and propertiesYesCypher, GQL, GremlinNeo4j, Memgraph, TigerGraph, JanusGraph, Neptune, Apache AGEApplication 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)SPARQLNeptune (SPARQL), Apache Jena, Stardog, GraphDB, Oracle RDF GraphInterchange, ontologies, reasoning, linked data
Relational tables with edge tablesRows; edges are rows in a join tableYes, as columnsSQL, recursive CTEsPostgreSQL, MySQL, SQL Server, Oracle, SQLiteData that is mostly tabular with some shallow graph questions
Document with referencesDocuments; edges are ids or $graphLookupYes, inside the documentMongoDB aggregationMongoDBOccasional bounded traversal inside documents
HypergraphEdge that connects more than two nodesYesRare natively; modeled as an extra nodeHyperGraphDB (rare)N-ary relationships

The things you keep reading.

KeywordIn plain wordsTiny exampleWhere it matters
Index-free adjacencyA node points straight at its relationships; no index lookup per hopAnn's record holds the address of her first FOLLOWS recordDeep traversals
Native vs non-native graph storageStorage laid out for graphs, or a graph API on top of another storeNeo4j (native) vs JanusGraph on Cassandra (non-native)Latency, operations
Recursive CTEA SQL query that feeds its own output back in until nothing new appearsWITH RECURSIVE reach ...Graph questions in PostgreSQL, MySQL, SQL Server, SQLite
Variable-length pathA pattern with a hop range(a)-[:FOLLOWS*1..3]->(b)Cypher, Gremlin repeat().times()
Quantified path patternThe GQL-aligned spelling of the same idea(a)-[:FOLLOWS]->{1,3}(b)Cypher 25 / Neo4j 5.9+
Shortest pathFewest hops (or lowest cost) between two nodesSix degrees of separationRouting, social, network
Supernode (dense node)A node with millions of edgesA celebrity, a country, a popular tagTraversal blow-ups
Edge cutThe edges severed when you split a graph across machinesFriend edges crossing two shardsWhy graph sharding is hard
Property graph vs GraphQLA data model vs an API query languageGraphQL can sit on top of PostgreSQLNaming confusion

The three things to do.

SituationDo 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 occasionalWITH 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 algorithmsA 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 / relationalGraph database
Relationships are derived at query time by joining on foreign keysRelationships 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 migrationNew relationship type: just create it; schema is optional
Strong at aggregates over millions of rows, reporting, constraintsStrong at paths, neighbourhoods, patterns, algorithms
One mature, well-tooled model for tabular dataA 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 ​

  1. "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.
  2. "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.
  3. "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.

YearEventWhy it matters
1999 to 2004W3C RDF and the semantic web family; RDF 1.0 in 2004Origin of triples, URIs and ontologies
2007 onwardNeo4j property graph engine (Java), native storageThe first widely used native LPG database
2010CypherDeclarative ASCII-art pattern matching
2009 to 2015Apache TinkerPop and Gremlin; Titan, then JanusGraphA vendor-neutral traversal API on top of many stores
2013SPARQL 1.1Property paths (+, *), updates, federation
2015openCypher open specificationCypher implemented by Memgraph, Neptune, TigerGraph, AGE and others
2023SQL/PGQ in the SQL standardGraph pattern matching inside SQL
April 2024ISO/IEC 39075:2024 GQLFirst 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.

text
        ┌────────────┐   KNOWS {since: 2019}   ┌────────────┐
        │ :Person    │ ──────────────────────▶ │ :Person    │
        │ name: Ann  │                         │ name: Bob  │
        └─────┬──────┘                         └─────┬──────┘
              │ WORKS_AT {role: 'CTO'}               │ WORKS_AT {role: 'Dev'}
              ▼                                      ▼
        ┌──────────────────────────────────────────────────┐
        │ :Company  name: Acme                              │
        └──────────────────────────────────────────────────┘
Property graphRelational tables:PersonAnn:PersonBob:CompanyAcme:KNOWS {since: 2019}:WORKS_AT {role}:WORKS_ATpersonid PK, namecompanyid PK, nameknows (join table)a_id FK, b_id FK, sinceemployment (join table)person_id FK, company_id FK, roleEvery hop is a JOIN on foreign keysEdge properties need extra columns per join tableA new relationship type means a new table

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 featureNeo4jMemgraphNeptuneTigerGraphJanusGraphApache AGE
Labels on nodesMany labels per nodeMany labels per nodeOne label in Gremlin, openCypher labelsVertex types (schema first)Vertex label (one)Label (one per vertex)
Edge propertiesYesYesYesYesYesYes (agtype)
SchemaOptional; constraints availableOptionalSchema-lessSchema-first (GSQL)Optional, recommendedSchema-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:

sql
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.

text
# 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" .
sql
-- 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.

ConcernProperty graph (Cypher, Gremlin)RDF (SPARQL)
Edge propertiesNativeReification, named graphs or RDF-star
IdentityLocal ids, application keysGlobal IRIs
Reasoning/inferenceNot built inRDFS/OWL entailment in many triple stores
SchemaOptional constraintsOntologies (OWL, SHACL for validation)
InterchangeVendor formats, CSV, GraphMLStandard serializations (Turtle, N-Triples, JSON-LD)
Application traversalsPrimary use casePossible, 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.

Native graph store: follow pointersRelational: probe an index per hopnode Annfirst rel ptrrelationshipKNOWS, to node ptrnode Bobfirst rel ptrrelationshipnext hop ...Cost per hop ~ the relationships actually touched, not the size of the tableperson rowPK lookupB-tree on knows(a_id)O(log n) probeperson rowPK lookupB-tree probeagain ...k hops = k joins; the planner must guess each intermediate size
text
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 lookup

Real 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.

EngineNative graph layout?Where hops resolve
Neo4jYes: record stores (aligned) or block formatPointers in relationship records, via the page cache
MemgraphYes, in-memoryPointers in RAM
TigerGraphYes (native parallel graph)Own storage engine, MPP
Amazon NeptunePurpose-built graph engine on a shared cluster volumeEngine indexes over the cluster volume
JanusGraphNo: backed by Cassandra, HBase or BerkeleyDB JEBackend key lookups per adjacency list
Apache AGENo: PostgreSQL tables per labelSQL 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.

AnchorIteration 1Iteration 2Iteration 3 ...follower_id = 110 rows, depth 1work table JOINfollows: ~100 rowswork table JOINfollows: ~1000 rowsstops at depth boundor when no new rowsUNION (not UNION ALL) drops rows already in the result.But it compares whole rows (user_id, depth), so the same user at two depths survives.Without a depth bound or CYCLE clause, a cycle (Ann follows Bob follows Ann) never ends.Real intermediate rows grow roughly as fan-out to the power of depth.
text
     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   stop

Real 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:

QuestionWhy 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:

DepthPostgreSQL 16 recursive CTENeo4j 5.26 variable-length MATCH
3 hopsabout 3 msabout 2 to 5 ms
4 hopsabout 11 msabout 6 ms
5 hopsabout 65 msabout 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
-- 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;
text
// 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 }
text
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 Bolt

Real 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.

LanguageStyleStandardUsed byVariable-length idiom
Cypher 5 / 25Declarative patternNeo4j product languageNeo4j, Memgraph (dialect), Neptune (openCypher subset)*1..3 or {1,3}
openCypherDeclarative patternOpen specificationNeptune, TigerGraph, Apache AGE, Memgraph*1..3
GQLDeclarative patternISO/IEC 39075:2024Aligning products (Neo4j, Google Spanner Graph)quantified paths {1,3}, +, *
GremlinImperative traversal stepsApache TinkerPop (not a formal standard)JanusGraph, Neptune, Azure Cosmos DB for Gremlinrepeat(...).times(3)
SPARQL 1.1Triple patternsW3C RecommendationNeptune, Jena, GraphDB, Stardogproperty paths + *
GSQLDeclarative, accumulatorsTigerGraph product languageTigerGraphACCUM, POST-ACCUM, hop blocks
SQL/PGQGRAPH_TABLE match in SQLSQL:2023 Part 16Oracle Database 23ai (verify others)path quantifiers
Recursive CTESQLSQL:1999, all major enginesPostgreSQL, MySQL 8, SQL Server, Oracle, SQLite, CockroachDBWITH 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:

DecisionRule 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 typeSpecific and verb-like (PURCHASED, REPORTS_TO), not RELATED_TO
DirectionStore 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)
TimePut valid_from and valid_to on relationships, or model versions as nodes with NEXT/SUPERSEDES edges
Supernode riskDo not hang a million edges off one node if you can fan out by bucket (Day, Region)
text
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)
sql
-- "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.

PatternUse whenCost
Time-stamped relationshipFew changes per edge, point-in-time questionsEvery traversal filters on the stamps
Version node chainWhole entity versions are auditedMore nodes, more hops
Snapshot graphs per periodHeavy analytics per periodStorage duplication
Event nodes (events as nodes in a timeline)Event sourcing into a graphNeeds 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.

text
// 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 forNotes
RangeEquality, ranges, prefix, orderingThe default CREATE INDEX
TextCONTAINS, ENDS WITH on stringsNot for ordering
PointSpatial lookupsNeeds point properties
Token lookupLabel and relationship-type scansOn by default
Full-textLexical search with scoringQueried through a procedure
VectorSimilarity search over embeddingsVector index memory lives outside the page cache per the Neo4j docs; see Vector Search
EngineWhere indexes live
Neo4jProperty indexes and constraints per label; token lookups
MemgraphLabel and label-property indexes, plus constraints
NeptuneBuilt-in indexes over the graph; you do not create them
JanusGraphComposite and mixed indexes; mixed indexes delegate to Elasticsearch, Solr or Lucene
TigerGraphVertex/edge attribute indexes through the schema
Apache AGEPostgreSQL 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".

text
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 write

Real 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.

EngineTransactionsIsolation (documented behaviour)Distribution
Neo4jACID, transaction logRead committed (default) with locks on written entitiesPrimaries (Raft) plus secondaries, causal consistency via bookmarks
MemgraphACID in IN_MEMORY_TRANSACTIONALSNAPSHOT_ISOLATION default; READ_COMMITTED and READ_UNCOMMITTED selectableReplication; see its docs for HA
Amazon NeptuneACIDDefined in Neptune's transaction-semantics page (isolation levels per query type); check it before relying on a levelOne writer, up to 15 replicas on a shared cluster volume
TigerGraphACID transactions ("Transaction and ACID" in its Architecture docs)See that pageDistributed MPP
JanusGraphDepends on backendBackend-definedCassandra, HBase, BerkeleyDB JE
Apache AGEPostgreSQL transactionsPostgreSQL isolation levels applyWhatever 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.

text
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 hop

Real 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.

MitigationHowTrade-off
Filter by relationship type and direction-[:FOLLOWS]-> not --Cheapest and always first
Bucket nodesCelebrity -> Day bucket -> followersMore modeling
Limit and sampleLIMIT per hop; algorithms with a sampling sizeApproximate answers
Exclude from fraud joinsIgnore known shared devices/IPs by a flag propertyNeeds a maintained list
Degree propertyStore degree and skip nodes above a thresholdMust 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.

text
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 trips

Real scenarios: a social network that outgrows one machine; a knowledge graph with trillions of edges; a fraud graph that must stay consistent.

StrategyHowAdvantageCost
Vertical scale and RAMOne big machine, graph in memory or page cacheLocal pointers, simpleMachine limit
Read replicasNeo4j secondaries; Neptune up to 15 replicasRead scale-out, availabilityWrites still hit one writer
Federation / multiple graphsOne database per tenant or domain (Neo4j multi-database)Natural boundaries, no cutNo cross-graph traversal
Distributed engineTigerGraph MPP, JanusGraph on Cassandra, Spanner GraphScales storage and writesNetwork hops per cut edge, complexity
Property or workload shardingSplit properties from topology (newer in some engines)Scales propertiesTopology 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.

text
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'})
text
// 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
FamilyAlgorithmAnswersGDS procedure (stream mode)
Path findingShortest path, Dijkstra, A*, Yen's k shortest, BFS/DFSCheapest or fewest-hop routegds.shortestPath.dijkstra.stream
CentralityPageRank, betweenness, closeness, degreeWho is important or a brokergds.pageRank.stream, gds.betweenness.stream
Community detectionLouvain, Leiden, label propagation, weakly connected componentsWhich groups clustergds.louvain.stream
SimilarityNode similarity, k-nearest neighboursWho is alikegds.nodeSimilarity.stream
EmbeddingsFastRP, node2vecVectors for MLgds.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.

text
// 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.

text
Client --GraphQL--> resolver --SQL--> PostgreSQL
Client --GraphQL--> resolver --Cypher--> Neo4j
Client --GraphQL--> resolver --HTTP--> three microservices

Real 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.

QuestionGraphQLGraph database
What is it?API query language and runtimeDBMS
Who calls it?Browser and mobile clientsYour services
TraversalDeclared by the client, executed by resolversExecuted by the engine
Replaces PostgreSQL?NoSometimes, 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.

ProductModel and storageLanguagesTransactions and scaleNotes
Neo4jNative labeled property graph; record formats aligned (Community default) and block (Enterprise, recommended); standard and high_limit deprecated in 5.23Cypher 5 / Cypher 25, Bolt protocolACID, transaction log; cluster of primaries and secondaries, causal consistency with bookmarksGraph Data Science, APOC, Browser, Bloom; drivers in Go, PHP (community), Java, Python, JavaScript, .NET
Amazon NeptuneFully managed purpose-built engine; Neptune Analytics for in-memory analyticsGremlin, openCypher, SPARQLOne 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 transitProperty graph and RDF in one service, not mixed in one dataset
MemgraphIn-memory native property graph; storage modes IN_MEMORY_TRANSACTIONAL (default), IN_MEMORY_ANALYTICAL, ON_DISK_TRANSACTIONALCypher over BoltDefault isolation SNAPSHOT_ISOLATIONMAGE algorithm modules, streaming ingestion
TigerGraphNative parallel (MPP) graph databaseGSQL, openCypher in GSQLDistributed, ACID transactions documented in its architecture sectionSchema-first; strong on deep multi-hop analytics at scale
JanusGraphGraph 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 backendThe Titan successor; non-native
Apache AGEPostgreSQL extension; Cypher inside SQL; "single storage that can handle both relational and graph model data"openCypher via cypher() function, returns agtypePostgreSQL's transactions, MVCC, replication, backupSmaller ecosystem than Neo4j
ArangoDBMulti-model (document, key/value, graph)AQLCluster with auto-shardingGraph traversals in AQL
Google Spanner GraphGraph on SpannerGQL, openCypherGlobal consistencyManaged
Oracle Database 23aiProperty graph views over relational tables, SQL/PGQ; also RDF Graph with SPARQLSQL/PGQ, SPARQL, PGQLOracle's transaction engineGraph over relational data you already hold
SQL ServerNODE and EDGE tables with the MATCH clause (since 2017)T-SQLSQL ServerGraph tables are ordinary tables with hidden columns; check your edition
MongoDBDocuments; $graphLookup aggregation stage walks referencesMQLReplica sets and sharded clustersRecursive lookup inside one collection, bounded maxDepth; sharded collections have restrictions
MySQL (InnoDB)TablesSQL with recursive CTEs (8.0 and later)InnoDBNo graph engine; cte_max_recursion_depth guards loops
SQLiteTablesSQL with recursive CTEsSingle writerFine for small embedded graphs
CockroachDBTablesPostgreSQL-compatible SQL with recursive CTEsDistributed SQLA graph engine is not part of it
RedisKey-value; the RedisGraph module was retired and a fork continues as FalkorDBCypher (module)In-memoryCheck current status before adopting

Choosing a native engine, in one table:

If you needLook atWhy
The largest ecosystem, tools and algorithmsNeo4jGDS, Browser, drivers, community
A managed service on AWS, with SPARQL tooAmazon NeptuneShared storage, replicas, no operations
Low latency on a graph that fits in RAM and streaming ingestMemgraphIn-memory engine
Deep multi-hop analytics across a clusterTigerGraphMPP engine
An existing Cassandra or HBase, Gremlin codeJanusGraphReuses the backend
Graph queries inside PostgreSQL, one operational surfaceApache AGE or recursive CTEsNo 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".

text
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)MeaningDefault seen in the 5.26 container
server.memory.pagecache.sizeMemory used to cache graph data and indexes from disk; the manual recommends defining it explicitly512.00MiB (set by the image)
server.memory.heap.initial_size / max_sizeJVM heapUnset in the container
db.formatStore format for a new databasealigned in Community
db.tx_log.rotation.sizeWhen the transaction log file rotates256.00MiB
db.checkpoint.interval.timeHow often a checkpoint flushes pages15m
db.checkpoint.interval.txCheckpoint after this many transactions100000
db.checkpoint.interval.volumeCheckpoint after this much log volume250.00MiB
dbms.memory.transaction.total.maxCap on transaction memoryUnset

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.

text
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 checkpoint

Clustering: 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.

ConceptNeo4j termNotes
Write replica set with consensusPrimaries (Raft group)One writer at a time
Read scale-outSecondariesEventually catch up; use bookmarks for read-your-writes
Read-your-writesBookmark / causal consistencyHandled by the driver session
Routingneo4j:// URI, routing tablebolt:// is direct
Whole-graph shardingNot part of the cluster modelUse multiple databases or federation; see Sharding

Memgraph, Neptune, TigerGraph, JanusGraph and AGE internals in brief Good to know ​

ProductWhat 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 NeptunePrimary 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
TigerGraphNative parallel graph; GSQL with accumulators; openCypher support inside GSQL; GraphStudio visual tools
JanusGraphAdjacency lists are stored as rows in Cassandra/HBase (wide rows); mixed indexes via Elasticsearch/Solr/Lucene; Gremlin Server
Apache AGECreates 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 ​

WhereCode or messageMeaningRetry?
Neo4jNeo.ClientError.Schema.ConstraintValidationFailed ("Node(0) already exists with label User and property id = 1" seen in our run)Uniqueness constraint violatedNo: fix data or use MERGE
Neo4jNeo.ClientError.Statement.SyntaxError ("Invalid input 'MATC'...")Cypher does not parseNo
Neo4jNeo.ClientError.Statement.ParameterMissingA $param was not suppliedNo
Neo4jNeo.TransientError.Transaction.DeadlockDetectedTwo transactions locked in opposite orderYes, in a transaction function (the driver does)
Neo4jNeo.TransientError.General.DatabaseUnavailable or leader switchCluster failoverYes, with backoff
Neo4jNeo.ClientError.Security.UnauthorizedBad credentialsNo
PostgreSQLNo error: the query runs until cancelled or statement_timeout firesA recursive CTE with a cycle, UNION ALL, and no bound or CYCLE clauseFix the query; set statement_timeout
PostgreSQLSQLSTATE 40001 / 40P01Serialization failure or deadlockYes; see Isolation Levels and Deadlocks
MySQL 8ERROR 3636 (HY000) "Recursive query aborted after N iterations" governed by cte_max_recursion_depthRecursion cap hit (MySQL 8.0)Raise the cap or bound the query
NeptuneConcurrentModificationException (Gremlin)Write conflict between concurrent mutationsYes, with backoff

Solving the classic problems ​

One subsection per classic problem, with the solution table first, then SQL (PostgreSQL), Cypher, Go and Laravel.

ProblemPreferred solutionHowAdvantageCost or limitation
Friends within N hopsRecursive CTE or MATCH ... *1..NBound the depth; dedupe by nodeOne statement, no application loopFan-out to the power of depth
Shortest pathSHORTEST 1 / shortestPath() / GDS DijkstraBFS or Dijkstra in the engineEngine-optimisedSQL needs a path array and a bound
Fraud ringsShared-identifier pattern or Louvain / weakly connected components(a)-[:USED]->(d)<-[:USED]-(b)Reads like the questionSupernode devices must be excluded
RecommendationsCollaborative filtering pattern, node similarityTwo-hop co-purchase pattern, count distinct peersReal timeNeeds a feed from the system of record
Impact analysisReverse transitive closure(d)-[:DEPENDS_ON*1..]->(p)Whole closure in one queryCycles in dependency data
Hierarchy and breadcrumbsltree or recursive CTEMaterialised path, GiST indexNo second databaseSingle-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.

go
// 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.

sql
-- 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
go
// 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):

text
MATCH (u:User {id: $id})-[:FOLLOWS*1..3]->(other:User)
WHERE other <> u
RETURN DISTINCT other.id AS id ORDER BY id

Go 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:

go
// 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
<?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
<?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
<?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 ​

sql
-- 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 data

Neo4j 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 ​

text
// 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
sql
-- 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 ​

text
// 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
sql
-- 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.

sql
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
OptionGood forLimit
Adjacency list (parent_id) + recursive CTEAny depth, easy writesEach level is a join
ltree materialised pathSubtree and ancestor queries with one indexed operatorOne parent per node; moving a subtree rewrites paths
Closure tableFast ancestor/descendant, any DAGQuadratic rows in the worst case
Nested setRead-heavy fixed treesExpensive writes
Graph databaseMany relationship types, DAGs and cyclesA second system

Apache AGE: Cypher inside PostgreSQL ​

sql
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 caseWhy a graph fitsTypical patternProducts used in practice
Social networksFriends-of-friends, mutual follows, feeds from the neighbourhood(u)-[:FOLLOWS*1..2]->()Neo4j, Memgraph, TigerGraph
Fraud ringsShared devices, cards, addresses link accountsShared-identifier pattern, community detectionNeo4j, TigerGraph, Neptune
RecommendationsCo-purchase and similarity over multi-hop pathsCollaborative filtering patternNeo4j, Memgraph, Neptune
Knowledge graphsEntities and typed relationships from text and sourcesRDF or LPG, linked data, GraphRAGNeptune, Neo4j, GraphDB, Stardog
Dependency and impact analysisTransitive closure over services, packages, tablesDEPENDS_ON*Neo4j, AGE
Identity resolution and access graphsWho can reach what through groups and rolesReachability over MEMBER_OF, CAN edgesNeo4j, Neptune
Network and IT topologyPath, impact and root causeShortest path, centralityNeo4j, TigerGraph
Supply chain and routingPaths with costsDijkstra, A*Neo4j GDS, TigerGraph

When not to use one:

SituationUse insteadReason
Mostly tabular data with occasional single-hop joinsPostgreSQL with an indexNo new system to run
Whole-table aggregates and reportingPostgreSQL, a columnar engine; see OLTP vs OLAPGraph engines are not built for scans
Shallow bounded hierarchy (3 levels)Adjacency list, ltree, closure tableComplexity not justified
Key lookups at massive scale and simple access patternsRedis, DynamoDB, Cassandra; see Wide-Column & Key-ValuePartitionable by key
Write-heavy logs and time seriesA log store or time-series storeGraph writes are heavier
Search by textFull-Text SearchDifferent index structure
Embedding similarity onlyVector SearchGraph is optional
You cannot staff a second databaseApache AGE or recursive CTEsOperational cost

Choosing ​

What is the hot query?Relationship-shaped dataShallow, bounded tree(categories, org chart)Variable depth, data alreadyin PostgreSQL, moderate sizeDeep paths, many relationshiptypes, traversal is the coreAdjacency list or ltreeno new databaseRecursive CTE, or Apache AGEmeasure before adding a systemNeo4j, Memgraph, Neptune,TigerGraph, JanusGraph
WorkloadRecommendationExtra techniqueReason
Category tree, breadcrumbs, org chart under 10 levelsPostgreSQL adjacency list or ltreeIndex the parent and path columnsNothing a graph engine adds is needed
Friends within 2 to 3 hops on a mid-sized social tablePostgreSQL recursive CTE(follower_id, followee_id) primary key, depth boundMeasured on our lab at 3 to 11 ms
Deep or variable-depth paths over many edge typesNeo4j, Memgraph, Neptune or TigerGraphIndex the start property; profilePath patterns are the language
Fraud detection on a growing identity graphNeo4j or TigerGraph, fed by eventsCommunity detection, exclude supernodesAlgorithms and multi-hop reach
Standards-based knowledge sharing and reasoningRDF store with SPARQL (Neptune, GraphDB, Stardog, Jena)SHACL, ontologiesInterchange and inference
Graph already in Cassandra or HBaseJanusGraphMixed index on ElasticsearchReuses the backend
Want Cypher but only PostgreSQLApache AGEIndex label tablesOne database
Graph algorithms over a huge static graphNeptune Analytics, Neo4j GDS, TigerGraphProject and run in memoryWhole-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 ​

text
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 ​

LayerWhat happensMitigation
Neo4j secondaryRead may lag the writerBookmarks (drivers manage them in a session)
Neptune replicaReads from replicas see slightly stale dataRead from the primary for read-your-writes
Cache in front (Redis)Top-N results cached per userTTL, invalidate by event
PostgreSQL read replicaThe projection source lagsTreat the graph as eventually consistent; see Replication
Cross-regionA single writer regionRegional 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 ​

LoadDesignExample
1xRecursive CTEs and ltree in PostgreSQL100k users, 1M edges: 3 to 65 ms for 3 to 5 hops on a laptop
10xAdd the right composite index, depth bound and CYCLE; or add Neo4j or AGE for the hot query; cache top-N1M users: a projection graph in Neo4j
100xNeo4j cluster with secondaries or Neptune with up to 15 replicas; per-tenant graphs; GDS for batch scores; precomputeFraud 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.

bash
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"
sql
-- 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 rows

Export the exact same graph and load it into Neo4j:

bash
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
text
// 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;     // 999945

Experiment 1: friends of friends, depth 3, 4, 5 in PostgreSQL.

text
\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.

text
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 ​

BeliefReality
Graph databases are always faster than SQLFaster 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 indexesYou still index the starting nodes; only hops avoid the index
Recursive CTEs cannot do graphsThey can, if bounded and cycle-safe; they just have no graph-native planner
GraphQL needs a graph databaseGraphQL is an API layer over any store
A graph database scales out like CassandraGraphs have no natural partition key; edge cuts cost network hops
Property graph and RDF are the sameDifferent models: RDF has global identifiers, reasoning and no native edge properties
Cypher and Gremlin are interchangeableDeclarative pattern vs traversal steps, with different product support
Graph databases have no transactionsNeo4j, Memgraph and others are ACID; JanusGraph follows its backend
Schemaless means no modelingThe model decides query cost; poor modeling is the main failure
You can parameterise any part of a Cypher queryNot the variable-length bound in Cypher 5 (*1..$d fails); validate and format an integer
A graph database replaces my relational databaseIt is usually a projection or a specialised store beside the system of record

Cheat sheet ​

TopicWhat to remember
ModelLabeled property graph: nodes with labels, relationships with one type, direction and properties
RDFTriples with IRIs, queried with SPARQL; no native edge properties
Index-free adjacencyHops follow pointers; the start node still needs an index
Native vs non-nativeNative: Neo4j, Memgraph, TigerGraph; non-native: JanusGraph, Apache AGE
Recursive SQLWITH RECURSIVE plus depth bound, UNION or CYCLE clause
CypherMATCH (a)-[:T*1..3]->(b) or -[:T]->{1,3}; MERGE is idempotent
GQLISO/IEC 39075:2024, Cypher-aligned
Gremling.V().repeat(out()).times(n); TinkerPop; JanusGraph, Neptune
Neo4jStore files, page cache (server.memory.pagecache.size), transaction log, primaries and secondaries
AlgorithmsGDS: project, then PageRank, Louvain, betweenness, Dijkstra
ModelingNouns to nodes, verbs to relationships, hyperedge to a node, time on the edge
SupernodesFilter by type and direction, bucket, exclude
ShardingEdge cuts make traversals cross the network; prefer vertical scale, replicas, per-tenant graphs
DriversGo neo4j-go-driver/v6, PHP laudis/neo4j-php-client; transaction functions are retried, keep them idempotent
DecisionStart with PostgreSQL; move when the hot query is a deep path and you have measured

Self-check: questions & answers ​

Show:
  • 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 ​

TermMeaning
Graph databaseA 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
LabelA tag on a node, such as :User
Relationship typeThe single name of an edge, such as FOLLOWS
PropertyA key/value on a node or relationship
RDFResource Description Framework: data as subject-predicate-object triples
Triple / quadA statement; a quad adds the named graph
IRIGlobal identifier used in RDF
SPARQLThe W3C query language for RDF
Property pathA SPARQL pattern for repeated predicates, such as foaf:knows+
Reification / RDF-starWays to attach data to an RDF statement
Index-free adjacencyA node holds direct references to its neighbours or relationships
Native graph storageStorage designed for graphs (Neo4j, Memgraph, TigerGraph)
Non-native graphA graph layer over another store (JanusGraph, Apache AGE)
TraversalWalking the graph from a starting node along relationships
HopOne relationship step
Variable-length pathA pattern with a hop range, *1..3
Quantified path patternGQL/Cypher 25 form of a variable-length path, {1,3}
Recursive CTEWITH RECURSIVE query that feeds its output back until no new rows
CYCLE clausePostgreSQL 14+ syntax that marks revisited values in a recursive query
CypherNeo4j's declarative graph query language
openCypherOpen specification of Cypher
GQLGraph Query Language, ISO/IEC 39075:2024
SQL/PGQProperty Graph Queries, SQL:2023 Part 16
GremlinApache TinkerPop's traversal language
Apache TinkerPopVendor-neutral graph computing framework and Gremlin
Gremlin ServerThe server that executes Gremlin traversals
GSQLTigerGraph's query language
BoltNeo4j's binary client protocol (bolt://, neo4j://)
MERGECypher clause: match or create; idempotent writes
Transaction functionA driver callback that is committed or retried automatically
BookmarkToken that lets a cluster route a read after a given transaction (causal consistency)
Page cacheNeo4j's memory cache of store files and indexes
Store format (aligned, block)How Neo4j lays out data on disk
Primary / secondaryNeo4j database roles: transaction processing vs read scale
RaftConsensus protocol used among primaries
Causal consistencyA client always reads at least its own writes
Supernode (dense node)A node with a huge number of relationships
Edge cutEdges crossing a partition boundary when a graph is split
HyperedgeA relationship connecting more than two nodes
Reified relationshipA relationship turned into a node so it can carry its own relationships
GDS (Graph Data Science)Neo4j's library for graph algorithms
Graph projection / catalogThe named in-memory graph GDS algorithms run on
PageRankCentrality by incoming links weighted by the importance of linkers
Betweenness centralityHow often a node lies on shortest paths between others
LouvainCommunity detection by modularity optimisation
Shortest path / DijkstraFewest hops or lowest cost route
Weakly connected componentsGroups of nodes connected ignoring direction
Fraud ringA group of accounts linked by shared identifiers
Knowledge graphA graph of entities and typed relations, often RDF or LPG
ltreePostgreSQL extension for label-path hierarchies
Adjacency list / closure tableRelational encodings of trees and DAGs
Apache AGEPostgreSQL extension adding openCypher and agtype
agtypeAGE's JSON-like result type
$graphLookupMongoDB aggregation stage for recursive reference lookups
GraphQLAn API query language; not a database
neo4j-go-driverNeo4j's official Go driver (github.com/neo4j/neo4j-go-driver/v6)
laudis/neo4j-php-clientCommunity PHP Bolt client for Neo4j

References ​

Built by Morteza Negahi