Skip to content
Adrian Mircea Nenu computo, ergo sum
← Blog
databases software engineering

Building a Graph Database from Scratch in C++

In smollerGraph I build a graph database from scratch in C++, a small one that you can read, run and understand from one end to the other, with the focus on what happens behind the query, from how nodes and relationships are laid out on disk and how the database follows them from one to the next, to how a Cypher pattern becomes a plan that runs.

Why graphs

Graphs sit at the core of many of the problems we solve through engineering, from knowledge graphs for search and AI, healthcare, routes and maps, to file systems, distributed systems, the batch jobs and ETL loads of the enterprise and the entities in a game engine, and they matter a lot in cybersecurity too, where tools such as BloodHound find attack paths through an organisation's accounts and machines. Despite that, the inside of a graph database is something most of us never get to see, and I created this series because of my interest in complex software engineering at scale and the practices around it, after years in industry at Morgan Stanley and Google building large distributed systems, which rest on databases that most of us treat as black boxes, so I wanted a codebase small enough that you can follow a query all the way down to the bytes it reads.

Learning from Neo4j and Kùzu

Before we write any code of our own, the series looks at two graph databases in depth, where Neo4j is a server written in Java, which keeps its graph as fixed-size records that point at each other, while Kùzu is an embedded database in C++, from research at the University of Waterloo, with columns and compressed sparse row adjacency, and smollerGraph learns from both of them and is measured against both as it grows, on questions in the style of LDBC's Social Network Benchmark, at laptop scale.

From memory to disk

The code starts out as a throwaway graph kept in memory, a small knowledge graph about animals with a breadth-first walk and tests around it, and from there, each episode replaces a piece of what sits underneath while the tests keep checking the answers. The graph moves into files of 4 KiB pages, with fixed-size records for nodes and relationships, so it outlives the program, and then a buffer pool keeps those pages in memory, with frames, pins, dirty pages and the clock algorithm deciding which page goes next. A B+ tree, kept in pages through that same buffer pool, finds a node by its name, so opening a graph no longer means reading every node, and a parser and a planner turn a subset of Cypher into a plan and its rows.

Later on, properties join the nodes and relationships, in chains of records of their own, so queries can ask about them with WHERE, and labels and relationship types become tokens, numbers kept in place of their names as in Neo4j, which makes room for each relationship to sit in two chains, one for the node it starts at and one for the node it ends at, so it can be followed either way. The planner then starts from whichever node of a pattern it can find most quickly and walks from there in both directions.

Measuring as we go

Early on, we put a benchmark together, on a million relationships, with the same two-hop question asked of smollerGraph, Neo4j and Kùzu, but it wasn't quite fair, as smollerGraph timed a walk straight through its graph while the other two were each given a query in Cypher, so in episode eleven, all three answer the same two questions in Cypher, with parsing and planning included. On those, smollerGraph answers the two-hop question in a median of about 28 microseconds, where Neo4j takes nearly a millisecond and Kùzu about 1.6 milliseconds, although I'd take that with a pinch of salt, as Neo4j's times still include a trip over its network protocol to a container and Kùzu's a call from Python, while ours are measured inside the process, and smollerGraph does a small fraction of what either of them does, so what it shows is mostly that the layout on disk is doing its job, which is what matters at this stage.

Beyond storage

Once the storage was in place, the series moved on to what people actually do with a graph, with shortest paths found by a breadth-first search from both ends that meet in the middle, written as shortestPath in Cypher the way Neo4j writes it, and then cheapest paths along weighted relationships, with Dijkstra's algorithm, written the way Kùzu writes them. Nodes get embeddings with FastRP, as Neo4j's Graph Data Science library computes them, so you can ask which nodes are most similar to another, and a small graph neural network, a GraphSAGE in PyTorch, learns which species are threatened from their relatives in a graph of mammals and birds from Wikidata, with its predictions loaded back into the database for Cypher to ask about.

The most recent episode on applications takes a made-up company's Active Directory as a graph, with Cypher that follows several relationship types at once, so smollerGraph finds the paths from an ordinary account to Domain Admins, the way BloodHound does.

Around the database

A fair share of the series goes into the engineering around the code, with cpplint, clang-tidy and Abseil's Status keeping the codebase honest, a page in the browser that draws the graph with D3 and shows each node's record on disk, and a deploy to a VPS with Docker Compose and Caddy. The API docs are generated by Doxygen from the comments already in the headers and published by CI, the reasons behind each choice are written up as architecture decision records, and the library is packaged so that another CMake project can fetch it and run a query in a single call.

The library also compiles unchanged to WebAssembly with Emscripten, so the explorer runs the whole database in a browser tab, on a graph it builds from Wikidata's facts as the page opens, and you can play with it without installing anything.

Where it's heading

smollerGraph is heading towards a knowledge graph, with facts kept as nodes and the relationships between them, and it has already started to meet my other two series, as mvGPT, the small GPT I'm building from scratch, has learned to write Cypher to ask it for facts, while nanoMMO keeps its game content in it as a graph, with a test in CI that fails whenever a new player can no longer reach a quest, a monster, an item or a skill. Transactions and a log, which keep a database correct when things go wrong, are still ahead.

Following along

The code is on GitHub, with its API docs, and every step of every episode is a tag in the repository, so you can check out the code at any point in a video and run it yourself. New episodes go up on my YouTube channel, and the series' website has a page for each of them, with links to browse the code at each step and see what changed since the one before.

Latest videos

YouTube ↗