Drivers, Sessions, Transactions

Sessions are cheap, transactions cost — and managed transactions retry on transient errors.

0/4 done

Overview

Drivers, Sessions, Transactions

Sessions are cheap, transactions cost — and managed transactions retry on transient errors.

Why it matters

The driver gives you sessions (per-thread) and transactions (per-unit-of-work). Read transactions can be routed to followers; write transactions go to the leader.

Going deeper

The driver layers three things:

  • Session — a lightweight, per-thread context that also carries causal bookmarks. Cheap to open; don't share one across threads.
  • Transaction — the unit of work. Reads can route to followers; writes go to the leader.
  • Managed (transaction-function) transactionssession.execute_write(fn) / execute_read(fn) — automatically retry on transient errors (deadlock, leader re-election) with backoff.
def add_order(tx, cust_id, total):
    tx.run('MATCH (c:Customer {id:$id}) '
           'CREATE (c)-[:PLACED]->(:Order {total:$t})', id=cust_id, t=total)

with driver.session() as s:
    s.execute_write(add_order, 'c1', 42.0)

Prefer managed transactions for almost everything: the retry logic is exactly the resilience you'd otherwise hand-roll, and they keep the read/write routing correct.

Analogy

Sessions and transactions are a phone line and a single call. Opening a line (session) is cheap; what costs is the call itself (transaction). A managed transaction is calling through an operator who, if the line drops mid-sentence (deadlock, leader switch), quietly redials and reconnects you — instead of you getting a dial tone and an error.

Pitfalls — what breaks when this is weak

  • Explicit BEGIN/COMMIT everywhere. No automatic retry on transient errors. Fix: use managed execute_write/execute_read.
  • Sharing a session across threads. Sessions aren't thread-safe. Fix: one session per unit of work/thread.
  • Non-idempotent write functions. A retried transaction runs twice. Fix: make the function idempotent (MERGE, not blind CREATE).

Make it stick

Use the prompts below to anchor drivers, sessions, transactions to a real graph you own.

  • Where do you use explicit transactions that should be managed transaction functions for free retry?
  • Are your write functions idempotent enough to survive an automatic retry running them twice?
  • Is any session being shared across threads in your driver code?

Reading in progress · 0 of 4 activities done