Skip to content

Graph Databases

Intermediate 48 min read Part 5 of 18

Graph databases model data as nodes and edges: property graphs vs RDF, index-free adjacency, Cypher/Gremlin/SPARQL/GQL, partitioning, and TAO-style scale.

Summary#

A graph database stores data as nodes (entities such as people, products and accounts), edges (relationships such as FOLLOWS, BOUGHT or TRANSFERRED_TO) and properties (key-value attributes on both). Relationships are stored as first-class records. That makes questions like these fast and natural to express, where they'd otherwise be long chains of SQL joins:

  • "friends of my friends who live in Berlin";
  • "the shortest path from this account to a known fraudster";
  • "products bought by people who bought this".

There are two main data models:

  • Property graphs: Neo4j, Amazon Neptune, JanusGraph, TigerGraph, Memgraph. They're queried with Cypher, Gremlin or the new ISO standard GQL.
  • RDF triple stores: subject-predicate-object statements with global identifiers, queried with SPARQL. These are common in knowledge graphs and the semantic web.

Native engines use index-free adjacency: each node physically points to its relationships, so a hop costs time proportional to that node's degree, not to the size of the whole database.

Graphs are hard to partition. Real graphs are highly connected with power-law degree distributions, so any split cuts many edges, and supernodes (a celebrity with 100 million followers) overload whichever machine holds them. That's why the world's largest social graphs often don't run on graph databases. Facebook serves its social graph through TAO, a graph-shaped cache and API over sharded MySQL. Twitter built FlockDB, a simple edge store on sharded MySQL, and LinkedIn built its own in-house graph systems instead of adopting an off-the-shelf graph database.

In interviews, the default is that relational or key-value stores handle most "graph-ish" data, meaning one or two hops with known access patterns. Reach for a graph database when deep, variable-length traversals, path finding or pattern matching are the core workload: fraud rings, recommendations by multi-hop similarity, network and IT dependency analysis, knowledge graphs, and access-control graphs. Name a concrete engine for it: Neo4j, Neptune, JanusGraph or Dgraph.

Why It Exists#

