Variable-Length Paths, Shortest Paths and Transactions

Article · 8:00

Variable-length patterns and bounding them, shortest path algorithms, subqueries and CALL, transaction scope, driver sessions and retry.

Variable-length paths are what you came for and they are the hazard. MATCH (a)-[:KNOWS*1..3]->(b) finds everything one to three hops away, and it is the query shape no relational database can express cleanly.

The danger is specific and worth stating precisely. MATCH (a)-[*]-(b) has no upper bound, no relationship type and no direction. On a connected graph, the number of paths grows roughly as the average degree to the power of the hop count - so on a graph with an average degree of 30, six hops is around 729 million paths, and the query will consume the heap and take the server with it. This is not a tuning problem; it is a query that cannot be allowed to run.

Four bounds, and you want all of them:

  1. An upper hop limit, always: *1..3, never *.
  2. A relationship type: [:KNOWS*1..3], not [*1..3].
  3. A direction where the semantics allow it, which halves the branching at every hop.
  4. An anchored start that an index serves, so the traversal begins at one node rather than all of them.

Add a LIMIT, and in Enterprise or Aura a transaction timeout as a backstop.

shortestPath and allShortestPaths are special-cased and efficient - they use a bidirectional search rather than exploring every path. shortestPath still needs an upper bound in practice, because on a disconnected pair it explores until it exhausts the search space. For weighted shortest paths and anything more sophisticated, the Graph Data Science library has proper implementations (Dijkstra, A*, Yen's), and the right pattern there is to project a subgraph into memory and run the algorithm on it.

Subqueries (CALL { ... }) scope a piece of query, which is how you do per-row aggregation, unions and - importantly - CALL { ... } IN TRANSACTIONS OF n ROWS, which batches a large write into many transactions so it does not exhaust the heap. That clause is the answer to "my bulk update ran out of memory".

Transactions and sessions. A transaction is ACID and scoped to one database. The driver offers auto-commit (one statement, no retry), transaction functions (a lambda the driver retries on transient errors - this is the one to use), and explicit transactions (full control, no retry). The rule: use transaction functions, make the function idempotent, and do not hold a transaction open across application logic. A long-running write transaction holds locks and grows the transaction state in the heap.

Locking is worth knowing: Neo4j takes write locks on nodes and relationships it modifies, and a deadlock between two transactions touching the same nodes in different orders produces a DeadlockDetectedException, which is transient and retryable - so transaction functions handle it for you, and explicit transactions do not.

Laboratory exercise 3 - paths and concurrency.

Build a fraud-scoring service and run at least 100 concurrent clients.

Demonstrate the unbounded traversal safely. On a disposable instance with a small heap and a transaction timeout configured, run an unbounded MATCH (a)-[*]-(b) and record what happens - the timeout, the memory, the error. Do this on a throwaway container, not on anything you care about. Then add each of the four bounds in turn and record the database hits at each step. The progression from "will not finish" to "two milliseconds" is the module's main artefact.

Implement shortestPath between two accounts and compare it with a bounded variable-length path finding the same connection.

Implement the fraud ring query - people connected through shared attributes within three hops - and profile it.

Use CALL { ... } IN TRANSACTIONS to perform a bulk property update over a million nodes, and compare it with the same update in one transaction, recording the memory used by each.

Demonstrate a deadlock: two concurrent transactions updating two nodes in opposite orders. Capture the exception, then show a transaction function retrying it successfully.

Finally, measure the three transaction styles under concurrency: auto-commit, transaction function and explicit, recording throughput and failure rate.

Deliverable: the service, the unbounded traversal evidence with its safety configuration, the four-bound progression with database hits at each step, the shortest-path comparison, the profiled fraud ring query, the batched-against-single transaction memory comparison, the deadlock demonstrated and retried, and the three transaction styles measured.

// ==================================================================
// *** THE UNBOUNDED TRAVERSAL. Read this before you write one. ***
// ==================================================================
// MATCH (a)-[*]-(b) RETURN a, b;
//
//   NO upper bound. NO relationship type. NO direction. NO anchor.
//
//   The number of paths grows roughly as (average degree) ^ (hops).
//   On a graph with average degree 30:
//     3 hops      27,000 paths
//     4 hops     810,000
//     5 hops  24,300,000
//     6 hops 729,000,000     <- the heap is gone
//
// *** THIS IS NOT A TUNING PROBLEM. It is a query that cannot be
// *** allowed to run. *** Demonstrate it ON A THROWAWAY CONTAINER
// with a small heap and a timeout set - never on anything you care
// about.

// ==================================================================
// THE FOUR BOUNDS. You want all of them.
// ==================================================================
// 0. The hazard:
MATCH (a)-[*]-(b) RETURN count(*);

// 1. AN UPPER HOP LIMIT. Always. `*` is never acceptable.
MATCH (a)-[*1..3]-(b) RETURN count(*);

// 2. A RELATIONSHIP TYPE.
MATCH (a)-[:TRANSFERRED*1..3]-(b) RETURN count(*);

// 3. A DIRECTION, which halves the branching at EVERY hop.
MATCH (a)-[:TRANSFERRED*1..3]->(b) RETURN count(*);

// 4. AN ANCHORED START an index serves, so the traversal begins at
//    ONE node rather than all of them.
MATCH (a:Account {id: 'acc-1'})-[:TRANSFERRED*1..3]->(b:Account)
RETURN b.id, length(()-[:TRANSFERRED*1..3]->()) AS hops
LIMIT 100;
//
// Record the db hits at each step. The progression from "will not
// finish" to "two milliseconds" is the module's main artefact.

// Multiple types, and the pattern a fraud graph actually uses:
MATCH path = (p:Person {id: 'p-0001'})
             -[:LIVES_AT|USED_DEVICE|HAS_PHONE|OWNS*1..4]-
             (other:Person)
WHERE other <> p
RETURN other.id, [n IN nodes(path) | coalesce(n.id, labels(n)[0])] AS via,
       length(path) AS hops
ORDER BY hops LIMIT 50;

// A BACKSTOP, in Enterprise or Aura - set it even when every query
// is bounded, because the one that is not will be written eventually:
//   db.transaction.timeout=30s
//   dbms.memory.transaction.total.max=2g
//   dbms.memory.transaction.max=500m
CALL dbms.listTransactions()
YIELD transactionId, currentQuery, elapsedTimeMillis, allocatedBytes
WHERE elapsedTimeMillis > 10000
RETURN transactionId, currentQuery, elapsedTimeMillis, allocatedBytes;
CALL dbms.killTransaction('neo4j-transaction-42');

// ==================================================================
// shortestPath: special-cased and efficient. And still bound it.
// ==================================================================
MATCH (a:Account {id:'acc-1'}), (b:Account {id:'acc-9999'}),
      p = shortestPath((a)-[:TRANSFERRED*..8]-(b))
RETURN [n IN nodes(p) | n.id] AS route, length(p) AS hops;
//                                 ^^^ AN UPPER BOUND, even here.
//   It uses a BIDIRECTIONAL search rather than exploring every path -
//   genuinely efficient. But on a DISCONNECTED pair it explores
//   until it exhausts the search space, so the bound matters.

MATCH (a:Person {id:'p-1'}), (b:Person {id:'p-2'}),
      p = allShortestPaths((a)-[*..6]-(b))
RETURN p LIMIT 10;

// WEIGHTED shortest paths and anything more sophisticated belong to
// the Graph Data Science library, where the pattern is to PROJECT a
// subgraph into memory and run the algorithm on it (Module 4).

// ==================================================================
// SUBQUERIES: scope, per-row aggregation, and BATCHED WRITES.
// ==================================================================
MATCH (p:Person)
CALL {
  WITH p
  MATCH (p)-[:OWNS]->(:Account)-[t:TRANSFERRED]->()
  WHERE t.at > datetime() - duration('P7D')
  RETURN sum(t.amount) AS weekly_out
}
WITH p, weekly_out WHERE weekly_out > 50000
RETURN p.id, weekly_out ORDER BY weekly_out DESC;
//   A per-row aggregation without a correlated-subquery workaround.

// *** CALL { ... } IN TRANSACTIONS: the answer to "my bulk update
// *** ran out of memory". ***
MATCH (p:Person)
CALL { WITH p SET p.risk_score = 0 } IN TRANSACTIONS OF 10000 ROWS;
//   One transaction per 10,000 rows, so the transaction state never
//   grows beyond that. Compare the memory with the single-transaction
//   version in the lab:
//     one transaction, 1,000,000 nodes  -> heap exhausted
//     IN TRANSACTIONS OF 10000          -> steady, bounded
//
//   NOTE: it is NOT atomic overall - a failure part-way leaves
//   earlier batches committed. That is the trade, and a restartable
//   update (one that can be re-run) is the way to live with it.

UNWIND $rows AS row
MERGE (p:Person {id: row.id})
  ON CREATE SET p.name = row.name
  ON MATCH  SET p.updated_at = datetime();
//   UNWIND + a parameter list is how you batch-load from a driver:
//   ONE query, many rows, one round trip. Never a query per row.

// ==================================================================
// TRANSACTIONS AND SESSIONS: use TRANSACTION FUNCTIONS.
// ==================================================================
//   AUTO-COMMIT        one statement, NO RETRY
//     session.run("MATCH ...")
//
//   *** TRANSACTION FUNCTION - THE ONE TO USE. The driver RETRIES
//   *** on transient errors (deadlock, leader change, a brief
//   *** unavailability): ***
//     session.execute_write(lambda tx: tx.run("MERGE ...", **params))
//     session.execute_read(lambda tx: tx.run("MATCH ...").data())
//
//   EXPLICIT            full control, NO RETRY
//     with session.begin_transaction() as tx: ...
//
// THE RULES:
//   * use transaction functions
//   * *** MAKE THE FUNCTION IDEMPOTENT *** - it may run more than
//     once, so MERGE rather than CREATE, and no side effects inside
//   * *** DO NOT HOLD A TRANSACTION OPEN ACROSS APPLICATION LOGIC ***
//     - it holds locks and grows transaction state in the heap
//   * route reads to replicas with execute_read (Module 5)

// ==================================================================
// LOCKING AND DEADLOCKS - transient, and retryable.
// ==================================================================
// Neo4j takes WRITE LOCKS on the nodes and relationships it
// modifies. Two transactions touching the same nodes in DIFFERENT
// ORDERS deadlock:
//
//   tx1: MATCH (a {id:'1'}), (b {id:'2'}) SET a.x=1, b.x=1
//   tx2: MATCH (a {id:'2'}), (b {id:'1'}) SET a.x=2, b.x=2
//
//   -> Neo.TransientError.Transaction.DeadlockDetected
//
// *** IT IS TRANSIENT AND RETRYABLE, so a TRANSACTION FUNCTION
// *** HANDLES IT FOR YOU and an explicit transaction does not. ***
// That is the concrete reason for the rule above, and the lab
// demonstrates both.
//
// Reduce them by design: lock in a CONSISTENT ORDER (sort the ids
// before updating), and keep write transactions short.
CALL dbms.listTransactions() YIELD transactionId, status, currentQuery
WHERE status <> 'Running' RETURN transactionId, status, currentQuery;

Discussion

No questions on this topic yet. Sign in to ask the first one.