Ask most candidates to design a graph database and they describe a table of edges in Postgres with a src and dst column and a couple of indexes. That works until the first interesting question: “A user has 2 billion vertices and 200 billion edges across 200 machines. Someone runs friends-of-friends on a vertex whose neighbors are scattered across all 200 shards. Walk me through how many network round trips that query makes.” If the answer is “one per hop times the fan-out,” the query touches every machine in the cluster, twice, and the p99 is measured in seconds. The entire difficulty of a distributed graph database is not storing the graph - it is laying the graph out across machines so a traversal stays local, and moving that layout around while the cluster is live without freezing reads.

This post designs that system: a general-purpose distributed property graph database (vertices and edges, both with typed properties) that stores a graph far larger than one machine’s RAM and answers multi-hop traversal queries - friends-of-friends, shortest path, pattern match - with as few cross-shard round trips as the layout allows. The hard part the whole design is organized around is the partitioning strategy: a vertex-cut scheme that co-locates highly connected vertices with their most frequent neighbors, plus an online rebalancer that shifts partitions between shards without blocking the concurrent reads streaming through them. Everything else - storage format, query routing, consistency - is built to serve those two problems.

This is the engine underneath a product like a social graph or a knowledge graph, not the product itself. It is Neo4j’s clustering layer or TigerGraph’s distributed storage reduced to its hard core. Let me build it properly.

Functional Requirements (FR)

In scope:

  • Property graph storage. Store vertices and edges, each carrying a type label and a set of typed key-value properties. A vertex has an ID, a label (User, Post, Product), and properties (name, created_at). An edge has an ID, a type (FOLLOWS, LIKED, BOUGHT), a direction, two endpoint vertex IDs, and properties (weight, since).
  • Point mutations. Create/update/delete a vertex; create/update/delete an edge. An edge create must atomically attach the edge to both endpoints’ adjacency.
  • 1-hop neighbor read. Given a vertex and an optional edge-type filter and direction, return its neighbors (in-edges, out-edges, or both). This is the primitive every traversal is built from.
  • Multi-hop traversal. Given a start vertex, a hop bound k, and optional per-hop filters (edge type, vertex predicate), return the reachable set or a count. Friends-of-friends is the canonical k=2 case.
  • Shortest path. Given two vertices, return the shortest path (bounded hop limit) between them, respecting edge-type filters. Bidirectional BFS across shards.
  • Pattern match (bounded). Small fixed subgraph patterns - (a)-[:FOLLOWS]->(b)-[:FOLLOWS]->(c) with predicates - evaluated starting from an anchor vertex. A subset of Cypher/Gremlin, not the full language.

Explicitly out of scope (naming it means I own the boundary):

  • Global graph analytics. PageRank, connected components, community detection, all-pairs shortest path. These are full-graph batch jobs that scan every edge; they run offline on a snapshot in a Pregel/Giraph/GraphX system, not as online queries. This engine does bounded local traversal, and I will say exactly where the line is.
  • The full query language. I support a bounded traversal/pattern subset, not arbitrary multi-way joins with aggregation pushdown and a cost-based optimizer. I note where the optimizer would go.
  • Geo-distribution / multi-region strong consistency. Single-region cluster with replicas; cross-region is a note, not a design.
  • Transactions spanning many vertices. I guarantee atomicity of a single edge (both endpoints) and single-vertex writes, and I give a bounded-isolation story for small multi-vertex transactions, but I do not promise serializable transactions over arbitrary subgraphs.

The decision that drives everything: this is a read-dominated system where the dominant cost is network round trips during traversal, and the graph does not fit on one machine, so the layout of vertices across machines is the whole ballgame. Every hard choice below follows from “keep the traversal’s frontier on as few machines as possible, and let the layout change while the system runs.”

Non-Functional Requirements (NFR)

  • Scale: ~2B vertices, ~200B directed edges, average degree ~100 with a heavy tail (supernodes with tens of millions of edges - a celebrity, a popular hashtag). Raw stored size on the order of a few TB to low tens of TB, far beyond one node, so ~100-200 shards each holding a slice plus replicas.
  • Latency: 1-hop neighbor read p99 < 10ms. Friends-of-friends (k=2, bounded fan-out) p99 < 50ms. Bounded shortest-path p99 < 200ms. The latency budget is dominated by cross-shard round trips: a round trip is ~0.5-1ms in-datacenter, so a query that serializes 20 round trips is already at 20ms before any work.
  • Throughput: ~300K 1-hop reads/sec, ~50K multi-hop traversals/sec, ~30K writes/sec (edge creates dominate writes) at peak across the fleet.
  • Availability: 99.95% on reads. A traversal that returns a slightly stale neighbor set is acceptable; a query that hangs because one shard is slow is not. Reads must degrade, never block.
  • Consistency: read-your-writes for the writer on their own vertices and edges; eventual consistency for everyone else’s view of the graph. An edge created 2 seconds ago appearing in a traversal a moment late is invisible. The one hard requirement: an edge create must be atomic across both endpoint adjacencies - you never see an edge from A’s side that does not exist from B’s side.
  • Durability: the graph is the source of truth and must never be lost. Every mutation is on a durable, replicated write-ahead log before it is acknowledged. In-memory adjacency caches are derived and rebuildable.
  • Rebalancing: the layout must be changeable online. Adding shards, draining a hot shard, or re-co-locating a vertex with its neighbors must happen while reads and writes flow, without a global lock and without blocking the traversals passing through the moving data.

