Coordinate parallel transactions

When working with a Neo4j cluster, causal consistency is enforced by default in most cases, which guarantees that a query is able to read changes made by previous queries. The same does not happen by default for multiple transactions running in parallel though. In that case, you can use bookmarks to have one transaction wait for the result of another to be propagated across the cluster before running its own work. This is not a requirement, and you should only use bookmarks if you need casual consistency across different transactions, as waiting for bookmarks can have a negative performance impact.

A bookmark is a token that represents some state of the database. By passing one or multiple bookmarks along with a query, the server will make sure that the query does not get executed before the represented state(s) have been established.

Bookmarks with .executableQuery()

When querying the database with .executableQuery(), the driver manages bookmarks for you. In this case, you have the guarantee that subsequent queries can read previous changes with no further action.

driver.executableQuery("<QUERY 1>").execute();

// subsequent .executableQuery() calls will be causally chained

driver.executableQuery("<QUERY 2>").execute();  // can read result of <QUERY 1>
driver.executableQuery("<QUERY 3>").execute();  // can read result of <QUERY 2>

To disable bookmark management and causal consistency, use .withBookmarkManager(null) in the query configuration.

driver.executableQuery("<QUERY>")
    .withConfig(QueryConfig.builder().withBookmarkManager(null).build())
    .execute();

Bookmarks within a single session

Bookmark management happens automatically for queries run within a single session, so that you can trust that queries inside one session are causally chained.

try (var session = driver.session(SessionConfig.builder().withDatabase("neo4j").build())) {
    session.executeWriteWithoutResult(tx -> tx.run("<QUERY 1>"));
    session.executeWriteWithoutResult(tx -> tx.run("<QUERY 2>"));  // can read QUERY 1
    session.executeWriteWithoutResult(tx -> tx.run("<QUERY 3>"));  // can read QUERY 1,2
}

Bookmarks across multiple sessions

If your application uses multiple sessions, you may need to ensure that one session has completed all its transactions before another session is allowed to run its queries.

In the example below, sessionA and sessionB are allowed to run concurrently, while sessionC waits until their results have been propagated. This guarantees the Person nodes sessionC wants to act on actually exist.

Coordinate multiple sessions using bookmarks
package demo;

import java.util.Map;
import java.util.List;
import java.util.ArrayList;

import org.neo4j.driver.AuthTokens;
import org.neo4j.driver.Bookmark;
import org.neo4j.driver.Driver;
import org.neo4j.driver.GraphDatabase;
import org.neo4j.driver.SessionConfig;
import org.neo4j.driver.TransactionContext;

public class App {

    private static final int employeeThreshold = 10;

    public static void main(String... args) {
        final String dbUri = "<URI for Neo4j database>";
        final String dbUser = "<Username>";
        final String dbPassword = "<Password>";

        try (var driver = GraphDatabase.driver(dbUri, AuthTokens.basic(dbUser, dbPassword))) {
            createSomeFriends(driver);
        }
    }

    public static void createSomeFriends(Driver driver) {
        List<Bookmark> savedBookmarks = new ArrayList<>();  // to collect the sessions' bookmarks

        // Create the first person and employment relationship
        try (var sessionA = driver.session(SessionConfig.builder().withDatabase("neo4j").build())) {
            sessionA.executeWriteWithoutResult(tx -> createPerson(tx, "Alice"));
            sessionA.executeWriteWithoutResult(tx -> employ(tx, "Alice", "Wayne Enterprises"));
            savedBookmarks.addAll(sessionA.lastBookmarks());  (1)
        }

        // Create the second person and employment relationship
        try (var sessionB = driver.session(SessionConfig.builder().withDatabase("neo4j").build())) {
            sessionB.executeWriteWithoutResult(tx -> createPerson(tx, "Bob"));
            sessionB.executeWriteWithoutResult(tx -> employ(tx, "Bob", "LexCorp"));
            savedBookmarks.addAll(sessionB.lastBookmarks());  (1)
        }

        // Create a friendship between the two people created above
        try (var sessionC = driver.session(SessionConfig.builder()
            .withDatabase("neo4j")
            .withBookmarks(savedBookmarks)  (2)
            .build())) {
            sessionC.executeWriteWithoutResult(tx -> createFriendship(tx, "Alice", "Bob"));
            sessionC.executeWriteWithoutResult(tx -> printFriendships(tx));
        }
    }

    // Create a person node
    static void createPerson(TransactionContext tx, String name) {
        tx.run("MERGE (:Person {name: $name})", Map.of("name", name));
    }

    // Create an employment relationship to a pre-existing company node
    // This relies on the person first having been created.
    static void employ(TransactionContext tx, String personName, String companyName) {
        tx.run("""
            MATCH (person:Person {name: $personName})
            MATCH (company:Company {name: $companyName})
            CREATE (person)-[:WORKS_FOR]->(company)
            """, Map.of("personName", personName, "companyName", companyName)
        );
    }

    // Create a friendship between two people
    static void createFriendship(TransactionContext tx, String nameA, String nameB) {
        tx.run("""
            MATCH (a:Person {name: $nameA})
            MATCH (b:Person {name: $nameB})
            MERGE (a)-[:KNOWS]->(b)
            """, Map.of("nameA", nameA, "nameB", nameB)
        );
    }

    // Retrieve and display all friendships
    static void printFriendships(TransactionContext tx) {
        var result = tx.run("MATCH (a)-[:KNOWS]->(b) RETURN a.name, b.name");
        while (result.hasNext()) {
            var record = result.next();
            System.out.println(record.get("a.name").asString() + " knows " + record.get("b.name").asString());
        }
    }
}
1 Collect and combine bookmarks from different sessions using Session.lastBookmarks(), storing them in a Bookmark object.
2 Use them to initialize another session with the .withBookmarks() config method.

driver passing bookmarks

The use of bookmarks can negatively impact performance, since all queries are forced to wait for the latest changes to be propagated across the cluster. For simple use-cases, try to group queries within a single transaction, or within a single session.

Mix .executableQuery() and sessions

To ensure causal consistency among transactions executed partly with .executableQuery() and partly with sessions, you can retrieve the default bookmark manager for ExecutableQuery instances through driver.executableQueryBookmarkManager() and pass it to new sessions through the .withBookmarkManager() config method. This will ensure that all work is executed under the same bookmark manager and thus causally consistent.

// import org.neo4j.driver.Driver;
// import org.neo4j.driver.SessionConfig;

driver.executableQuery("<QUERY 1>").execute();

try (var session = driver.session(SessionConfig.builder()
    .withBookmarkManager(driver.executableQueryBookmarkManager())
    .build())) {

    // every query inside this session will be causally chained
    // (i.e., can read what was written by <QUERY 1>)
    session.executeWriteWithoutResult(tx -> tx.run("<QUERY 2>"));
}

// subsequent executableQuery calls will also be causally chained
// (i.e., can read what was written by <QUERY 2>)
driver.executableQuery("<QUERY 3>").execute();

Glossary

LTS

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

Aura is Neo4j’s fully managed cloud service. It comes with both free and paid plans.

Cypher

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

APOC

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

Bolt

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

ACID

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.

NULL

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

transaction

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

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.

Driver

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