# Graph databases (Neo4j) for system design interviews

> Neo4j is a property graph database that stores entities as nodes and connections as relationships, with properties on both. It fits systems where answering questions means following several connections, such as compatibility checks, relationship-based recommendations, or inherited permissions.

Source: https://sysround.com/tech/neo4j
Updated: 2026-11-05


## How it works

The property graph model gives nodes labels, such as User or Product, and relationships types, such as FOLLOWS or COMPATIBLE_WITH. Relationships are directed, but queries can traverse them in either direction. Properties hold attributes such as timestamps, weights, and compatibility conditions.

Queries typically use an index to find a small starting set, then expand through stored relationships. Neo4j stores relationship connectivity directly rather than requiring an indexed join for every hop. This helps local traversals, but the work still grows with the number of relationships explored.

Cypher describes graph patterns declaratively. The planner chooses operations such as index seeks, relationship expansions, filters, and aggregations. In an interview, describe the starting-node lookup, relationship types, hop bounds, and expected fan-out rather than saying that graph queries are inherently fast.

Neo4j provides ACID transactions backed by transaction logging and locking. Its default isolation level is read committed, not serializable. Constraints can enforce identifiers and other invariants, but application logic must still handle concurrent updates, deadlocks, and retries.

In a standard replicated deployment, each database has a leader that coordinates writes. Primary members replicate transaction state using Raft, while secondaries provide additional read capacity. Drivers use routing information to send reads and writes to suitable servers; adding read replicas does not divide the graph or increase a single database's write capacity proportionally.

## What it gives you in a design

- **Multi-hop relationship queries.** Express paths, shared neighbors, and reachability without manually chaining many joins. The benefit is strongest when traversal depth and fan-out remain bounded.
- **Properties on relationships.** Store attributes such as validity periods, confidence, or compatibility conditions directly on a connection. A relationship's existence alone does not mean it satisfies every business rule.
- **Indexes and constraints.** Indexes locate starting nodes efficiently, and uniqueness constraints protect stable application identifiers. Available constraint types depend on edition and version.
- **Transactional graph updates.** Update related nodes and relationships atomically within a database transaction. This is useful when creating an entity and its connections must succeed or fail together.
- **Causal consistency with bookmarks.** Pass bookmarks between related transactions so a later read waits for the required earlier write to become visible. This supports read-your-writes across routed connections without claiming that every replica is always current.
- **Graph analytics tooling.** The separate Graph Data Science library supports algorithms such as community detection and similarity over graph projections. Budget projection memory and refresh work separately from online transactional queries.

## Scaling, replication and failure

Start with the graph's working set, index footprint, and traversal cost. Page-cache misses, high-degree nodes, and large intermediate results can dominate latency. Profile representative queries and bound expansion depth, relationship types, and returned results.

Replication improves availability and read capacity, but each replica of a standard database holds that database's graph. Writes still pass through its leader. A voting majority is required for write progress, so a minority partition cannot continue accepting writes independently.

Partitioning a graph is difficult because traversals can cross ownership boundaries. Tenant-local or otherwise disconnected subgraphs are useful partition candidates; globally connected graphs create cross-partition coordination and network traffic. Neo4j's multi-database, composite-database, and sharding options depend on product and version, so state the exact deployment model rather than assuming a replicated cluster automatically shards data.

Secondary reads can lag behind committed writes. Use bookmarks when a request depends on an earlier transaction, and define acceptable staleness for unrelated reads. During failover, expect temporary errors and retry only retry-safe operations; a lost response can leave the client uncertain whether its transaction committed.

## Limits and defaults worth knowing

- **Default transaction isolation:** Read committed. Non-repeatable reads can occur; ACID does not imply serializable execution.
- **Relationship structure:** A relationship has exactly one start node, one end node, and one relationship type. Model a connection among several participants with an intermediate node.
- **Voting majority:** A standard Raft group with three voting primary members needs two for a majority and can tolerate one primary failure while retaining quorum. Secondaries do not add votes.
- **Write coordination:** A standard replicated database has one leader coordinating writes at a time. Additional replicas do not create independent writers for that database.
- **Transaction timeout:** Configurable through database settings and transaction APIs. Effective limits depend on deployment configuration and managed-service policies.

## Use it when

- Core requests follow several relationship types or require shared-neighbor and path queries.
- Connections carry meaningful attributes, conditions, or validity periods.
- The graph can be queried from selective starting nodes with bounded depth and fan-out.
- Relationship-heavy queries change frequently enough that maintaining many specialized relational queries or materialized views becomes costly.
- A compatibility or recommendation subsystem needs graph traversal, while other stores handle transactions, search, or media.

## Avoid it when