Back-of-the-Envelope Estimation (BoE)

Real arithmetic, because the storage and round-trip numbers pick the architecture.

Storage:

Vertices: 2B, each ~ 200 B (id + label + a few properties + adjacency offset)
  2B * 200 B                      = 400 GB  for vertex records
Edges: 200B directed, each stored as an adjacency entry:
  neighbor_id (8B) + edge_type (1B) + edge_prop_ref (8B) ~ 24 B per entry
  (store both directions for undirected / bidirectional traversal: 200B entries)
  200B * 24 B                     = 4.8 TB  for adjacency
Edge property blobs (sparse):     ~ 1-2 TB
-> raw ~ 6-7 TB, times replication factor 3 = ~ 20 TB across the fleet.
   At ~128 GB usable RAM+SSD per shard, ~150-200 shards. Confirms: must shard.

The number that decides the design - round trips per traversal:

Friends-of-friends, k=2, from a vertex with degree D=100:
  Hop 1: read start vertex's 100 neighbors -> 1 shard (the start's shard).
  Hop 2: expand each of 100 neighbors' adjacency.
    WORST CASE (random partitioning): those 100 neighbors sit on ~100
    distinct shards -> up to 100 cross-shard round trips, often batched
    but still touching most of the cluster.
    GOAL (locality-aware layout): the 100 neighbors cluster onto, say,
    5-10 shards -> 5-10 round trips, batched to one RPC per shard.

That is the entire thesis in one estimate. The same query costs ~100 round trips under random sharding and ~5-10 under a locality-aware layout. At ~0.7ms per round trip, that is the difference between a 70ms+ tail and a sub-10ms expansion. Traversal latency is a function of partition locality, not of graph size.

Write load and WAL:

30K writes/sec, edge create ~ 2 adjacency appends (both endpoints) + 1 WAL record
  WAL: 30K * ~100 B = 3 MB/sec per the primary, times replication -> ~9 MB/sec.
  Trivial in bytes; the cost is the cross-shard coordination when the two
  endpoints of an edge live on different shards (the usual case).

Supernode blast radius:

A supernode with 20M edges, stored as one adjacency list:
  20M * 24 B = 480 MB for one vertex's neighbors.
  Expanding it fully in a traversal reads 480 MB and fans to every shard.
  -> supernodes must be special-cased (edge partitioning + fan-out caps),
     or one celebrity vertex melts a shard and any traversal through them.

Two conclusions drive the design. First, partitioning is the product: the layout decides whether a traversal is local or cluster-wide. Second, supernodes break any naive scheme and need their own treatment. Everything below serves those.

High-Level Design (HLD)

