Run your own transactions

When querying the database with executeQuery(), the driver automatically creates a transaction. A transaction is a unit of work that is either committed in its entirety or rolled back on failure. You can include multiple Cypher statements in a single query, as for example when using MATCH and MERGE in sequence to update the database, but you cannot have multiple queries and interleave some client-logic in between them.

For these more advanced use-cases, the driver provides functions to take full control over the transaction lifecycle. These are called managed transactions, and you can think of them as a way of unwrapping the flow of executeQuery() and being able to specify its desired behavior in more places.

Obtain a session

Before running a transaction, you need to obtain a session. Sessions act as concrete query channels between the driver and the server. In particular, sessions borrow connections from the connection pool as needed, and ensure causal consistency is enforced.

Sessions are created with the method Driver.session(). It takes a single (optional) object parameter, with the property database allowing to specify the target database. For further parameters, see Session configuration.

session = driver.session({ database: 'neo4j' })

Session creation is a lightweight operation, so sessions can be created and destroyed without significant cost. Always close sessions when you are done with them.

Sessions are not thread safe: you can share the main Driver object across threads, but make sure each thread creates its own sessions.

Run a managed transaction

A transaction can contain any number of queries. As Neo4j is ACID compliant, queries within a transaction will either be executed as a whole or not at all: you cannot get a part of the transaction succeeding and another failing. Use transactions to group together related queries which work together to achieve a single logical database operation.

A managed transaction is created with the methods Session.executeRead() and Session.executeWrite(), depending on whether you want to retrieve data from the database or alter it. Both methods take a transaction function callback (1), which is responsible of actually carrying out the queries and processing the result. Queries are specified with the method (2), where you provide a Cypher query (3) and an object of query parameters (4) which returns a Result object. You can then process the result records and query summary (5).