Relational databases handle relationships through foreign keys and joins. That works beautifully for one or two hops: "orders for this customer", or "posts by the people I follow". Some questions, though, are inherently about paths:

  • Social: "people within 3 hops of me who work at Acme"; "how am I connected to this person?" (LinkedIn's "2nd/3rd-degree connection").
  • Fraud: "accounts that share a device, phone number or card with any account linked to a known fraud case, up to 4 hops away". Fraud rings are dense subgraphs that look innocent row by row.
  • Recommendations: "products bought by users who bought what I bought, weighted by how recently".
  • Network and dependency analysis: "if this router or microservice fails, which customer services are affected, transitively?"
  • Knowledge graphs: "drugs that target proteins associated with this disease". The interesting answers are chains of typed relationships.
  • Authorization: "can user U read document D?" when permission comes through nested groups, folders, and shared links, as in Google's Zanzibar-style systems.

In SQL, each hop is another self-join on an edges table. "Exactly 3 hops" is three joins. "Up to N hops" needs a recursive CTE. The intermediate results grow multiplicatively. The query planner must evaluate a join for each hop, using index lookups that each cost O(log n) in the size of the whole edges table. The SQL is also awkward to write and read.

A graph database makes the relationship itself a stored, navigable object. Each node "knows" its neighbours, so walking from a node to its neighbours means following pointers, not searching an index. The cost of a traversal then depends on how much of the graph you touch, not on how big the whole graph is.

The model also brings schema flexibility. Adding a new relationship type (say, MENTORED) means creating edges with a new label, with no join table to design and migrate. That suits domains where the relationship types keep evolving, like knowledge graphs and master-data management.

The honest counterpoint matters just as much. Graph databases are a frequent interview over-engineering trap. Most applications' relationship queries are shallow and predictable. A table follows(follower_id, followee_id) with indexes on both columns, sharded by user, serves "who do I follow" and "who follows me" at enormous scale. Facebook's social graph, the largest in the world, lives in MySQL behind TAO. Choose a graph database because the queries are graph-shaped and deep, not because the data has relationships. All data has relationships.

How It Works#

The building blocks: nodes, edges and properties#

Every graph model has three ingredients:

  • Nodes (vertices) are the entities: a Person, a Company, an Account, a Device. In property graphs a node carries one or more labels (types) and a set of properties: {name: "Ana", city: "Berlin"}.

  • Edges (relationships) connect two nodes. In property graphs they are:

    • directed (from a start node to an end node; queries can ignore direction);
    • typed (FOLLOWS, WORKS_AT, TRANSFERRED_TO);
    • able to carry properties of their own ({since: 2019, weight: 0.8}, or a transfer's amount and timestamp).

    Edge properties are a major modelling convenience: the relationship itself holds data, without an extra join table.

  • Properties are key-value pairs on nodes and edges, and can be indexed for entry-point lookups, such as finding the node with email = 'ana@example.com'.

A typical query on this graph reads naturally: "products bought by people Ana follows, or by people they follow, that Ana hasn't bought" returns the rain jacket. It's a 2–3 hop pattern match.

Modelling choices that matter:

  • Node or property? If you'll traverse through a value ("people in the same city as me"), make it a node ((:City {name: "Berlin"})), so the traversal follows edges instead of scanning a property. If it's only displayed or filtered at the end, keep it as a property.
  • Edge or node? A relationship with rich data and its own relationships (a Transaction involving several accounts, a device and a merchant) should usually become a node (sometimes called reification, or an intermediate node). Edges connect exactly two nodes.
  • Edge direction. Store each relationship once with a meaningful direction ((a)-[:FOLLOWS]->(b)). Queries can traverse either way, and native engines keep both incoming and outgoing chains, so there's no need for duplicate reverse edges.
  • Fine-grained edge types. (:Person)-[:LIVES_IN]->(:City) beats a generic RELATED_TO {type: 'lives_in'}, because engines group a node's relationships by type and direction. Typed edges let the engine skip irrelevant ones, which matters for nodes with millions of edges.

Two data models: property graph vs RDF triples#

The labelled property graph (LPG) is what's described above: nodes and edges with labels and arbitrary properties. It's the model of Neo4j, Neptune (property-graph mode), JanusGraph, TigerGraph, Memgraph, ArangoDB, and the GQL standard. It's application-oriented: it feels like objects with pointers.

RDF (Resource Description Framework) is a W3C standard from the semantic web. Everything is a triple: subject → predicate → object.

<https://ex.org/person/ana>   <https://schema.org/name>      "Ana" .
<https://ex.org/person/ana>   <https://ex.org/vocab/follows> <https://ex.org/person/ben> .
<https://ex.org/person/ana>   <https://schema.org/worksFor>  <https://ex.org/org/acme> .
<https://ex.org/org/acme>     <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <https://schema.org/Organization> .

Key RDF ideas:

  • Global identifiers (IRIs). Every node and predicate is a URI, so datasets from different organisations can be merged just by unioning their triples. That's the foundation of linked open data: DBpedia and Wikidata export RDF, and schema.org vocabularies are RDF-based.
  • A property is just another triple. name "Ana" is a triple whose object is a literal. There's no separate "property" concept.
  • Edge properties need extra machinery. To say "Ana follows Ben since 2019" you need reification: a statement node with four triples, named graphs, or the newer RDF-star / RDF 1.2 quoted triples (<< :ana :follows :ben >> :since 2019). This is where LPGs are more convenient.
  • Ontologies and reasoning. RDFS and OWL let you declare classes, subclass hierarchies, domains and ranges, and logical rules. A reasoner can then infer new triples: if :Engineer rdfs:subClassOf :Employee and Ana is an Engineer, then Ana is an Employee. Validation shapes (SHACL) constrain data quality.
  • Storage. Triple stores (Virtuoso, GraphDB from Ontotext, Stardog, Apache Jena, Amazon Neptune in RDF mode, Blazegraph, which underpinned the Wikidata Query Service) index triples in several permutations, such as SPO, POS and OSP. Any pattern with one or two bound positions is then a range scan.
AspectLabelled property graphRDF triple store
UnitNodes and edges with property mapsTriples (subject, predicate, object)
IdentityInternal ids; application keys as propertiesGlobal IRIs; designed for merging datasets
Edge propertiesNativeNeeds reification, named graphs or RDF-star
SchemaOptional, usually app-definedOntologies (RDFS/OWL), SHACL; inference
Query languageCypher, Gremlin, GQLSPARQL
Typical useApplication data: social, fraud, recommendations, IT opsKnowledge graphs, data integration, life sciences, publishing, government open data
EnginesNeo4j, Neptune, JanusGraph, TigerGraph, MemgraphVirtuoso, GraphDB, Stardog, Jena, Neptune (RDF)

Rule of thumb:

  • Choose an LPG when you build an application over connected data, and want an intuitive model with edge properties and fast traversals.
  • Choose RDF when you must integrate and reason over data from many sources with shared vocabularies, need standards-based interchange, or rely on ontological inference.

Many enterprise "knowledge graphs" are RDF. Most product backends that use a graph database are LPG.

Native graph storage and index-free adjacency#

Index-free adjacency means that every node directly references its adjacent relationships, and every relationship directly references its two nodes, through physical pointers (record offsets or ids that map to fixed-size slots). Getting a node's neighbours doesn't consult a global index: you jump straight from the node record to its relationship chain.

The classic Neo4j record store, as described in Graph Databases (Robinson, Webber and Eifrem, O'Reilly), illustrates this:

  • Node store. Fixed-size records, about 15 bytes in the classic format. A node's id is its record offset (id × record size). Each record holds a pointer to the node's first relationship, a pointer to its first property, and label information.

  • Relationship store. Fixed-size records, about 34 bytes. Each holds the start and end node ids, the relationship type, and four pointers:

    • the previous and next relationship of the start node;
    • the previous and next relationship of the end node;
    • a pointer to its first property.

    Each node's relationships thus form a doubly linked list threaded through the relationship records.

  • Property store. Linked property records, with small values inline and large strings and arrays in separate dynamic stores.

  • Relationship groups. For dense nodes (above a threshold, around 50 relationships by default), relationships are grouped by type and direction. A traversal of FOLLOWS outgoing then skips millions of LIKES incoming.

The cost of one hop under this design:

  1. Read the node record: offset arithmetic, O(1).
  2. Walk its relationship chain, filtering by type and direction: O(degree), or O(degree of that type) with relationship groups.
  3. For each relationship, read the other node's record: O(1) each.

A k-hop traversal therefore costs time proportional to the number of nodes and edges visited, independent of the total graph size. A 3-hop query touching 10,000 edges takes about the same time whether the database has 1 million or 1 billion nodes, as long as the touched records are in the page cache.

Compare a relational join on a follows(follower_id, followee_id) table with a B-tree index:

  • each lookup of "who does X follow" is an index seek, O(log n) in the size of the whole table, typically 3–4 page reads, usually cached;
  • a k-hop expansion performs one seek per frontier node per hop.

In practice, a good relational engine with cached indexes isn't dramatically slower per hop for shallow queries: log n with a high fan-out B-tree is a small constant. The gap appears in three places:

  • Deep, variable-length traversals, where the planner can't predict the result size and executes generic joins or recursive CTEs with large intermediate sets.
  • Pattern matching across many relationship types, where every hop is a different join.
  • Path-specific operations (shortest path, "all paths up to length 5", cycle detection) that SQL lacks as built-ins and must emulate.

Index-free adjacency has costs too:

  • Random access. Pointer chasing jumps around the store, which is great when it's in RAM and painful from disk. Graph databases want a working set that fits in memory: Neo4j's page cache is typically sized to hold the store files.
  • Hard to distribute. Physical pointers assume the neighbour lives in the same store. Once neighbours are on other machines, every hop may be a network round trip. That's the root of the partitioning problem, covered below.
  • Write cost. Adding a relationship updates both nodes' chains, with locking on both nodes. Dense nodes become lock hotspots.

Newer Neo4j versions introduced a block format that co-locates a node's properties and small relationship sets in blocks, to reduce pointer chasing. The principle stays the same: neighbours are reached by direct reference.

Non-native graph storage#

Many graph databases store the graph in a general-purpose key-value or wide-column store, and build the graph model on top:

  • JanusGraph (a Linux Foundation project forked from Titan in 2017) stores each vertex as a row in Cassandra, ScyllaDB, HBase or Google Bigtable. The row key is the vertex id, and the columns are the vertex's properties and its edges, each edge stored as a column sorted by label, direction and sort key. Fetching a vertex's adjacency list is a single-row (or slice) read, a form of adjacency without a global index, inherited from the wide-column layout. Global property lookups use an external index backend: Elasticsearch, Solr or Lucene. Vertex-centric indexes sort a vertex's edges by an edge property, so "Ben's 10 most recent follows" is a range read inside one row.
  • Dgraph stores data as posting lists keyed by (predicate, subject). For example, the key <follows, ana> holds the sorted list [ben, …]. They live in its Badger LSM key-value store and are sharded by predicate. A query asking for follows of a set of nodes hits the group that owns follows and gets all the lists in one request, which is efficient for wide, shallow expansions.
  • Amazon Neptune uses a purpose-built engine on a distributed, quorum-replicated storage layer in the style of Aurora. Indexes cover the combinations of subject, predicate, object and graph.
  • Relational adjacency tables, such as edges(src, type, dst, props) with indexes on (src, type) and (dst, type), are how Facebook (TAO on MySQL) and Twitter (FlockDB on MySQL) stored their graphs. Apache AGE adds openCypher to PostgreSQL on top of tables, and SQL:2023 added property-graph queries (SQL/PGQ) over ordinary tables.

Native or non-native?

  • Native stores win on single-machine traversal latency for deep queries.
  • Non-native stores win on horizontal scalability, durability and operational familiarity, since they inherit Cassandra's or HBase's sharding, replication and multi-DC support. They pay roughly one key-value read per vertex expansion, with batching.

For many production graphs (billions of edges, shallow queries, huge write rates), non-native designs are what's actually deployed.

Query languages: Cypher, Gremlin, SPARQL and GQL#

Cypher is declarative pattern matching with ASCII-art syntax. Created by Neo4j, it was opened as openCypher and is supported by Neptune, Memgraph, Apache AGE, RedisGraph's successors and others. You draw the pattern: (node)-[:REL]->(node).

// Friends-of-friends of Ana who work at Acme, excluding existing friends
MATCH (me:Person {email: 'ana@example.com'})-[:FOLLOWS]->(f)-[:FOLLOWS]->(fof:Person)
WHERE (fof)-[:WORKS_AT]->(:Company {name: 'Acme'})
  AND NOT (me)-[:FOLLOWS]->(fof) AND fof <> me
RETURN fof.name, count(DISTINCT f) AS mutuals
ORDER BY mutuals DESC LIMIT 10;
 
// Variable-length path and shortest path
MATCH p = shortestPath((a:Account {id: $suspect})-[:SHARES_DEVICE|SHARES_CARD*..4]-(b:Account {flagged: true}))
RETURN p;

The *..4 means "1 to 4 hops", a variable-length traversal that would be a recursive CTE in SQL.

Gremlin is the imperative or functional traversal language of Apache TinkerPop. It's supported by JanusGraph, Neptune, Azure Cosmos DB (Gremlin API), HugeGraph and others. You describe steps a traverser takes:

// Same friends-of-friends query in Gremlin
g.V().has('Person','email','ana@example.com').as('me').
  out('FOLLOWS').aggregate('friends').
  out('FOLLOWS').hasLabel('Person').
  where(neq('me')).where(without('friends')).
  where(out('WORKS_AT').has('Company','name','Acme')).
  groupCount().by('name').
  order(local).by(values, desc).limit(local, 10)

Gremlin is very expressive and portable across TinkerPop engines. It reads like code, with explicit traversal order, which some find harder to optimise and maintain than declarative patterns. TinkerPop also defines a vendor-neutral server protocol (Gremlin Server), and the graph-computer API for OLAP traversals.

SPARQL is the W3C query language for RDF. Queries are triple patterns with variables, joined on shared variables:

PREFIX ex: <https://ex.org/vocab/>
PREFIX schema: <https://schema.org/>
SELECT ?fofName (COUNT(DISTINCT ?f) AS ?mutuals) WHERE {
  ?me schema:email "ana@example.com" ;
      ex:follows ?f .
  ?f  ex:follows ?fof .
  ?fof schema:worksFor ?org ; schema:name ?fofName .
  ?org schema:name "Acme" .
  FILTER (?fof != ?me)
  FILTER NOT EXISTS { ?me ex:follows ?fof }
}
GROUP BY ?fofName ORDER BY DESC(?mutuals) LIMIT 10

SPARQL also supports property paths (ex:follows+ for one-or-more hops), federated queries across endpoints (SERVICE), and inference-aware querying when the store runs a reasoner.

GQL (Graph Query Language) is the first new ISO database language standard since SQL, published in 2024 as ISO/IEC 39075. Its syntax draws heavily on Cypher, along with Oracle's PGQL and others. Alongside it, SQL/PGQ (Part 16 of SQL:2023) lets you define a property graph over existing relational tables and query it with GRAPH_TABLE (... MATCH ...) inside SQL. Vendors are converging on GQL: Neo4j's Cypher is evolving toward GQL conformance, and Google's Spanner Graph supports GQL. In the long run, "which graph language" becomes less of a lock-in question.

LanguageStyleData modelStrengthsWhere
Cypher / openCypherDeclarative patternsProperty graphReadable; optimiser chooses plan; huge ecosystemNeo4j, Neptune, Memgraph, AGE
GremlinImperative traversal stepsProperty graphPortable across TinkerPop engines; fine controlJanusGraph, Neptune, Cosmos DB
SPARQLDeclarative triple patternsRDFStandards; federation; reasoning; property pathsVirtuoso, GraphDB, Stardog, Neptune
GQL (ISO 39075)Declarative patterns (Cypher-like)Property graphVendor-neutral standardEmerging: Neo4j, Spanner Graph, others
SQL/PGQGraph patterns inside SQLGraph view over tablesNo data migration; joins with relational dataEmerging in relational engines
DQL / GraphQLNested field selectionDgraph's graphNatural for API responsesDgraph

Don't confuse GraphQL (an API query language for fetching nested JSON from any backend) with graph database languages. A GraphQL API often sits in front of SQL. Dgraph is unusual in supporting GraphQL natively as its database interface. See the API design pages for GraphQL itself.

Traversals vs relational joins, concretely#

Take a social graph of 100 million users with an average of 300 follows each: 30 billion edges. In SQL:

-- follows(follower_id BIGINT, followee_id BIGINT, created_at TIMESTAMP)
-- PRIMARY KEY (follower_id, followee_id), INDEX (followee_id, follower_id)
 
-- 2 hops: friends-of-friends of user 42, ranked by mutual count
SELECT f2.followee_id AS candidate, COUNT(*) AS mutuals
FROM follows f1
JOIN follows f2 ON f2.follower_id = f1.followee_id
WHERE f1.follower_id = 42
  AND f2.followee_id <> 42
  AND f2.followee_id NOT IN (SELECT followee_id FROM follows WHERE follower_id = 42)
GROUP BY f2.followee_id ORDER BY mutuals DESC LIMIT 10;
 
-- Up to N hops needs a recursive CTE (degrees of separation)
WITH RECURSIVE reach(user_id, depth) AS (
  SELECT followee_id, 1 FROM follows WHERE follower_id = 42
  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 user_id, MIN(depth) FROM reach GROUP BY user_id;

The arithmetic is what really matters. With an average out-degree of 300:

HopFrontier sizeNotes
1300user 42's follows
2300 × 300 = 90,000edge visits (fewer distinct nodes due to overlap)
327,000,000most of a city's population
48.1 billionexceeds the whole graph: everything is reachable ("six degrees")

Some of this explosion is the same for any engine. A graph database can't make a 3-hop full expansion cheap, because 27 million edge visits are 27 million edge visits. The differences between engines are these:

  • The constant per edge. Pointer chasing in RAM costs about 100 ns per visit. A B-tree index seek per frontier node costs microseconds. On a 90,000-edge 2-hop query, that's roughly 10 ms against 100+ ms.
  • Planning. Graph engines are built for "expand, filter, expand" pipelines. Relational planners may choose hash joins over huge tables, or misestimate recursive cardinalities.
  • Path semantics. Shortest path, all simple paths, and cycle avoidance are built in.
  • Early termination. "Any path to a flagged account within 4 hops" can stop at the first hit. Bidirectional BFS meets in the middle and touches about 2 × 300² = 180k nodes instead of 300⁴.

The practical lesson, in both worlds, is to bound traversals: limit the depth, sample high-degree nodes, filter early, and precompute what's popular. "Friends-of-friends recommendations" at LinkedIn or Facebook scale aren't computed live from a full 2-hop expansion for every user on every page view. They're precomputed offline, or served from specialised indexes and caches.

Graph algorithms you should know#

Graph queries (OLTP: find this pattern near this node, now) differ from graph analytics (OLAP: compute something over the whole graph). Both use a small toolbox of algorithms.

Breadth-first search (BFS) and shortest paths.

  • BFS explores the graph level by level from a source. In an unweighted graph, the first time BFS reaches a node is via a shortest path. Keeping a previous pointer per node lets you reconstruct it. The cost is O(V + E) over the visited region.
  • Bidirectional BFS runs BFS from both source and target, alternating (usually expanding the smaller frontier), and stops when the frontiers meet. With branching factor b and distance d, the work falls from about b^d to 2·b^(d/2). For b = 300 and d = 4, that's from 8.1 billion to 180,000. It's the single most important optimisation for "how am I connected to X" queries.
  • Dijkstra's algorithm handles weighted edges such as distance, cost or latency. It uses a priority queue, and costs O((V + E) log V). A* adds a heuristic lower bound (straight-line distance in road networks) to guide the search toward the target. Road routing systems add preprocessing such as contraction hierarchies (Geisberger et al., 2008) to answer continental queries in milliseconds.
  • k-shortest paths and all simple paths up to length L are used in fraud and network analysis. The cost is exponential in L, so always bound L.

PageRank and centrality. PageRank ("The Anatomy of a Large-Scale Hypertextual Web Search Engine", Brin and Page, 1998) scores a node's importance as the stationary probability that a random surfer is on it. The surfer follows a random outgoing link with probability d (the damping factor, typically 0.85) and jumps to a random node with probability 1 − d:

PR(v) = (1 − d)/N + d · Σ_{u → v} PR(u) / outdeg(u)
iterate from PR = 1/N until changes < ε  (typically 20–50 iterations)
dangling nodes (no out-links) redistribute their rank uniformly

Each iteration is one pass over all edges, which makes PageRank a natural fit for bulk, parallel, vertex-centric computation.

  • Personalized PageRank restarts at a specific node (or set of nodes) instead of a uniform random node. It gives "importance relative to me", and is the basis of many "who to follow" and recommendation systems. Twitter's "WTF: The Who to Follow Service at Twitter" (Gupta et al., WWW 2013) described random-walk-based recommendations computed in memory on a single large server.
  • Other centralities:
    • degree (simple popularity);
    • betweenness, the fraction of shortest paths through a node, which finds brokers and bottlenecks and costs O(V·E) with Brandes' algorithm, so it's approximated on large graphs;
    • closeness;
    • eigenvector centrality.

Community detection finds densely connected groups:

  • Louvain ("Fast unfolding of communities in large networks", Blondel et al., 2008) greedily optimises modularity: the density of edges inside communities compared with a random graph with the same degrees. It moves nodes between communities and then collapses communities into super-nodes, repeating hierarchically. It's fast, and handles graphs with hundreds of millions of edges.
  • Leiden (Traag, Waltman and van Eck, 2019) fixes Louvain's tendency to produce badly connected communities, with guarantees that communities are connected.
  • Label propagation gives each node the most common label among its neighbours, iterated. It's near-linear time and trivially parallel, but non-deterministic.
  • Connected components (weakly and strongly connected) is the basic first step: "which accounts form an isolated cluster?" It's used in entity resolution and fraud-ring detection.
  • Triangle counting and the clustering coefficient measure how many of a node's neighbours are connected to each other. They're used for spam detection, since fake accounts tend to have low clustering, and as features for ML.

Similarity and link prediction:

  • Jaccard similarity of neighbour sets: "users who follow many of the same accounts".
  • Adamic-Adar weights common neighbours by inverse log degree, so a shared obscure friend counts more than a shared celebrity.
  • Node embeddings, such as node2vec ("node2vec: Scalable Feature Learning for Networks", Grover and Leskovec, KDD 2016), learned from random walks.
  • Graph neural networks. Pinterest's PinSage (Ying et al., KDD 2018) applied them to web-scale recommendation.

These embeddings feed straight into Vector Databases and Similarity Search for nearest-neighbour recommendations.

OLTP queries vs OLAP graph processing#

Graph OLTP is what graph databases optimise: start from a handful of nodes found through an index, explore locally, and return quickly. Concurrency is high and each query is small.

Graph OLAP runs algorithms over every vertex and edge. The canonical model is Google's Pregel ("Pregel: A System for Large-Scale Graph Processing", Malewicz et al., SIGMOD 2010): "think like a vertex", using bulk synchronous parallel (BSP) supersteps.

  1. In each superstep, every active vertex runs a user function. It reads the messages sent to it in the previous superstep, updates its value, and sends messages along its edges.
  2. A global barrier separates supersteps.
  3. Vertices vote to halt, and the computation ends when all are inactive and no messages are in flight.

PageRank in Pregel works like this:

  • each vertex sends PR/outdeg to its neighbours;
  • each vertex sums what it receives;
  • repeat for about 30 supersteps.

The open-source descendants include Apache Giraph (used at Facebook for trillion-edge computations, as described in its engineering posts), GraphX on Spark, and GraphFrames. PowerGraph (Gonzalez et al., OSDI 2012) introduced the gather-apply-scatter model and vertex-cut partitioning for power-law graphs. Many engines ship algorithm libraries: Neo4j Graph Data Science, Neptune Analytics, TigerGraph's GSQL library, and Memgraph's MAGE.

Keep the two workloads apart. Running PageRank over a billion-edge graph inside the OLTP database competes with user-facing queries for cache and CPU. The usual pattern:

  1. Export a snapshot to a batch system (Spark/GraphX, or an in-memory analytics engine).
  2. Compute.
  3. Write scores back as properties, or into a serving store.

That's the same separation as OLTP versus the data warehouse. See Batch vs Stream Processing.

Why partitioning graphs is hard#

Key-value and document data shard cleanly. Each record is independent, so hash the key and spread it out (Partitioning and Sharding). Graphs resist this because the value is in the connections. Any split cuts edges, and every cut edge turns a pointer dereference into a network hop.

Hash partitioning cuts almost everything. If vertices are assigned to k partitions uniformly at random, the probability that an edge's endpoints share a partition is 1/k. So the fraction of edges cut is 1 − 1/k: 90% with 10 machines, 99% with 100. A 3-hop traversal from one user becomes a cascade of cross-machine requests. Each hop's frontier fans out to nearly every partition, so latency is dominated by the network and by stragglers.

Real graphs make it worse.

  • Power-law degrees. A few nodes have enormous degree: celebrities, popular products, the "United States" node in a knowledge graph, a shared corporate Wi-Fi device in a fraud graph. These are supernodes.
  • Small-world structure. Most nodes are within a few hops of each other, so there are no clean "islands" to put on separate machines.
  • Evolution. The graph changes constantly, so a good partition today degrades tomorrow.

Supernodes cause trouble in three ways:

  1. Traversal blow-up. Touching a supernode in a 2-hop query expands into 100 million neighbours. Queries must skip, sample or cap high-degree nodes ("ignore nodes with degree above 10,000 in fraud traversals", or "use only the 1,000 most recent followers").
  2. Hot partitions. The machine holding the supernode's edges serves a disproportionate share of all traversals and writes. Every new follower of a celebrity updates the same adjacency list, which creates write contention and lock hotspots.
  3. Memory and storage imbalance. One adjacency list can be gigabytes.

Partitioning strategies:

  • Min-cut partitioning. METIS (Karypis and Kumar, 1998) uses multilevel coarsening, then partitioning, then refinement, to minimise cut edges subject to balanced sizes. It's excellent offline for static graphs (road networks, meshes), but expensive to recompute on billions of edges, and it decays as the graph evolves.
  • Streaming partitioners. LDG (Linear Deterministic Greedy, Stanton and Kliot, KDD 2012) and Fennel (Tsourakakis et al., WSDM 2014) assign each arriving vertex to the partition holding most of its neighbours, with a penalty for full partitions. They come close to offline quality in one pass.
  • Domain-aware keys. Partition by an attribute that correlates with connectivity:
    • country or region (friends cluster geographically, which is the primer's suggestion for social graphs);
    • tenant, in multi-tenant SaaS, where cross-tenant edges are rare;
    • company, for org charts. This is often the most effective strategy in practice.
  • Vertex-cut (edge partitioning). Instead of assigning vertices (cutting edges), assign edges to machines and replicate high-degree vertices wherever their edges live. PowerGraph showed that this balances power-law graphs far better. A supernode's 100M edges spread over 100 machines, with a mirror on each, synchronised per iteration.
  • Replication of hot read-mostly data. Copy small but heavily traversed subgraphs (taxonomies, reference data) to every partition.

Distributed traversal techniques:

  • Batch the frontier per partition. Send one request per partition per hop containing all frontier vertices on it, rather than one request per vertex. The primer's social-graph solution makes exactly this point: batch friend lookups to the same person server.
  • Push computation to the data. Ship the traversal step to the partition, so it filters and aggregates locally and returns only results, not raw adjacency lists.
  • Limit depth and fan-out.
  • Cache popular traversals and precompute expensive ones offline: "people you may know" candidates for every user, refreshed nightly.

This is why many web-scale companies deliberately choose shallow, well-defined graph APIs over sharded stores, rather than general-purpose distributed graph databases. If your product queries are "list my edges of type T, newest first" and "count my edges of type T", you can shard by source vertex and serve every query from one shard. That's precisely Facebook's choice with TAO.

Social graphs at scale: TAO-style caching over sharded SQL#

Facebook's TAO ("TAO: Facebook's Distributed Data Store for the Social Graph", Bronson et al., USENIX ATC 2013) is the canonical example of serving a massive graph without a graph database.

The data model is just two things:

  • Objects: typed nodes with an id and key-value data (users, posts, comments, pages, check-ins). The 64-bit id embeds a shard id.
  • Associations: typed, directed edges (id1, atype, id2) with a 32-bit time field and key-value data. Examples are (alice, LIKES, post42), (post42, LIKED_BY, alice) and (alice, FRIEND, bob). Many association types have an inverse type, which TAO writes alongside: liking a post writes both LIKES and LIKED_BY.

The API is deliberately small and graph-shaped:

obj_get(id) / obj_add / obj_update / obj_delete
assoc_add(id1, atype, id2, time, data)      assoc_delete(id1, atype, id2)
assoc_get(id1, atype, id2set, [t_low, t_high])
assoc_count(id1, atype)                     → e.g. number of likes on a post
assoc_range(id1, atype, pos, limit)         → newest-first edge list, paginated
assoc_time_range(id1, atype, high, low, limit)

Every query starts at one known node (id1) and reads that node's edge list of one type, sorted by time, newest first. There's no multi-hop query in the API. Multi-hop features (news feed, "friends who liked this") are composed in the application from many single-hop reads, all of which are cache hits.

The architecture:

  • Storage is MySQL, sharded into many logical shards. Objects live in their shard (by the id's embedded shard id). Associations live on the shard of id1, so one node's edge list of a type is one indexed range read on one shard.
  • Caching is a two-tier, graph-aware cache of TAO servers in front of MySQL:
    • Followers are many cache tiers, close to the web servers.
    • Leaders are one tier per region, which talks to the database.
    • Caches store objects, association lists and association counts, not opaque blobs. They understand the data model, so an assoc_add updates the cached list and count in place rather than invalidating it.
  • Regions. One region is the master for each shard, and others are slaves (replicas, in the paper's terms). Writes are forwarded to the shard's master leader and then to the master database. They're replicated asynchronously to the other regions' databases, and the replication stream drives cache invalidations there.
  • Consistency. TAO is eventually consistent across regions, with read-after-write consistency within a region for the writer: the follower that took the write updates its own cache. Rare critical reads can be marked to go to the master.
  • Scale. The paper reports TAO serving about a billion reads per second and millions of writes per second over a constantly changing graph of many petabytes. It's extremely read-heavy, with cache hit rates in the high 90s percent.

Lessons for system design:

  1. Model the graph, but constrain the queries to what shards and caches serve well: single-hop, typed and time-ordered edge lists.
  2. Co-locate a node's edges with the node (shard by id1), so the most common query touches one shard.
  3. Write both directions (an edge and its inverse) to serve "who I follow" and "who follows me" without cross-shard scans. Accept the small inconsistency window between them.
  4. Use a data-model-aware cache, not just a key-value cache, so writes update cached lists instead of invalidating hot keys.
  5. Handle supernodes in the application. A celebrity's follower list isn't fanned out on write. Counts come from assoc_count, and lists are paginated.

The same ideas appear in Twitter's FlockDB (an edge store on sharded MySQL for follower graphs, open-sourced in 2010), and in the primer's social-graph design: a lookup service maps person to shard, person servers hold friend lists, BFS runs in a graph service, results are cached, and BFS is bidirectional with depth limits. Design a Social Graph and Shortest-Path Search works through that design end to end, and Design a News Feed (Facebook / Twitter) shows how feed fan-out uses the follow graph.

The graph database landscape#

Graph systems fall into a few families. The family decides most of a system's behaviour, so learn the families first and the products second.

FamilyExamplesStorage ideaSweet spot
Native property-graph OLTPNeo4j, Memgraph, TigerGraphAdjacency stored as pointers or compact neighbour listsDeep, ad-hoc traversals on a graph that fits a few big machines
Graph layer over a distributed KV storeJanusGraph, Dgraph, NebulaGraph, Cosmos DB Gremlin APIEach vertex's edges are a row or posting list in a sharded KV storeVery large graphs, shallow traversals, high write volume
Managed multi-model / multi-APIAmazon Neptune, ArangoDB, Spanner GraphVaries: replicated storage with graph indexes, or documents plus edge collectionsTeams that want graph queries without running the infra
Relational with graph extensionsPostgreSQL plus Apache AGE, SQL/PGQ, recursive CTEsEdge tables plus B-tree indexesGraph-shaped queries that are occasional, shallow, or next to relational data
RDF triple storesOntotext GraphDB, Stardog, Virtuoso, Apache Jena, Neptune SPARQLTriples with SPO/POS/OSP permutation indexesKnowledge graphs, ontologies, data integration, inference
Graph analytics enginesNeo4j GDS, Spark GraphX/GraphFrames, Neptune Analytics, KùzuIn-memory or columnar CSR snapshotsWhole-graph algorithms: PageRank, communities, embeddings

Neo4j

Neo4j is the best-known native graph database.

  • Storage: the record-store layout described earlier (fixed-size node and relationship records, linked relationship chains), with a page cache that should hold the hot part of the store.
  • Query: Cypher, the language that seeded openCypher and later GQL.
  • Transactions: fully ACID, with a write-ahead log.
  • Clustering: in recent versions, primary servers replicate transactions using Raft, so a write commits once a majority of primaries have it. Secondaries replicate asynchronously and scale reads. Each database has one Raft leader for writes, so write throughput scales up, not out.
  • Sharding: Neo4j does not transparently shard a single graph. Fabric (4.x) and composite databases (5.x) let one Cypher query span several databases that you partition yourself, for example one per region or tenant.
  • Analytics: the Graph Data Science (GDS) library projects a subgraph into an in-memory format and runs 60+ algorithms (PageRank, Louvain, Leiden, node2vec, FastRP, similarity) whose results can be written back as properties.

Fits when the graph fits on one large machine (hundreds of millions to a few billion relationships), you need deep multi-hop queries with low latency, and the workload is read-heavy. Watch out for single-leader write throughput, supernodes, and memory: if the page cache can't hold the hot store, every pointer chase becomes a random disk read.

Amazon Neptune

Neptune is AWS's managed graph database.

  • Query: Gremlin, openCypher and SPARQL over the same service. Property-graph and RDF data are separate models, though.
  • Storage: a shared, distributed storage volume that keeps six copies of the data across three Availability Zones, the same design family as Aurora. Compute is decoupled from storage.
  • Replicas: one writer instance plus up to 15 read replicas sharing the same volume, so replica lag is typically small and failover promotes a replica.
  • Extras: Neptune Analytics, an in-memory engine for running algorithms and vector similarity over a loaded graph, and Neptune ML, which trains graph neural networks through SageMaker.

Fits when you're on AWS, want no operations work, and the writes fit a single writer. Watch out for the single-writer ceiling, and for the fact that the query planners for Gremlin and openCypher behave differently, so test your real queries.

JanusGraph

JanusGraph is an open-source fork of Titan, started in 2017 under the Linux Foundation. It is a graph layer, not a storage engine.

  • Storage backends: Apache Cassandra, ScyllaDB, Apache HBase, Google Bigtable, or embedded BerkeleyDB for small deployments.
  • Index backends: Elasticsearch, Solr or Lucene for full-text, geo and range queries on properties.
  • Query: Gremlin via Apache TinkerPop.
  • Layout: each vertex is a wide row. Its edges are columns sorted by edge label and sort key, which gives the vertex-centric index effect: "Alice's FOLLOWS edges created after date X" is a contiguous slice.

Fits when you already run Cassandra, HBase or Bigtable at scale and need a graph view over billions of edges with mostly shallow traversals. Watch out for operating three systems (graph servers, storage cluster, index cluster), eventual consistency inherited from the backend, and deep traversals that pay a network round trip per hop.

Dgraph

Dgraph is a distributed graph database written in Go.

  • Storage: Badger, its own LSM key-value store (Storage Engines: B-Trees vs LSM Trees).
  • Sharding by predicate: all edges of one predicate (say follows) are stored together as posting lists (the sorted list of target uids per source uid) and form a tablet. Tablets are assigned to groups, and each group is a Raft replica set. Predicates can be rebalanced between groups.
  • Query: DQL (formerly called GraphQL+-) and a native GraphQL endpoint generated from a schema.
  • Execution: a traversal along a predicate is one request to the group that owns it, which returns a whole posting list, so joins become sorted-list intersections, much like a search engine.

Fits when you want GraphQL-native APIs over a distributed graph with horizontal scale. Watch out for very large single predicates (one huge tablet) and the vendor's history: the company behind it has changed hands, so check the project's current status before betting on it.

Others worth knowing

  • TigerGraph: a native, distributed, MPP (massively parallel processing) graph engine with the GSQL language. Known for deep-link analytics, such as 10-hop fraud and supply-chain queries over sharded graphs.
  • Memgraph: an in-memory property-graph database in C++ that speaks Cypher and the Bolt protocol. Strong for streaming graph updates, for example from Kafka, with low-latency queries.
  • ArangoDB: multi-model: documents, key-value and graphs (edge collections) under one query language, AQL.
  • Azure Cosmos DB for Apache Gremlin: Gremlin over Cosmos DB's globally distributed, partitioned storage. You choose the partition key, and cross-partition traversals cost more request units.
  • NebulaGraph: a shared-nothing distributed graph with separate query, storage and meta services. It uses RocksDB storage, Raft replication and the nGQL language. Popular in China at very large scale.
  • Kùzu: an embedded, columnar graph database, "the DuckDB of graphs", using Cypher and worst-case optimal join techniques. It's aimed at analytics inside an application process.
  • Apache AGE: a PostgreSQL extension that adds openCypher queries over graph data stored in Postgres tables (PostgreSQL in Practice).
  • Spanner Graph: Google Cloud's graph support inside Spanner (announced 2024). It offers GQL-style queries over Spanner tables, with Spanner's global consistency.
  • RDF stores: Ontotext GraphDB, Stardog, OpenLink Virtuoso (it serves the public DBpedia endpoint) and Apache Jena (TDB storage plus the Fuseki server). They provide SPARQL, reasoning and SHACL validation.

Choosing a graph store#

Knowledge graphs and GraphRAG#

A knowledge graph stores facts about real-world entities and their relationships: "Marie Curie — won — Nobel Prize in Physics", "Nobel Prize in Physics — awarded by — Royal Swedish Academy of Sciences". Google introduced its Knowledge Graph in 2012 with the slogan "things, not strings". It powers the info panels next to search results (Design a Web Search Engine (Google Search)). Wikidata is a public knowledge graph with over 100 million items and a public SPARQL endpoint.

Building one is mostly a data integration problem, not a storage problem:

  1. Entity extraction: find mentions of things in text or tables.
  2. Entity resolution: decide that "IBM", "International Business Machines" and "Big Blue" are one node. This is the hardest part, using blocking, pairwise matching models and clustering.
  3. Relation extraction: identify facts connecting entities.
  4. Schema or ontology: define allowed types and relationships, so data from many sources agrees.
  5. Provenance and confidence: record which source asserted each fact, and how sure we are.

GraphRAG combines knowledge graphs with LLM retrieval-augmented generation (Designing LLM and AI-Powered Systems). Plain vector RAG retrieves text chunks that are similar to the question. That works badly for questions that need connecting facts across documents ("which suppliers of our top 5 products had safety incidents?") or global summaries ("what are the main themes in these 10,000 support tickets?"). Microsoft's paper "From Local to Global: A Graph RAG Approach to Query-Focused Summarization" (Edge et al., 2024) describes one approach:

  • An LLM extracts entities and relationships from every chunk, building a knowledge graph.
  • Leiden community detection groups the graph into hierarchical communities, and the LLM pre-summarises each community.
  • Global questions are answered by map-reducing over community summaries. Local questions start from entities matched in the query and expand to their neighbours, plus related chunks.

The trade-off is cost: extraction runs an LLM over the whole corpus, and re-indexing changing data is expensive. In practice teams combine both: vector search to find entry points, then a graph traversal of 1–2 hops to gather connected context. The same pattern drives agent memory stored as a graph of entities and facts that the agent updates over time (Vector Databases and Similarity Search).

When to Use It#

Reach for a graph database when the relationships are the query, not just a way to look up rows. Concrete signals:

  • Variable or deep path queries. "Is there a path of length 4 or less between these accounts?", "all transitive dependencies of this package", "shortest route through this network". In SQL these become recursive CTEs or N self-joins whose cost explodes. In a native graph each hop costs about the same as following a pointer.
  • Many-to-many relationships everywhere, with heterogeneous types. Examples are people, devices, IPs, cards and merchants in a fraud graph, or services, hosts, owners and incidents in an IT dependency graph. If you'd create 15 join tables, the domain is a graph.
  • Pattern matching. "Find rings where A pays B, B pays C and C pays A within 24 hours", or "two accounts sharing a device and a phone number". Graph pattern languages express these naturally.
  • The schema keeps evolving. New edge types appear often, and adding one shouldn't need a migration.
  • Graph algorithms are part of the product: recommendations from Personalized PageRank, community detection, centrality, influence scoring or entity resolution.
  • Knowledge graphs and linked data, where an ontology, inference and integrating many sources matter. Here RDF and SPARQL fit.

Pick something else instead when:

  • Queries are one hop. "List Alice's followers newest first" or "count likes on post 42" are perfectly served by a sharded relational or wide-column table indexed on (source, type, time), plus a cache. That's what Facebook (TAO on MySQL) and Twitter (FlockDB on MySQL) chose.
  • You need aggregates over whole tables: sums, group-bys and reports. A warehouse or columnar engine is far faster.
  • The graph is huge, the traversals are deep, and you need low latency. No system makes a 4-hop traversal over 100 billion edges fast. Precompute offline, bound the query, or rethink the feature.
  • The data is fundamentally documents or rows with a few references between them. Foreign keys and joins are fine.

When NOT to Use It#

  • In most system design interviews. Interviewers often view a graph database as a red flag unless the problem truly needs multi-hop traversals. Even "design a social network" is usually answered with sharded SQL or Cassandra for edges, plus caching. Say why you aren't using one: "follower lists are single-hop range reads, so a graph DB adds operational risk without benefit."
  • As your primary system of record for an extremely write-heavy workload that needs horizontal write scaling, such as 1 million edge inserts per second. Most native graphs have a single write leader per database.
  • When the team has no graph expertise and the graph features are speculative. A Postgres edge table with a recursive CTE gets you surprisingly far, and you can add a graph projection later (PostgreSQL in Practice).
  • For time-series, logs or full-text search. Use the purpose-built systems (Time-Series Databases, Elasticsearch and Search Systems).

How to Implement It#

A practical path from requirements to a running graph:

  1. List the questions first. Write the 5–10 traversals the product needs, with expected depth, fan-out and latency SLOs: "friends-of-friends not yet connected, top 20, p99 under 100 ms". Graph models are designed backwards from queries, just like NoSQL models (Data Modeling).
  2. Choose nodes and edges.
    • Nouns that you traverse through become nodes.
    • Verbs become typed, directed edges.
    • Attributes you only filter on become properties.
    • Promote a property to a node when you'll traverse via it: a City node, rather than city strings, if you ask "people in the same city as my friends".
    • Use intermediate nodes for n-ary relationships (an Order connecting customer, products and address), or when an edge needs its own relationships.
  3. Estimate size and degree distribution. Count nodes, edges, average and maximum degree, and growth per day. Identify likely supernodes and decide now how queries will treat them.
  4. Pick the store using the decision flow above. Pick the language (Cypher/GQL, Gremlin or SPARQL) to suit the team and tooling.
  5. Create constraints and indexes.
    • Use unique constraints on natural keys (User.id).
    • Index the entry-point lookups. A graph DB still needs an index to find the starting node; adjacency only helps after that.
    • Add vertex-centric or relationship-property indexes for selective edge filters.
  6. Load in bulk, then stream. Use the offline bulk importer for the initial graph (far faster than transactional inserts). Then keep it up to date through Change Data Capture and the Outbox Pattern from the system of record, and make writes idempotent with MERGE and upserts (Idempotency and Safe Retries).
  7. Bound every traversal. Set maximum depth, fan-out limits per hop, timeouts, and LIMIT. Skip or sample supernodes. Profile with EXPLAIN and PROFILE.
  8. Separate analytics from OLTP. Run PageRank and community detection on a replica or an exported snapshot. Write the results back as properties (pagerank, communityId) that online queries read.
  9. Plan scaling and HA. Use read replicas for read scale and a clustered leader for writes. Use domain partitioning (by tenant or region) if a single graph won't fit. Test failover, and keep backups with point-in-time restore.
  10. Monitor page-cache hit ratio, query p99 by query type, the longest-running traversals, replica lag, and the degree of the top nodes (Observability: Logs, Metrics and Traces).

A small fraud-detection model and queries in Cypher:

// Constraints: entry points must be indexed
CREATE CONSTRAINT user_id IF NOT EXISTS FOR (u:User) REQUIRE u.id IS UNIQUE;
CREATE CONSTRAINT device_id IF NOT EXISTS FOR (d:Device) REQUIRE d.id IS UNIQUE;
CREATE CONSTRAINT card_fp IF NOT EXISTS FOR (c:Card) REQUIRE c.fingerprint IS UNIQUE;
 
// Idempotent ingest of one login event (safe to retry)
MERGE (u:User {id: $userId})
MERGE (d:Device {id: $deviceId})
MERGE (u)-[r:USED]->(d)
  ON CREATE SET r.first = $ts
  SET r.last = $ts;
 
// Accounts linked to a flagged user through shared devices or cards,
// within 2 shared-identifier hops, skipping supernode devices
MATCH (bad:User {id: $flaggedId})
MATCH path = (bad)-[:USED|PAID_WITH*1..4]-(other:User)
WHERE other <> bad
  AND all(n IN nodes(path) WHERE NOT n:Device OR n.degree < 50)
RETURN other.id AS suspect, min(length(path)) AS hops
ORDER BY hops
LIMIT 100;
 
// Fraud ring: three users sharing one card fingerprint
MATCH (c:Card)<-[:PAID_WITH]-(u:User)
WITH c, collect(u) AS users
WHERE size(users) >= 3
RETURN c.fingerprint, [x IN users | x.id] AS ring;

The n.degree < 50 filter is the supernode guard. A device such as a shared café tablet, used by thousands of accounts, would otherwise link everyone to everyone. The degree property is maintained by the ingest pipeline or an analytics job.

TechnologyFits when
Neo4jDeep ad-hoc traversals and pattern matching on a graph that fits one large machine; rich tooling and GDS
Amazon NeptuneManaged on AWS; Gremlin, openCypher or SPARQL; read-heavy with a single writer
JanusGraphBillions of edges on an existing Cassandra, ScyllaDB, HBase or Bigtable estate; shallow traversals
DgraphDistributed graph with a native GraphQL API; predicate-sharded horizontal scale
TigerGraphDeep-link analytics (many hops) over large sharded graphs, using GSQL
MemgraphIn-memory, low latency, streaming updates from Kafka; Cypher compatible
PostgreSQL plus AGE, or recursive CTEsOccasional graph queries next to relational data; small teams; one database to run
Sharded MySQL or Cassandra plus a cacheWeb-scale social edges with single-hop list and count queries (TAO and FlockDB style)
RDF store (GraphDB, Stardog, Jena)Knowledge graphs, ontologies, inference, linked open data
Spark GraphX, Neo4j GDS, Neptune AnalyticsOffline whole-graph algorithms: PageRank, communities, embeddings

Trade-offs#

OptionProsConsPick when
Native graph DBConstant cost per hop; expressive pattern queries; flexible schemaHard to shard; single write leader; memory-hungry; smaller talent poolDeep or ad-hoc traversals over a graph that fits on one cluster
Graph layer on a distributed KV storeScales to tens of billions of edges; reuses an existing storage estateNetwork round trip per hop; eventual consistency; three systems to runHuge graphs with mostly 1–2 hop queries
Relational edge tablesOne system; ACID; SQL skills; joins fine at 1–2 hopsRecursive queries slow at depth; awkward pattern matchingGraph features are secondary or shallow
TAO-style sharded store plus cacheMassive read throughput; predictable latency; simple ops primitivesNo multi-hop queries; application composes traversals; eventual consistencySocial features at web scale
RDF triple storeStandards, global identifiers, inference, schema-free integrationVerbose; slower for property-heavy OLTP; reification overheadKnowledge graphs and data integration
Offline graph analyticsWhole-graph algorithms at any scaleResults are stale; batch latencyRecommendations, rankings and communities computed periodically

Common Pitfalls#

  • Unbounded variable-length patterns. [*] with no upper bound can explore the whole graph. Always cap the depth and LIMIT.
  • Supernodes. A query that wanders into a node with 10 million edges takes seconds or runs out of memory. Detect high-degree nodes, add degree properties, and filter or sample.
  • Missing entry-point indexes. Without an index on User.id, every query starts with a full node scan.
  • Modelling everything as nodes. Turning every attribute into a node bloats the graph and slows filters. Promote only what you traverse through.
  • Generic edge types. One RELATED_TO edge with a type property forces the engine to read and filter every edge. Specific edge types are stored and traversed separately.
  • Cartesian products from disconnected MATCH clauses, such as MATCH (a:User), (b:Product). Check EXPLAIN for them.
  • Running analytics on the OLTP primary. A PageRank run evicts the page cache and hurts production latency.
  • Assuming the graph DB is the source of truth for data also kept elsewhere, with no sync and no reconciliation. Treat it as a projection fed by CDC unless it truly owns the data.
  • Expecting cross-shard traversals to be fast in a distributed graph. The cost model is network hops, not pointers.
  • Choosing a graph DB for a one-hop problem, or because the domain "sounds like a graph".

Real-World Examples#

  • Facebook TAO serves the social graph (users, posts, likes, friendships) as objects and associations over sharded MySQL with a two-tier cache, at about a billion reads per second (Bronson et al., USENIX ATC 2013).
  • Twitter built FlockDB on sharded MySQL for follower edges. Its "Who to Follow" service ran Personalized PageRank-style random walks and SALSA over an in-memory graph on a single large server using the Cassovary library, and later moved real-time recommendations to GraphJet (Sharma et al., VLDB 2016) ("WTF: The Who to Follow Service at Twitter", Gupta et al., WWW 2013).
  • LinkedIn built in-house graph systems for its member graph, used for degree-of-connection badges ("2nd", "3rd") and "People You May Know".
  • Pinterest used PinSage (Ying et al., KDD 2018), a graph convolutional network over a pin–board graph with billions of nodes, for recommendations, trained on random-walk neighbourhoods.
  • Google's Knowledge Graph (2012) powers entity panels in search. Wikidata publishes an open knowledge graph through SPARQL.
  • Fraud detection in banking and e-commerce is a common production use of graph databases, linking accounts by shared devices, cards, addresses and IPs to expose rings.
  • Uber (according to its engineering blog) built a knowledge graph for food discovery in Uber Eats, linking dishes, cuisines and restaurants.

Case studies that use this pattern#

In the Interview#

Common follow-ups and crisp answers:

  • "How would you find degrees of separation between two users?" Use bidirectional BFS from both ends with a depth cap of about 3 per side, and batch frontier lookups per shard. Precompute or cache the results for frequent pairs. With an average degree of about 300, one-sided depth 6 is hopeless, but two depth-3 searches meet in the middle.
  • "Would you use Neo4j for Twitter's follower graph?" No. The core queries are single-hop lists and counts at enormous write volume. A sharded edge store plus cache fits. A graph engine might power offline "who to follow" computations.
  • "How do you shard a graph?" By source vertex, so that a node's out-edges are local. Store inverse edges sharded by target. For multi-hop, accept network hops, partition by locality (region or tenant) if possible, and use vertex-cut or replication for supernodes.
  • "How do you handle a celebrity with 100 million followers?" Never iterate all their edges online. Use counts from a counter, paginate lists, and use pull-based feed merging for celebrity posts. In traversals, skip or sample nodes above a degree threshold.
Deep Dive: TAO internals, consistency and what came afterShow

Why a graph-aware cache beats a generic cache. With memcache in front of MySQL, a like on a hot post would invalidate the cached list of likers. The next thousand readers would all miss and stampede the database (a thundering herd). TAO's caches store association lists and counts as data structures. When a follower cache receives assoc_add(alice, LIKES, post42), it forwards the write to the leader. When the write succeeds, the follower applies the change to its cached list and count in place, so no reader misses. The leader does the same for its copy. Other follower tiers in the region learn about the change through invalidation and refill messages sent by the leader.

Leaders as the per-shard serialisation point. Each shard has one leader cache per region, and every cache miss and write for that shard goes through it. This gives three benefits:

  • Request coalescing: many concurrent misses for the same list become one database query.
  • Write ordering: the leader serialises writes to a shard, so it can keep the cache consistent with the database.
  • Database protection: the database sees only the leader tier's traffic, which is a small fraction of total reads.

The paper also describes how hot objects are handled. Followers detect shards with high load and cache items client-side for a short time. "Alerting" the client about hot items lets it avoid sending every request for them to the same follower.

Cross-region replication. Each shard's master region owns writes. A write from a slave region is forwarded to the master region's leader, then applied to the master database, then replicated asynchronously (MySQL replication) to slave-region databases. Changes from the replication stream are delivered to the slave region's caches as invalidations. As a result:

  • A writer sees its own write in its region immediately, because its follower updated in place.
  • Other users in other regions may see the old value for a replication lag of typically seconds, longer during incidents.
  • Inverse edges are written as two separate operations, LIKES then LIKED_BY, with no atomicity across shards. A failure between them leaves a dangling half-edge, which is repaired by asynchronous jobs. Product code must tolerate this.

Failure handling. If a leader cache fails, followers route around it to the database directly or to another leader. If a master database fails, a slave is promoted, and the region's writes are rerouted. If a follower fails, clients use other followers. Throughout, TAO's design leans towards availability with eventual consistency: graph data is rarely money.

Later work on consistency. As more products needed stronger guarantees, Facebook published:

  • FlightTracker ("FlightTracker: Consistency across Read-Optimized Online Stores at Facebook", Shi et al., OSDI 2020). It provides read-your-writes across stores and regions by tracking a user's recent writes as a small "ticket" carried with the user's requests. Caches check the ticket and fetch fresher data when they're behind.
  • RAMP-TAO ("RAMP-TAO: Layering Atomic Transactions on Facebook's Online TAO Data Store", Cheng et al., VLDB 2021). It adds atomic visibility for multi-edge writes (both directions of an edge, or several edges in one product action) as a layer on top. It's based on RAMP (Read Atomic Multi-Partition) transactions (Bailis et al., SIGMOD 2014), and readers detect and repair fractured reads.

The lesson generalises beyond Facebook. Start with a simple, cacheable, eventually consistent primitive that matches 99% of queries. Then layer stronger guarantees only where products need them, rather than paying for distributed transactions on every write (Distributed Transactions: 2PC, Sagas and Outbox).

Capacity sketch. Suppose 1 billion reads per second at a 96% follower hit rate:

  • That's 40 million reads per second to leaders.
  • If leaders hit at about 90%, about 4 million queries per second reach MySQL across thousands of shards, or roughly a few thousand QPS per shard. That's well within an indexed MySQL range read's capacity.

The cache hierarchy is what makes a relational store survive graph read volumes.

Deep Dive: Query execution, cardinality and worst-case optimal joinsShow

How a Cypher query becomes a plan. Consider MATCH (a:User {id: 7})-[:FOLLOWS]->(b)-[:FOLLOWS]->(c) WHERE c.country = 'IN' RETURN c LIMIT 20. The planner chooses:

  1. Entry point: a NodeIndexSeek on User(id) for a, rather than a label scan.
  2. Expansion: an Expand(All) from a over FOLLOWS, which walks a's relationship chain, then a second Expand from each b.
  3. Filter: apply c.country = 'IN' after the second expansion. Alternatively, if an index on User(country) exists and is selective, the planner can seek both ends and join in the middle with a hash join on b.
  4. Limit: stop after 20 rows. Lazy, pull-based (Volcano-style) execution means early termination avoids work.

The choice between "expand from one side" and "seek both sides and join" depends on cardinality estimates: how many bs per a, how many cs match the filter. Graph planners face the same estimation problem as SQL planners, made worse by skew. The average out-degree may be 200, but Alice's is 2 million. Plans tuned for the average fail badly on supernodes, which is why production queries add explicit caps.

Why binary joins can be terrible for cyclic patterns. Take the triangle query: find all (a, b, c) with edges a→b, b→c and c→a. Over an edge relation E with N edges, a classical plan joins E with E on the middle vertex first. That intermediate result has size equal to the number of 2-paths, which is the sum over vertices of in-degree times out-degree. With one supernode of degree 1 million, that's on the order of 10^12 intermediate rows, even if there are few triangles. Every binary join order has this problem on some input.

The AGM bound. Atserias, Grohe and Marx ("Size Bounds and Query Plans for Relational Joins", FOCS 2008) showed that the maximum output size of a join query is bounded by N raised to the fractional edge cover number of the query hypergraph. For triangles that's N^1.5. Any binary-join plan can be forced to produce Θ(N^2) intermediate rows, so binary joins are asymptotically suboptimal for cyclic queries.

Worst-case optimal joins (WCOJ). Ngo, Porat, Ré and Rudra ("Worst-case Optimal Join Algorithms", PODS 2012) gave the first algorithm that runs in time matching the AGM bound. Leapfrog Triejoin (Veldhuizen, ICDT 2014, from LogicBlox) is a simpler, practical version. The idea is to join one variable at a time across all relations at once, not one relation at a time:

for a in intersect(E.src, E.dst):              // a must have out- and in-edges
  for b in intersect(out(a), E.src):           // a->b, and b has out-edges
    for c in intersect(out(b), in(a)):         // b->c and c->a: intersect sorted lists
      emit (a, b, c)

Each intersect over sorted neighbour lists costs proportional to the smaller list, not the product. This is the "leapfrog": iterators repeatedly seek to the maximum current key. Sorted adjacency lists, whether a CSR (compressed sparse row) array, a posting list or a B-tree, make it efficient.

Where WCOJ shows up:

  • Graph engines for cyclic pattern queries: Kùzu uses WCOJ-style multiway intersections, and the subgraph matching literature builds on it.
  • Datalog systems: LogicBlox.
  • Relational engines adopting it for cyclic joins: Freitag et al., "Adopting Worst-Case Optimal Joins in Relational Database Systems", VLDB 2020, in the Umbra system.
  • Dgraph's posting-list intersections are the same idea in a distributed setting.

Practical takeaway for designers. Acyclic paths (chains: friends of friends) are handled fine by expand-style plans with good entry points. Cyclic patterns (triangles, rings, "two users sharing both a device and a card") are where binary-join plans blow up and multiway intersection helps. If your workload is pattern-heavy, such as fraud rings, ask whether the engine does multiway intersection, and test on skewed data.

Worked numbers. Take a graph of 10 million edges where the top node has degree 500,000:

MeasureValue
Wedges through the top node alone500,000² = 2.5 × 10^11
AGM bound on triangles, N^1.5(10^7)^1.5 ≈ 3.2 × 10^10
WCOJ work at the top nodeProportional to the sum of smaller-list sizes per intersection, typically billions, not hundreds of billions

A two-orders-of-magnitude difference decides whether the query finishes in minutes or never.

Deep Dive: The math of distributed traversals and partitioningShow

Frontier growth. With average degree d, a breadth-first search touches about d^h vertices at depth h. These are upper bounds, because the overlap of friend circles (clustering) reduces the count in real social graphs. With d = 300:

SearchVertices touched
One-sided, depth 290,000
One-sided, depth 327 million
One-sided, depth 48.1 billion, effectively the whole graph
Bidirectional, two searches of depth 2 meeting in the middle (covers paths up to length 4)2 × 90,000 = 180,000
Bidirectional, depth 3 per side (covers paths up to length 6)2 × 27 million = 54 million: heavy, but feasible offline

That 45,000× reduction at depth 4 is why every degrees-of-separation design uses bidirectional BFS. Expanding the smaller frontier first at each step helps further, because the frontier sizes are often lopsided when one end is a celebrity.

Network cost per hop. Under hash partitioning over P machines, a frontier of F vertices maps to min(F, P) machines. With batching, each hop sends at most P requests, one per machine, each carrying that machine's share of the frontier. Without batching, it sends F requests. For F = 90,000 and P = 100, batching cuts 90,000 RPCs to 100. The bytes transferred are still proportional to the frontier's total adjacency size, so the real cost is bandwidth plus the slowest machine.

Tail latency compounds. If each per-machine request has a 1% chance of taking more than 50 ms, then a hop that waits on 100 machines hits at least one slow one with probability 1 − 0.99^100 ≈ 63%. A 3-hop query almost certainly sees the tail every time. Mitigations:

  • hedged requests: send a duplicate to a replica after a p95 delay;
  • partial results with deadlines, which are acceptable for "people you may know";
  • fewer, larger partitions for traversal-heavy workloads.

Dean and Barroso's "The Tail at Scale" (CACM 2013) formalises this effect.

Edge cut versus locality. Random hashing keeps only 1/P of edges local. Domain partitioning does much better when a fraction α of edges stays inside a partition. For example, if 80% of friendships are within the same country and partitions follow countries, α ≈ 0.8. Expected remote lookups per hop drop from (1 − 1/P) to (1 − α). For P = 100 that's from 99% of lookups remote to about 20%, which is roughly a 5× reduction in network traffic per hop. The cost is imbalance: big countries need sub-partitioning, and cross-border edges remain.

Vertex-cut replication factor. In a random vertex-cut over P machines, a vertex with degree D appears on about P × (1 − (1 − 1/P)^D) machines. Low-degree vertices (D ≪ P) appear on about D machines. Supernodes appear on nearly all P. PowerGraph's "greedy" placement lowers this by putting each edge where its endpoints already have replicas. The average replication factor determines memory overhead and the synchronisation cost per iteration of a Pregel or GAS (Gather-Apply-Scatter) computation.

Sizing the primer's social graph. Take the primer's figures: 100 million users with 50 friends each gives about 5 billion directed edges.

  • Memory. Stored as 8-byte neighbour ids, that's 40 GB of adjacency, or about 80 GB with reverse edges and overhead. A cluster of person servers with 64–128 GB each, or even a few large machines, can hold it entirely in memory, sharded by user id with a lookup service mapping user to server.
  • Load. 1 billion searches per month is about 400 searches per second on average. Each bidirectional depth-2-per-side search touches about 2 × 2,500 = 5,000 vertices (50² per side), which is about 2 million vertex lookups per second cluster-wide. That's comfortable with batching.
  • Peak. Plan for 3–5× the average at peak.
  • Caching. Cache popular pairs and the 2-hop neighbourhoods of very active users. Results can be stale by minutes without harming the product.

This back-of-the-envelope reasoning is exactly what an interviewer wants to see before you pick a graph database, or decide you don't need one.

Key Takeaways#

  • A graph database stores relationships as first-class data. Native engines use index-free adjacency, so each hop costs about the same regardless of graph size, while joins cost a logarithmic index lookup per row.
  • Property graphs (Neo4j, Neptune, JanusGraph) suit application data. RDF suits knowledge graphs and integration. Query them with Cypher/GQL, Gremlin or SPARQL. GQL (ISO, 2024) and SQL/PGQ (SQL:2023) are the new standards.
  • Graph databases shine for multi-hop, variable-length and pattern queries: fraud rings, dependencies, degrees of separation, recommendations. They're overkill for one-hop list and count queries, which a sharded table plus a cache serves better.
  • Partitioning graphs is fundamentally hard. Hashing cuts a 1 − 1/k fraction of edges, power-law degrees create supernodes, and every cut edge is a network hop. Use locality-based keys, vertex-cuts, replication and bounded traversals.
  • Bidirectional BFS with depth limits, batched frontier lookups per shard, caching and offline precompute make large social-graph traversals feasible.
  • Facebook TAO shows how to serve a massive graph without a graph DB: objects and associations, shard by source id, inverse edges, a graph-aware two-tier cache over MySQL, and eventual consistency, with stronger guarantees layered on later.
  • Keep OLTP traversals and OLAP algorithms (PageRank, Louvain/Leiden, embeddings) on separate infrastructure, using Pregel-style or in-memory analytics engines, and write the results back as properties.
  • In interviews, default to not using a graph database, justify it if you do, and always discuss supernodes, sharding and traversal limits.