A sharded storage tier holds vertex and edge data, each shard owning a set of partitions (the unit of placement and movement). A stateless query/coordinator tier parses traversals, routes hop expansions to shards, and assembles results. A partition directory (small, strongly consistent) maps partition -> shard and is the authority the whole cluster routes against. A rebalancer moves partitions between shards online. Writes go through a durable, replicated WAL per shard.

                         CLIENTS (traversal / mutation queries)
  ┌──────────────────────────────────────────────────────────────────────────┐
  │   App  --(Cypher/Gremlin-subset query)-->  Query Coordinator (stateless)   │
  │                        parse -> plan -> route hops                          │
  └───────────┬───────────────────────────────────────────────┬──────────────┘
              │ (lookup: which shard owns a vertex's partition) │
      ┌───────▼─────────┐                                       │ hop-expansion RPCs
      │ Partition        │   partition_id = hash(vertex_id) or   │ (batched per shard)
      │ Directory (Raft) │   locality-assigned; -> owning shard  │
      │ part -> shard    │   + version/epoch for move safety     │
      └───────┬─────────┘                                        │
              │ routing table (cached in coordinators)           │
  ┌───────────▼──────────────────────────────────────────────────▼───────────┐
  │                         STORAGE SHARDS (150-200)                           │
  │  ┌────────────── Shard N (leader) ───────────────┐   replicas (followers)  │
  │  │ Partitions: {P3, P17, P42, ...}                │   async/sync replicate  │
  │  │  per vertex:  record + adjacency (CSR-like)    │ ───────────────────────>│
  │  │  local index: vertex_id -> adjacency offset    │   WAL shipped to        │
  │  │  WAL (durable) + in-RAM hot adjacency cache    │   followers + snapshot  │
  │  └────────────────────────────────────────────────┘                        │
  └────────────────────────────▲──────────────────────────────────────────────┘
                               │ partition moves (copy -> catch-up -> cutover)
                      ┌────────┴─────────┐
                      │   Rebalancer     │  watches load/locality metrics,
                      │  (controller)    │  plans + executes online moves,
                      └──────────────────┘  updates the directory on cutover

Read hot path - a friends-of-friends traversal:

  1. The app sends a traversal (MATCH (a)-[:FOLLOWS*2]->(c) WHERE a.id=U) to a stateless Query Coordinator. The coordinator parses it into a plan: hop 1 expand U’s FOLLOWS out-edges, hop 2 expand each result’s FOLLOWS out-edges, dedupe, exclude hop-1 and self.
  2. The coordinator looks up U’s partition in its cached copy of the partition directory (partition_id -> shard) and sends a hop-expansion RPC to U’s owning shard: “expand U, FOLLOWS, out.” The shard reads U’s adjacency locally and returns the neighbor ID list. One round trip.
  3. For hop 2, the coordinator takes the ~100 neighbor IDs, groups them by owning shard using the directory, and sends one batched RPC per shard - not per vertex. Under a locality-aware layout the 100 neighbors fall on a handful of shards, so this is ~5-10 RPCs issued in parallel, each expanding a batch of vertices on that shard and returning their neighbor lists. The shard does the fan-out expansion locally, so the coordinator receives already-expanded results, not another round of IDs to route.
  4. The coordinator unions the hop-2 results, removes hop-1 neighbors and U itself, applies any vertex predicate, and returns. Total: 1 + (parallel ~5-10) round trips, bounded by the slowest shard, not the sum.

Write path - an edge create A -[FOLLOWS]-> B:

  1. The mutation goes to a coordinator, which must append the edge to A’s out-adjacency (on A’s shard) and B’s in-adjacency (on B’s shard). These are usually different shards. The coordinator runs a small two-shard commit: write the edge record to A’s shard WAL and B’s shard WAL, and only acknowledge once both are durable. A lightweight 2PC (or a single logical-edge home shard that owns the edge and asynchronously maintains the mirror) keeps the two adjacencies atomic. I pick the design in the deep dive.
  2. Each shard replicates its WAL to followers before (or shortly after, per the durability setting) acking, and updates its in-RAM adjacency cache.

The architectural core: the coordinator is a router that batches hop expansions by owning shard and pushes the expansion work down to the shard that holds the data, so the only thing crossing the network is “expand this batch” and “here are the expanded neighbors” - and the whole system is engineered so those shards are few. That “few” is the job of partitioning and rebalancing, which is where the real work is.

Component Deep Dive

The hard parts, each walked from the naive approach to where it breaks to the real design: (1) partitioning - the core challenge, from hash partitioning to locality-aware vertex-cut, (2) supernodes, which break any vertex-placement scheme, (3) cross-shard traversal execution that bounds round trips, and (4) online rebalancing that moves partitions without blocking reads.

1. Partitioning: From Hash Sharding to Locality-Aware Vertex-Cut (the core challenge)

The layout decides every traversal’s latency. The goal: place a vertex on the same shard as the neighbors it is most often traversed to, so a frontier expansion stays local.

Approach A: Hash-partition vertices by ID (the naive baseline)

shard = hash(vertex_id) mod N. Every vertex lands on a uniformly random shard. Simple, perfectly balanced by count, trivial to route (the directory is just a hash function).

Where it breaks at scale:

  • Every multi-hop traversal becomes a cluster-wide scatter. A vertex’s neighbors are, by construction, uniformly scattered across all N shards. From the BoE, friends-of-friends on a degree-100 vertex touches ~100 shards at hop 2. The query’s latency is the slowest of N shards, and at 50K traversals/sec each hitting most of the cluster, the network and the shards saturate. You have balanced storage perfectly and destroyed locality completely - the exact opposite of what a graph query needs.
  • Edges always straddle two shards. A -[FOLLOWS]-> B puts A and B on independent random shards, so every edge create is a cross-shard write and every 1-hop expansion to a neighbor is a network hop. There is zero co-location to exploit.

Hash partitioning optimizes the one thing that does not matter (count balance) and pessimizes the one thing that does (traversal locality). It is the right default for a KV store and the wrong default for a graph.

Approach B: Edge-cut partitioning (min-cut, the classic graph-partitioning answer)

Assign each vertex to a shard such that the number of edges crossing shard boundaries (the “cut”) is minimized - a balanced min-cut, the problem METIS and friends solve. Co-located vertices share a shard; a well-partitioned social graph puts dense friend-clusters together.

Where it breaks:

  • Power-law graphs do not have a small edge cut. Real graphs (social, web) are power-law: a few supernodes connect to everything. Any assignment of a supernode to one shard leaves most of its millions of edges crossing the cut. Edge-cut partitioners provably do badly on power-law degree distributions - the cut is enormous no matter how you slice it, because the hubs are incompressible. This is the well-known result behind PowerGraph: for power-law graphs, cut the vertices, not the edges.
  • Rebalancing a min-cut is a global, offline recompute. Min-cut is NP-hard; the heuristics are batch jobs over the whole graph. You cannot nudge one vertex online; the graph changes continuously and your partitioning goes stale, and recomputing it is a cluster-wide stop-the-world operation. It is a great offline bootstrap and a terrible online strategy.

Approach C: Vertex-cut partitioning with locality-aware placement and a routing directory

This is the design. Two ideas combined: vertex-cut for the supernode problem, and locality-aware incremental placement for online, traversal-driven co-location.

Vertex-cut: partition edges, replicate (mirror) vertices. Instead of assigning each vertex to one shard, assign each edge to a shard, and allow a vertex to be mirrored across every shard that holds one of its edges. One mirror per vertex is the master (owns the canonical properties and coordinates writes); the others are read mirrors. A supernode’s millions of edges spread across many shards by edge assignment, so no single shard holds all of them - the hub is “cut” into mirrors, each holding a slice of its adjacency. This is exactly PowerGraph’s Gather-Apply-Scatter model and is why it beats edge-cut on power-law graphs: the hard-to-place hubs are the ones you spread.

Edge-cut (vertex on one shard):          Vertex-cut (edge on one shard):
  hub H with 9 edges, all on shard 1       H's edges spread across 3 shards;
  shard1:  H + a,b,c,d,e,f,g,h,i           H is MIRRORED on each, holding
  shard2:  (nothing of H)                   its local slice of adjacency:
  -> shard1 holds all 9 edges, hot          shard1: H' + {a,b,c edges}
     and any traversal through H            shard2: H' + {d,e,f edges}
     hits shard1 only (hotspot).            shard3: H' + {g,h,i edges}
                                            -> H's expansion parallelizes
                                               across 3 shards; no hotspot.

Locality-aware placement for the common (non-hub) vertices. For ordinary vertices, co-locate a vertex with the neighbors it is most frequently traversed to. On edge creation, bias the new edge’s shard assignment toward the shard already holding the denser endpoint’s edges (a greedy, streaming vertex-cut heuristic like HDRF - High-Degree Replicated First - which places each edge to minimize new mirrors while balancing load). Over time, the rebalancer (part 4) observes traversal co-access: pairs of vertices frequently expanded together in the same query get pulled onto the same shard. The signal is not the static graph structure but the query workload - which neighbors actually get traversed.

Edge arrives: (u, v).  Greedy vertex-cut placement (HDRF-style):
  A(u) = set of shards that already mirror u (hold one of u's edges)
  A(v) = set of shards that already mirror v
  if A(u) ∩ A(v) != empty:  place edge on a shard in the intersection
       (no new mirror created - best case, pure locality win)
  elif one of A(u),A(v) empty: place on the other's shard (one new mirror)
  elif both non-empty:       place on the LESS loaded of the two sides,
       preferring the HIGHER-degree vertex's side (hubs attract edges,
       keeping the low-degree vertex's mirror count down)
  else (both new):           place on the least-loaded shard overall
  -> minimizes total mirror count (replication factor) while balancing.

The routing directory. Because placement is no longer a pure hash, the coordinator cannot compute a vertex’s location; it must look it up. A partition directory maps partition_id -> owning shard (and, for mirrored vertices, the set of mirror shards and which is master). We route at partition granularity, not per-vertex: vertices are grouped into a few hundred thousand logical partitions (hash of a locality-cluster ID), partitions are the unit of placement and movement, and the directory is small enough (a few hundred thousand entries) to replicate into every coordinator and keep in a Raft-backed store. A vertex-level lookup is first partition = f(vertex), then shard = directory[partition].

Why partitions as the placement unit, not raw vertices: a directory of 2B vertex -> shard entries is huge and churns constantly; a directory of ~200K partition -> shard entries is tiny, cache-friendly, and lets the rebalancer move millions of vertices as one cheap directory update. Locality-aware placement decides which partition a vertex-cluster belongs to; the directory decides which shard hosts that partition.

The invariant that makes this correct and fast: the master mirror of a vertex owns its canonical state and serializes its writes, every mirror can serve a local 1-hop expansion of the slice it holds, and the directory is the single source of truth for where everything lives - so a traversal reads from whichever mirrors are closest, and a supernode’s expansion fans out in parallel across its mirrors instead of hammering one shard.

2. Supernodes: When One Vertex Does Not Fit the Model

Vertex-cut already spreads a supernode’s edges across shards. But a supernode is still pathological for traversal and needs explicit handling.

Approach A: Treat a supernode like any vertex (naive)

Store all its edges as one adjacency list on its master, expand them all on traversal.

Where it breaks: from the BoE, a 20M-edge supernode is 480 MB of adjacency. Expanding it fully in a friends-of-friends reads half a gigabyte and fans to every shard the mirrors touch - one query melts the cluster. And any traversal that passes through a celebrity (two random users are often connected via a celebrity they both follow) inherits that blowup. A single hot vertex becomes the latency and hotspot story for a huge fraction of queries.

Approach B: Edge-sliced mirrors + fan-out caps + typed secondary indexing

  • Edge slicing across mirrors (already from vertex-cut). The supernode’s adjacency is split into slices, one per mirror shard. An expansion is issued to all mirror shards in parallel and merged, so the work and bytes are divided by the number of mirrors, not borne by one shard.
  • Bounded fan-out / sampling. Most product queries through a supernode do not actually need all 20M neighbors - friends-of-friends via a celebrity would return “everyone,” which is useless. Cap the expansion: traversals declare a per-hop fan-out limit, and the engine expands a bounded sample (or refuses to traverse through vertices above a degree threshold unless the query explicitly opts in). “Friends of friends” semantically should not route through a celebrity both parties follow; the degree cap encodes that.
  • Per-type adjacency segmentation and local indexes. Store a supernode’s adjacency segmented by edge type and sorted by neighbor ID (or by a property like recency). A traversal filtered to FOLLOWS reads only that segment; a traversal wanting “most recent 100 likers” reads a sorted prefix. This turns “scan 20M edges” into “read the relevant segment’s prefix,” and it is why the storage format is CSR-like per (vertex, edge-type) rather than one flat list.
  • Degree-aware query planning. The planner checks endpoint degrees via the directory’s degree stats and reorders: for shortest path between a low-degree and a high-degree vertex, expand from the low-degree side (bidirectional BFS that grows the cheaper frontier), so the supernode is a target reached, not a frontier exploded.

The rule: a supernode is never expanded fully and never lives on one shard. Its edges are sliced across mirrors, its adjacency is typed and sorted for prefix reads, and the planner expands away from it, not through it.

3. Cross-Shard Traversal Execution: Bounding Round Trips

The layout keeps neighbors clustered; the executor must still turn a k-hop traversal into the minimum number of network round trips over those clusters.

Approach A: Coordinator pulls IDs and re-routes each hop (naive)

Coordinator reads hop-1 IDs, then for each neighbor sends a separate RPC to fetch its neighbors, collects IDs, repeats for hop 3.

Where it breaks: one RPC per frontier vertex per hop is O(frontier size) round trips. A 100-wide frontier at hop 2 is up to 100 RPCs, mostly serialized by the coordinator’s result assembly, and the coordinator becomes the bottleneck shuttling raw ID lists back and forth. The data stays on the shards; only routing decisions need to be central, yet this design drags every intermediate result through the coordinator.

Approach B: Push-down expansion, batch-by-shard, and server-side frontier joins

  • Batch frontier by owning shard. At each hop, group the frontier’s vertices by owning shard (one directory lookup per vertex, all cached) and send one RPC per shard carrying the whole batch for that shard: “expand these 40 vertices, edge-type FOLLOWS, out-direction, return their neighbor lists.” Round trips per hop = number of distinct shards the frontier touches, not frontier size. Locality-aware layout makes that number small; batching makes it the floor.
  • Push the expansion down to the shard. The shard does the local adjacency reads and returns expanded neighbors, so the work happens where the data is. For a k-hop where consecutive hops stay on the same shard (common under good locality), the shard can expand multiple hops locally before returning - a “traversal fragment” executed server-side - collapsing several hops into one round trip. The coordinator sends a small traversal program, not a sequence of fetch calls.
  • Parallel fan-out, bounded by the slowest shard. Per-hop RPCs to distinct shards go out concurrently; the hop’s latency is the max over shards, not the sum. With a hedging/timeout policy, a straggler shard is re-issued to a replica so one slow node does not define the tail.
  • Bidirectional search for shortest path. Expand from both endpoints simultaneously, alternating the smaller frontier, and detect the meet in the middle. This cuts the explored set from O(b^k) to O(b^(k/2)) - the single biggest win for shortest path - and combined with degree-aware side selection keeps the frontiers off supernodes.
  • Dedup and visited-set management. The coordinator keeps the global visited set (to dedupe across shards and stop cycles) but ships only the new frontier down each hop. Visited membership is checked coordinator-side against a compact hash set; shards return raw neighbors and the coordinator filters. For very large frontiers, the visited set is itself partitioned and the filtering pushed down with a Bloom filter to cut transfer.
k=2 friends-of-friends, degree-100 start, good locality:
  hop1: 1 RPC to start's shard           -> 100 neighbor IDs
  group 100 IDs by shard -> 6 shards
  hop2: 6 parallel RPCs (batched)        -> each returns its batch's neighbors
  latency = RTT_hop1 + max(6 parallel RTTs) + local merge
          ~ 0.7ms + ~1ms + merge  ->  well under the 50ms budget
Contrast random layout: hop2 groups into ~80 shards -> 80 parallel RPCs,
  tail dominated by the slowest of 80, plus coordinator merge of 80 responses.

The executor’s one rule: route decisions are central and cheap (directory lookups), but data movement is pushed to the shards and batched by owning shard, so the number of round trips tracks the number of shards the frontier spans - which the layout is engineered to keep small.

4. Online Rebalancing: Moving Partitions Without Blocking Reads

The layout must change while the system runs - add a shard, drain a hot one, re-co-locate a partition with its newly-frequent neighbors. The hard constraint: do not block the reads and writes streaming through the partition while it moves.

Approach A: Lock the partition, copy it, update the directory (naive stop-the-world)

Take a write lock (or full lock) on the partition, copy its data to the destination shard, flip the directory, release.

Where it breaks: copying a partition holding millions of vertices and their adjacency takes seconds to minutes. For that whole window, every traversal that touches the partition stalls - and because traversals fan across many partitions, a single moving partition can stall a large fraction of all queries. At 300K reads/sec, a multi-second lock is an outage. Blocking is a non-starter; the requirement is explicitly online.

Approach B: Copy-catch-up-cutover with version-fenced routing and dual-read

A live migration protocol that keeps the source serving throughout and switches atomically at the end. This is the same shape as a VM live-migration or a Vitess resharding.

  1. Snapshot + bulk copy (source stays live). The rebalancer tells the destination shard to pull a consistent snapshot of the partition from the source (from the source’s WAL/snapshot at a marked log offset). Reads and writes keep hitting the source normally; the copy runs in the background off the snapshot, not the live data. No lock.
  2. Catch-up tailing. After the bulk copy, the destination tails the source’s WAL from the snapshot offset forward, applying every mutation the partition received during and after the copy. The destination converges toward the source’s live state while both stay up. This runs until the lag is tiny (sub-millisecond of backlog).
  3. Brief cutover with a fence. When caught up, the rebalancer performs an atomic handoff: it bumps the partition’s epoch in the directory and sets ownership to the destination. The source, on seeing the epoch bump (or on a short, millisecond-scale write pause for just this partition), stops accepting writes for the partition and forwards the final tail. The directory update is a single Raft commit - the only globally-synchronized step, and it is one small write, not a data copy.
  4. Version-fenced routing (the key to not blocking reads). Every directory entry carries an epoch. Coordinators cache the routing table and stamp each RPC with the partition epoch they believe is current. A shard rejects an RPC whose epoch is stale (“you are reading the wrong owner”), which prompts the coordinator to refresh the directory and retry against the new owner. During migration, reads keep going to the source (current epoch) with zero added latency; only at the instant of cutover does the epoch advance, and the first few post-cutover RPCs to the old owner get a fast reject-and-redirect. No read ever blocks - at worst a handful retry once.
  5. Dual-read / read-old-until-cutover. Before cutover, the destination is not yet authoritative, so reads are served entirely by the source - the half-copied destination is never read. After the epoch flips, reads go to the destination, which is fully caught up. There is no window where a read sees a partially-migrated partition, because the authority flips atomically via the epoch, and the source serves right up to that instant.
Timeline of a partition move (P42: shard A -> shard B), reads never block:
  t0  rebalancer: B pulls snapshot of P42 @ A's WAL offset X.  (A serves P42)
  t1  B bulk-loads snapshot.                                   (A serves P42)
  t2  B tails A's WAL from offset X, applies forward.          (A serves P42)
  t3  B caught up (lag ~0). rebalancer commits directory:
        P42 -> B, epoch 7->8  (single Raft write)              <-- atomic cutover
  t4  A rejects P42 RPCs stamped epoch 7 -> coordinator
        refreshes directory, retries at B (epoch 8).           (B serves P42)
  Reads during t0..t3 hit A with no added latency; the only
  cost is a one-time retry for in-flight RPCs at the t3 instant.

Writes during the move keep going to the source until cutover; because the destination is tailing the WAL, it does not miss any. A write arriving in the tiny cutover window either lands on the source and is forwarded in the final tail, or is rejected-and-retried onto the new owner by the same epoch fence. Edge atomicity (both endpoints) is unaffected: the edge’s two-shard commit uses current directory epochs, and a mid-move endpoint simply resolves to whichever shard the epoch names.

Picking what to move is the rebalancer’s policy loop: it watches per-shard CPU/memory/QPS and per-partition traversal co-access (which partitions are frequently expanded together in the same query). It plans moves that (a) relieve overloaded shards and (b) pull co-accessed partitions together, running moves one or a few at a time with a rate limit so migration traffic never crowds out live queries. Moves are reversible and idempotent; a failed move (destination dies mid-copy) is simply abandoned - the directory never flipped, so the source was authoritative the whole time.

The rebalancing invariant: the source serves the partition at full speed until a single atomic directory epoch bump hands off ownership, and stale-epoch RPCs fast-fail into a directory refresh - so a multi-minute data copy happens entirely in the background and the only synchronized moment is one small Raft write that no read ever waits on.

API Design & Data Schema

Query / mutation API

A bounded Cypher/Gremlin-style surface over HTTP/gRPC. Traversals are declarative; the coordinator plans and routes them.

# 1-hop neighbors
POST /v1/neighbors
  { "vertex_id": "U123", "edge_type": "FOLLOWS", "direction": "out",
    "limit": 500 }
  200 { "neighbors": [ {"id":"U98","edge_props":{"since":"2024-01-02"}}, ... ],
        "truncated": false }

# Multi-hop traversal (friends-of-friends)
POST /v1/traverse
  { "start": "U123", "steps": [
      {"edge_type":"FOLLOWS","direction":"out"},
      {"edge_type":"FOLLOWS","direction":"out"} ],
    "exclude_start_neighbors": true, "fanout_cap": 1000, "return": "vertices" }
  200 { "results": ["U77","U812", ...], "hops": 2, "shards_touched": 6 }

# Shortest path (bidirectional, bounded)
POST /v1/shortest_path
  { "from":"U123", "to":"U999", "edge_type":"FOLLOWS", "max_hops":6 }
  200 { "path": ["U123","U41","U300","U999"], "length": 3 }

# Pattern match (bounded subgraph from an anchor)
POST /v1/match
  { "pattern":"(a)-[:FOLLOWS]->(b)-[:LIKED]->(p:Post)",
    "anchor":{"a":"U123"}, "where":{"p.lang":"en"}, "limit":100 }

# Mutations
POST /v1/vertex   { "id":"U123","label":"User","props":{"name":"..."} }
POST /v1/edge     { "type":"FOLLOWS","from":"U123","to":"U98",
                    "props":{"since":"2026-11-26"} }   # atomic on both endpoints
DELETE /v1/edge   { "type":"FOLLOWS","from":"U123","to":"U98" }

# Admin / rebalancer control
GET  /v1/directory/partition?vertex_id=U123     # which partition + shard + epoch
POST /v1/rebalance/move  { "partition":"P42","to_shard":"S17" }   # manual move
GET  /v1/stats           # per-shard load, mirror counts, move queue, co-access

Storage format and schema

Not a relational schema - this is native graph storage: per-vertex records with an inlined, index-free adjacency so a 1-hop expansion is a pointer offset, not a join. NoSQL/custom engine, because the access pattern is “given a vertex, read its adjacency slice and hop,” which a B-tree row store with a join per hop is terrible at (the “index-free adjacency” argument Neo4j makes). SQL is used only for the tiny directory/catalog where consistency matters.

Vertex record (on each shard that masters or mirrors the vertex):

vertex {
  vertex_id   : uint64        # primary key, globally unique
  label       : uint16        # interned label id (User=1, Post=2, ...)
  is_master   : bool          # this shard masters the vertex (owns canonical props)
  props       : msgpack blob  # typed key-value properties (master copy authoritative)
  adjacency   : offset -> CSR-like block, SEGMENTED BY edge_type:
     for each edge_type: sorted array of (neighbor_id, direction, edge_prop_ref)
                         (sorted by neighbor_id; for supernodes also a
                          recency-sorted secondary ordering)
}
Local index:  vertex_id -> adjacency offset (in-RAM hash or sorted index)
Storage:      LSM/SSTable on SSD for cold, memory-mapped hot blocks, WAL for writes.

Edge (vertex-cut: the edge is assigned to one shard; its endpoints are mirrored there):

edge {
  edge_id     : uint64
  type        : uint16
  from_id     : uint64        # master may live on another shard
  to_id       : uint64
  props       : msgpack blob
  home_shard  : implied by the edge's partition assignment (HDRF placement)
}
The edge contributes an adjacency entry to from's out-list and to's in-list,
both materialized on the edge's home shard (where from and to are mirrored).

Partition directory (Raft-backed, strongly consistent, small):

partition {
  partition_id : uint32       # ~200K partitions total
  owner_shard  : uint16       # current owning shard (leader)
  mirror_shards: [uint16]     # shards holding mirrors of this partition's vertices
  master_map   : for mirrored vertices, which shard masters them
  epoch        : uint64       # bumped on every ownership change (move fence)
  degree_stats : coarse per-partition degree histogram (for planner)
}
Replicated into every coordinator; the ONE strongly-consistent structure.

Catalog (tiny, SQL/Raft): label ids, edge-type ids, property schemas, supernode degree thresholds, per-shard replica topology. Read constantly, changed rarely, cached in coordinators.

The split: native graph storage (index-free adjacency, segmented by edge type) on sharded LSM/SSD for the bulk, because traversal wants pointer-chase locality not relational joins; a tiny Raft-backed directory for partition -> shard -> epoch, because routing correctness and the move fence need strong consistency. Everything heavy is eventually consistent and rebuildable; only the directory and catalog are strongly consistent, and they are tiny.

Bottlenecks & Scaling

Where it breaks first, in order, and the fix for each.

1. Partition locality (the first and biggest wall). Random/hash sharding makes every multi-hop traversal a cluster-wide scatter; latency is the slowest of N shards and the network saturates. Fix: locality-aware vertex-cut partitioning (part 1). Edges assigned to shards by a greedy HDRF heuristic, vertices mirrored, partitions co-located by observed traversal co-access. This is the one change that makes traversal latency a function of locality, not graph size - cutting a friends-of-friends from ~100 shards touched to a handful.

2. Supernodes / hot vertices. A celebrity with tens of millions of edges is 100s of MB of adjacency on one vertex; expanding it, or traversing through it, melts a shard. Fix: vertex-cut slices the hub’s edges across mirrors (parallel expansion, no single hotspot), fan-out caps and degree thresholds stop traversals from exploding through hubs, per-edge-type segmented + sorted adjacency turns a full scan into a prefix read, and the planner expands away from high-degree vertices (degree-aware bidirectional search).

3. Cross-shard round trips per hop. Even with locality, a naive executor does one RPC per frontier vertex, so round trips scale with frontier size. Fix: batch the frontier by owning shard (one RPC per shard), push expansion down to the shards, and run hops in parallel bounded by the slowest shard (part 3). Multi-hop fragments that stay local are executed server-side in one round trip.

4. Shard load imbalance over time. Graph growth and shifting query patterns make one shard hot (storage or QPS) while others idle. Fix: online rebalancing (part 4) - the rebalancer drains hot shards and re-co-locates co-accessed partitions via copy-catch-up-cutover, rate-limited so migration never crowds live traffic. Adding a shard is just a set of moves onto it.

5. The move itself blocking reads. A partition copy takes seconds to minutes; locking it for that window is an outage. Fix: copy-catch-up-cutover with an epoch fence - the source serves at full speed throughout, cutover is a single atomic directory epoch bump (one Raft write), and stale-epoch RPCs fast-fail into a directory refresh-and-retry. No read ever blocks on a data copy.

6. The partition directory as a single point / hot read. Every coordinator routes against it; if it is unavailable or stale, routing breaks. Fix: the directory is small and fully replicated into every coordinator (cached), Raft-backed for the authoritative copy, and self-correcting via the epoch fence - a stale cached directory causes a one-time reject-and-refresh, never a wrong read. Scale the authoritative store with Raft read replicas; the write rate (ownership changes) is low.

7. Cross-shard edge writes / atomicity cost. An edge create touches two shards (both endpoints); a 2PC per edge at 30K writes/sec is coordination-heavy. Fix: vertex-cut co-locates the edge’s endpoints on the edge’s home shard (both mirrored there), so the edge create is frequently a single-shard write; when endpoints’ masters differ, a lightweight edge-home-owns-it protocol (the edge’s home shard commits the edge and asynchronously maintains the far mirror, with the mirror reconciled from the WAL) keeps it to one synchronous append plus async mirror update, reserving full 2PC only where strict atomicity across masters is demanded.

8. Replication lag / read-your-writes. Followers lag the leader; a user may not see their own just-created edge. Fix: route the writer’s own reads to the leader (or to a mirror the write already reached) for read-your-writes; everyone else reads from the nearest replica with eventual consistency. The edge-atomicity invariant (both endpoints) is enforced at write time, independent of follower lag.

9. Visited-set / frontier explosion on deep traversals. A k=4+ traversal on a dense region explodes the frontier and the coordinator’s visited set. Fix: bidirectional search (O(b^(k/2))), fan-out caps per hop, Bloom-filtered visited pushdown to cut transferred IDs, and early termination once enough results are found. Deep unbounded traversal is pushed to the offline analytics path, not served online.

10. Rebalancer thrash / oscillation. An over-eager rebalancer ping-pongs partitions as load shifts, spending more on migration than it saves. Fix: hysteresis and rate limits - move only on sustained imbalance past a threshold, cap concurrent moves, prefer the single highest-value move per cycle, and make moves reversible/idempotent so a bad decision is cheaply undone. The policy optimizes a damped objective (load balance + locality), not an instantaneous one.

Wrap-Up

The trade-offs that define this design:

  • All the engineering is in the layout and its movement, not the query. Expanding a vertex is a local pointer-chase; the design value is placing vertices so a traversal’s frontier spans few shards, and moving that placement online as load and workload shift. We spend the entire complexity budget on locality and live migration.
  • Vertex-cut over edge-cut, locality-aware over hash. Power-law graphs have no small edge cut, so we cut the vertices - assign edges to shards and mirror vertices - which spreads the incompressible hubs instead of piling them on one shard, and we place edges with a greedy workload-driven heuristic so ordinary vertices sit with the neighbors they are actually traversed to. Hash partitioning balances the one thing that does not matter (count) and ruins the one that does (locality); we accept a non-trivial routing directory as the price of locality.
  • Push-down batched expansion over coordinator-pulled hops. Route decisions are central and cheap (directory lookups); data movement is pushed to the shards and batched by owning shard, so round trips track shards-touched, not frontier size - and the layout is engineered to keep shards-touched small.
  • Online copy-catch-up-cutover over stop-the-world rebalancing. A partition move copies and tails in the background while the source serves at full speed, and hands off with a single atomic directory epoch bump; stale-epoch RPCs fast-fail into a refresh-and-retry, so the only synchronized moment is one small Raft write that no read waits on. We trade a one-time retry for in-flight RPCs at cutover for never blocking a read on a multi-minute copy.
  • Eventual consistency with atomic-edge and read-your-writes carve-outs. We do not promise serializable transactions over arbitrary subgraphs; we promise atomicity of a single edge across both endpoints, read-your-writes for the writer, and bounded-stale eventual consistency for everyone else - trading global transactional strength for the traversal latency and availability the workload actually needs.

One-line summary: a distributed property graph database that stores an index-free adjacency on sharded native storage, uses locality-aware vertex-cut partitioning to co-locate highly connected vertices with their most-traversed neighbors so multi-hop queries touch few shards, executes traversals by batching frontier expansion per owning shard and pushing it down, and rebalances partitions online via copy-catch-up-cutover behind an epoch-fenced directory - trading strong global consistency for bounded staleness so that friends-of-friends stays local and the cluster reshapes itself without ever blocking a read.