Retrieve people whose name starts with Al.
let session, result
session = driver.session({ database: 'neo4j' })
result = await session.executeRead(async tx => { (1)
  return await`  (2)
    MATCH (p:Person) WHERE STARTS WITH $filter  (3)
    RETURN as name ORDER BY name
    `, {filter: 'Al'}  (4)
  `The query \`${result.summary.query.text}\`` +
  `returned ${result.records.length} nodes.\n`
for(let record in result.records) {  (5)

Do not hardcode or concatenate parameters directly into the query. Use query parameters instead, both for performance and security reasons.

Within a transaction function, a return statement results in the transaction being committed, while the transaction is automatically rolled back if an exception is raised.

A transaction with multiple queries, client logic, and potential roll backs
const neo4j = require('neo4j-driver');

(async () => {
  const URI = 'neo4j://localhost'
  const USER = 'neo4j'
  const PASSWORD = 'verysecret'
  let driver, session
  let employeeThreshold = 10

  try {
    driver = neo4j.driver(URI, neo4j.auth.basic(USER, PASSWORD))
    await driver.verifyConnectivity()
  } catch(err) {
    console.log(`-- Connection error --\n${err}\n-- Cause --\n${err.cause}`)

  session = driver.session({ database: 'neo4j' })
  for(let i=0; i<100; i++) {
    const name = `Neo-${i.toString()}`
    const orgId = await session.executeWrite(async tx => {
      let result, orgInfo

      // Create new Person node with given name, if not already existing
        MERGE (p:Person {name: $name})
        RETURN AS name
        `, { name: name }

      // Obtain most recent organization ID and number of people linked to it
      result = await`
        MATCH (o:Organization)
        RETURN AS id, COUNT{(p:Person)-[r:WORKS_FOR]->(o)} AS employeesN
        ORDER BY o.createdDate DESC
        LIMIT 1
      if(result.records.length > 0) {
        orgInfo = result.records[0]

      if(orgInfo != undefined && orgInfo['employeesN'] == 0) {
        throw new Error('Most recent organization is empty.')
        // Transaction will roll back -> not even Person is created!

      // If org does not have too many employees, add this Person to that
      if(orgInfo != undefined && orgInfo['employeesN'] < employeeThreshold) {
        result = await`
          MATCH (o:Organization {id: $orgId})
          MATCH (p:Person {name: $name})
          MERGE (p)-[r:WORKS_FOR]->(o)
          RETURN $orgId AS id
          `, { orgId: orgInfo['id'], name: name }

      // Otherwise, create a new Organization and link Person to it
      } else {
        result = await`
          MATCH (p:Person {name: $name})
          CREATE (o:Organization {id: randomuuid(), createdDate: datetime()})
          MERGE (p)-[r:WORKS_FOR]->(o)
          RETURN AS id
          `, { name: name }

      // Return the Organization ID to which the new Person ends up in
      return result.records[0].get('id')
    console.log(`User ${name} added to organization ${orgId}`)
  await session.close()
  await driver.close()

Should a transaction fail for a reason that the driver deems transient, it automatically retries to run the transaction function (with an exponentially increasing delay). For this reason, transaction functions should produce the same effect when run several times (idempotent), because you do not know upfront how many times they are going to be executed. In practice, this means that you should not edit nor rely on globals, for example. Note that although transaction functions might be executed multiple times, the queries inside it will always run only once.

A session can chain multiple transactions, but only one single transaction can be active within a session at any given time. This means that a query must be completed before the next one can run, and it is the reason why the previous examples all use the async/await syntax. To maintain multiple concurrent transactions, see how to run asynchronous queries.

Further transaction function configuration

Both executeRead and executeWrite take a second optional parameter of type TransactionConfig, which allows to supply further configuration parameters. You can specify:

  • a transaction timeout (in milliseconds). Transactions that run longer will be terminated by the server. The default value is set on the server side.

  • an object of metadata that gets attached to the transaction. These metadata get logged in the server query.log, and are visible in the output of the SHOW TRANSACTIONS YIELD * Cypher command. Use this to tag transactions.

let session = driver.session({ database: 'neo4j' })
const people_n = await session.executeRead(
  async tx => { return await'MATCH (a:Person) RETURN count(a)') },
  { timeout: 5000, metadata: {'app_name': 'people'} }  // TransactionConfig

Run an explicit transaction

You can achieve full control over transactions by manually beginning one with the method Session.beginTransaction(). You run queries inside an explicit transaction with the method, as you do in transaction functions.

let session = driver.session({ database: 'neo4j' })
let transaction = await session.beginTransaction()

// await'<QUERY 1>')
// await'<QUERY 2>')
// ...

await transaction.close()
await session.close()

The behavior and lifetime of an explicit transaction is controlled through the methods Transaction.commit(), Transaction.rollback(), or Transaction.close().

Explicit transactions are most useful for applications that need to distribute Cypher execution across multiple functions for the same transaction, or for applications that need to run multiple queries within a single transaction but without the automatic retries provided by managed transactions.

Example stub with an explicit transaction involving external APIs
async function transferToOtherBank(driver, customerId, otherBankId, amount) {
  const session = driver.session({ database: 'neo4j' })
  const tx = await session.beginTransaction()
  try {
    if(! checkCustomerBalance(tx, customerId, amount))

    try {
      decreaseCustomerBalance(tx, customerId, amount)
      await tx.commit()
    } catch (error) {
      requestInspection(customerId, otherBankId, amount, e)
      throw error  // roll back

    await otherBankTransferApi(customerId, otherBankId, amount)
    // Now the money has been transferred => can't rollback anymore
    // (cannot rollback external services interactions)
  } finally {
    await tx.close()  // rolls back if not yet committed
    await session.close()

async function checkCustomerBalance(tx, customerId, amount) {
  result = await`
    MATCH (c:Customer {id: $id})
    RETURN c.balance >= $amount AS sufficient
    `, { id: customerId, amount: amount }
  return result.records[0].get('sufficient')

async function otherBankTransferApi(customerId, otherBankId, amount) {
  // make some API call to other bank

async function decreaseCustomerBalance(tx, customerId, amount) {
    MATCH (c:Customer {id: $id})
    SET c.balance = c.balance - $amount
    `, { id: customerId, amount: amount }

async function requestInspection(customerId, otherBankId, amount, error) {
  // manual cleanup required; log this or similar
  console.log('WARNING: transaction rolled back due to exception:')

Session configuration

When creating a session, you can provide an optional parameter of type SessionConfig to specify session configuration values.

Database selection

You should always specify the database explicitly with the database parameter, even on single-database instances. This allows the driver to work more efficiently, as it does not have to resolve the home database first. If no database is given, the user home database set in the Neo4j instance settings is used.

const session = driver.session({
  database: 'neo4j'

Request routing

In a cluster environment, all sessions are opened in write mode, routing them to the leader. You can change this by explicitly setting the defaultAccessMode parameter to either neo4j.session.READ or neo4j.session.WRITE. Note that .executeRead() and .executeWrite() automatically override the session’s default access mode.

const session = driver.session({
  database: 'neo4j',
  defaultAccessMode: neo4j.session.READ

Although executing a write query in read mode likely results in a runtime error, you should not rely on this for access control. The difference between the two modes is that read transactions are routed to any node of a cluster, whereas write ones are directed to the leader. Still, depending on the server version and settings, the server might allow none, some, or all write statements to be executed even in read transactions.

Similar remarks hold for the .executeRead() and .executeWrite() methods.

Run queries as a different user (impersonation)

You can execute a query under the security context of a different user with the parameter impersonatedUser, specifying the name of the user to impersonate. For this to work, the user under which the Driver was created needs to have the appropriate permissions. Impersonating a user is cheaper than creating a new Driver object.

const session = driver.session({
    database: 'neo4j',
    impersonatedUser: 'somebodyElse'

When impersonating a user, the query is run within the complete security context of the impersonated user and not the authenticated user (i.e., home database, permissions, etc.).

Close sessions

Each connection pool has a finite number of sessions, so if you open sessions without ever closing them, your application could run out of them. It is thus important to be adamant in always closing sessions when you are done with them, so that they can be returned to the connection pool to be later reused. The best way is to wrap session usage in a try/finally block, calling session.close() in the finally clause.

let session = driver.session({database: 'neo4j'})
try {
  // use session to run queries
} finally {
  await session.close()



A Long Term Support release is one guaranteed to be supported for a number of years. Neo4j 4.4 is LTS, and Neo4j 5 will also have an LTS version.


Aura is Neo4j’s fully managed cloud service. It comes with both free and paid plans. Every Neo4j-backed application requires a Driver object.


Cypher is Neo4j’s graph query language that lets you retrieve data from the graph. It is like SQL, but for graphs.


Awesome Procedures On Cypher (APOC) is a library of (many) functions that can not be easily expressed in Cypher itself.


Bolt is the protocol used for interaction between Neo4j instances and drivers. It listens on port 7687 by default.


Atomicity, Consistency, Isolation, Durability (ACID) are properties guaranteeing that database transactions are processed reliably. An ACID-compliant DBMS ensures that the data in the database remains accurate and consistent despite failures.

eventual consistency

A database is eventually consistent if it provides the guarantee that all cluster members will, at some point in time, store the latest version of the data.

causal consistency

A database is causally consistent if read and write queries are seen by every member of the cluster in the same order. This is stronger than eventual consistency.


The null marker is not a type but a placeholder for absence of value. For more information, see Cypher Manual — Working with null.


A transaction is a unit of work that is either committed in its entirety or rolled back on failure. An example is a bank transfer: it involves multiple steps, but they must all succeed or be reverted, to avoid money being subtracted from one account but not added to the other.


Backpressure is a force opposing the flow of data. It ensures that the client is not being overwhelmed by data faster than it can handle.

transaction function

A transaction function is a callback executed by an executeRead or executeWrite call. The driver automatically re-executes the callback in case of server failure.


A Driver object holds the details required to establish connections with a Neo4j database.