- Most requests are simple key lookups, ordinary tabular joins, or scans that an existing relational database already handles well.
- The main workload is large analytical aggregation over events rather than selective relationship traversal.
- The requirement is unrestricted, low-latency traversal through a globally connected graph partitioned across many machines.
- The design requires independent multi-region writes to the same data with automatic conflict merging.

## What interviewers ask about it

### Why not use PostgreSQL with an edge table?

For one-hop lookups or a small number of fixed joins, PostgreSQL may be simpler and sufficient. Neo4j becomes more compelling when variable relationship patterns and multi-hop traversals are central, but the decision should follow representative query plans and operational requirements.

### How do you prevent a high-degree node from making a query expensive?

Start from the most selective indexed anchor, restrict relationship types, and impose explicit depth and work limits. A final LIMIT does not necessarily bound expansion or sorting work, so inspect the execution plan and consider precomputed results for expensive queries.

### How would you scale writes?

First reduce transaction size, contention, and unnecessary index maintenance, then identify whether the graph has natural partition boundaries. Read replicas do not solve leader write saturation, and cross-partition traversals must be accounted for in any sharded design.

### How does a user read a relationship immediately after creating it?

Carry the write transaction's bookmark into the dependent read, using driver bookmark support. An arbitrary read sent to a lagging secondary without that dependency may return an older view.

### What happens if the leader fails during a write?

With a voting majority available, the cluster can elect another leader, but clients may see transient failures during the transition. If the commit response was lost, use an application operation ID or another deduplication mechanism rather than blindly repeating a non-idempotent write.

### Would you use the graph as the source of truth or as a projection?

Use it as the source of truth when graph updates and their transactional invariants are central to the application. Otherwise, build a projection from an authoritative store through CDC or an outbox, and explicitly handle lag, replay, deletions, and permission changes.

## Common mistakes

- Choosing a graph database merely because the data contains relationships, without identifying queries that benefit from graph traversal.
- Treating bounded hop count as bounded work even when each hop can expand through thousands of neighbors.
- Assuming replication automatically shards the graph or increases write throughput.
- Assuming ACID means serializable transactions, or that every routed read immediately observes the latest write.

## Alternatives

- **PostgreSQL:** Wins when relational transactions dominate and relationship queries use a manageable number of joins or recursive queries. It also avoids adding another database solely for occasional traversals.
- **Key-value or wide-column store with adjacency lists:** Wins for predictable, high-volume one-hop lookups with clear partition keys. The application takes responsibility for reverse edges, multi-hop orchestration, and consistency between copies.
- **Amazon Neptune:** Fits when a managed graph service in AWS is preferred, especially when RDF/SPARQL support matters. Compare query support, transaction semantics, and scaling behavior rather than assuming Neo4j compatibility.
- **Materialized views in an existing serving store:** Win when the application needs a small set of fixed answers, such as precomputed recommendations or compatibility lists. Reads become simpler, at the cost of refresh lag and maintenance logic.

## Interview questions where it comes up

- [Design a parts compatibility feature](https://sysround.com/questions/design-parts-compatibility): A graph can represent sparse compatibility relationships and their evidence, provided queries evaluate conditions rather than treating every path as valid compatibility.
- [Design a news feed like Facebook](https://sysround.com/questions/design-news-feed): A graph can support social-neighborhood queries and recommendation candidates, while feed generation and delivery usually need separate serving structures.
- [Design Dropbox or Google Drive](https://sysround.com/questions/design-dropbox): Graph traversal can help resolve shared-subtree relationships and inherited permissions, but permission revocation must remain correct despite cached or projected graph data.

## FAQ

### What is the difference between Neo4j and a relational database?

Neo4j models connections as stored relationships and provides a query language built around graph patterns. Relational databases model connections through keys and joins. Neither is universally faster; selective multi-hop traversal is a stronger reason to choose Neo4j than the mere presence of relationships.

### Does Neo4j scale horizontally?

Neo4j can spread database replicas across servers for availability and read capacity. That is different from partitioning one graph to scale storage and writes. Distributed graph options vary by product and version, and cross-partition traversals remain an important design cost.

### Is Neo4j a good database for a social network?

It can fit mutual-connection queries, relationship exploration, and candidate generation for recommendations. It is not automatically the best store for timelines, message history, counters, or media. A strong design assigns those workloads to suitable stores and explains how the graph stays current.

## Related concepts

- [Database indexing](https://sysround.com/concepts/database-indexing)
- [Partitioning strategies](https://sysround.com/concepts/data-partitioning)
- [Database replication](https://sysround.com/concepts/replication)
- [Causal consistency](https://sysround.com/concepts/causal-consistency)
- [Recommendation systems](https://sysround.com/concepts/recommendation-systems)


---
SysRound (https://sysround.com) is an AI practice tool for system design interviews: a voice or typed AI interviewer, a shared whiteboard, then feedback on every skill and a model answer. Its feedback is AI-generated and can be wrong.
