4.2. Interaction cycle

All database operations that access the graph, indexes, or the schema must be performed in a transaction. Transactions are single-threaded, confined and independent. Multiple transactions can be started in a single thread, and they will be independent from each other.

The interaction cycle of working with transactions looks like this:

  1. Begin a transaction.
  2. Perform database operations.
  3. Commit or roll back the transaction.

It is very important to finish each transaction. The transaction will not release the locks or memory it has acquired until it has been finished.

The idiomatic use of transactions in Neo4j is to use a try-with-resources statement and declare transaction as one of the resources. Then start the transaction and try to perform graph operations. The last operation in the try block should commit or roll back the transaction, depending on the business logic. In this scenario, try-with-resources is used as a guard against unexpected exceptions and as an additional safety mechanism to ensure that the transaction gets closed no matter what happens inside the statement block. All non-committed transactions will be rolled back as part of resource cleanup at the end of the statement. In case a transaction has been explicitly committed or rolled back, resource cleanup will not be required and the transaction closure will be an empty operation.

All modifications performed in a transaction are kept in memory. This means that very large updates must be split into several transactions in order to avoid running out of memory.