Performance recommendations

Always specify the target database

Specify the target database on all queries with the .withDatabase() method, either in Driver.executableQuery() calls or when creating new sessions. If no database is provided, the driver has to send an extra request to the server to figure out what the default database is. The overhead is minimal for a single query, but becomes significant over hundreds of queries.

Good practices

driver.executableQuery("<QUERY>")
    .withConfig(QueryConfig.builder().withDatabase("<database-name>").build())
    .execute();
driver.session(SessionConfig.builder().withDatabase("<database-name>").build());

Bad practices

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

Be aware of the cost of transactions

Queries are always run within transactions on the server, so that the database always ends up in a consistent state regardless of what happens during a transaction execution (power outages, software crashes, etc). Queries submitted via .executableQuery() or .executeRead/Write() are also automatically retried in case of failure. A transactions yields an overhead that is small, but that adds up as the number of transactions increases.

As your workload grows, evaluate what level of isolation each query needs and be intentional about your usage of transactions. There are essentially three approaches to running queries depending on your needs for safety and performance. Remember that there’s no free lunch and that it’s always a trade-off between the two.

  1. One transaction ⟷ One query (lowest throughput, highest safety)
    The safest mode of execution with respect to failures, because of the isolation and auto-retry guarantees, but also the slowest due to the overhead of transactions scaling with the number of queries.

    Run 1000 queries, each as a separate transaction
    for (int i=0; i<1000; i++) {
        driver.executableQuery("<QUERY>")
            .withConfig(QueryConfig.builder().withDatabase("<database-name>").build())
            .execute();
        // or session.executeRead/Write() calls, each with one query
    }
  2. One transaction ⟷ Multiple queries (higher throughput, high safety)
    When multiple queries are grouped into a single transaction, the transaction as a whole is isolated from others, whereas individual queries in the transaction are not isolated and failure of one query results in a rollback of all queries.

    Run 10 transactions with 100 queries each
    try (var session = driver.session(SessionConfig.builder().withDatabase("<database-name>").build())) {
        for (int k=0; k<10; k++) {
            session.executeWriteWithoutResult(tx -> {
                for (int i=0; i<100; i++) {
                    tx.run("<QUERY>");
                }
            });
        }
    }
  3. Auto-commit transactions (highest throughput, lowest safety)
    Auto-commit transactions shoot queries to the server as fast as it can handle. Failed queries are not retried, and there’s no exact guarantee on when changes get written to the database. One upper limit on the client size is given by the size of the connection pool: each call to session.run() borrows a connection, so the amount of parallel work is limited by the number of available connections.

    Run 1000 queries as auto-commit transactions
    try (var session = driver.session(SessionConfig.builder().withDatabase("<database-name>").build())) {
        for (int i=0; i<1000; i++) {
            session.run("<QUERY>");
        }
    }

Route read queries to cluster readers

In a cluster, route read queries to any reader node. You do this by:

Good practices

// import org.neo4j.driver.RoutingControl;

driver.executableQuery("MATCH (p:Person) RETURN p")
    .withConfig(QueryConfig.builder()
        .withDatabase("<database-name>")
        .withRouting(RoutingControl.READ)
        .build())
    .execute();
try (var session = driver.session(SessionConfig.builder().withDatabase("<database-name>").build())) {
    session.executeRead(tx -> {
        var result = tx.run("MATCH (p:Person) RETURN p");
        return result.list();
    });
}

Bad practices

// defaults to routing = writers
driver.executableQuery("MATCH (p:Person) RETURN p")
    .withConfig(QueryConfig.builder()
        .withDatabase("<database-name>")
        .build())
    .execute();
// don't ask to write on a read-only operation
try (var session = driver.session(SessionConfig.builder().withDatabase("<database-name>").build())) {
    session.executeWrite(tx -> {
        var result = tx.run("MATCH (p:Person) RETURN p");
        return result.list();
    });
}

Create indexes

Create indexes for properties that you often filter against. For example, if you often look up Person nodes by the name property, it is beneficial to create an index on Person.name. You can create indexes with the CREATE INDEX Cypher clause, for both nodes and relationships.

Create an index on Person.name
driver.executableQuery("CREATE INDEX person_name FOR (n:Person) ON (n.name)").execute();

For more information, see Indexes for search performance.

Profile queries

Profile your queries to locate queries whose performance can be improved. You can profile queries by prepending them with PROFILE. In case some queries are so slow that you are unable to even run them in reasonable times, you can prepend them with EXPLAIN instead of PROFILE. This will return the plan that the server would use to run the query, but without executing it.

Specify node labels

Specify node labels in all queries. This allows the query planner to work much more efficiently, and to leverage indexes where available. To learn how to combine labels, see Cypher → Label expressions.

Good practices

driver.executableQuery("MATCH (p:Person|Animal {name: $name}) RETURN p")
    .withParameters(Map.of("name", "Alice"))
    .withConfig(QueryConfig.builder().withDatabase("<database-name>").build())
    .execute();
try (var session = driver.session(SessionConfig.builder().withDatabase("<database-name>").build())) {
    session.run("MATCH (p:Person|Animal {name: $name}) RETURN p", Map.of("name", "Alice"));
}

Bad practices

driver.executableQuery("MATCH (p {name: $name}) RETURN p")
    .withParameters(Map.of("name", "Alice"))
    .withConfig(QueryConfig.builder().withDatabase("<database-name>").build())
    .execute();
try (var session = driver.session(SessionConfig.builder().withDatabase("<database-name>").build())) {
    session.run("MATCH (p {name: $name}) RETURN p", Map.of("name", "Alice"));
}

Batch data creation

Batch queries when creating a lot of records using the WITH and UNWIND Cypher clauses.

Good practice

Submit one single queries with all values inside
// Generate a sequence of numbers
int start = 1;
int end = 10000;
List<Map> numbers = new ArrayList<>(end - start + 1);
for (int i=start; i<=end; i++) {
    numbers.add(Map.of("value", i));
}

driver.executableQuery("""
    UNWIND $numbers AS node
    MERGE (:Number {value: node.value})
    """)
    .withParameters(Map.of("numbers", numbers))
    .withConfig(QueryConfig.builder().withDatabase("<database-name>").build())
    .execute();

Bad practice

Submit a lot of single queries, one for each value
for (int i=1; i<=10000; i++) {
driver.executableQuery("MERGE (:Number {value: $value})")
    .withParameters(Map.of("value", i))
    .withConfig(QueryConfig.builder().withDatabase("<database-name>").build())
    .execute();
}
The most efficient way of performing a first import of large amounts of data into a new database is the neo4j-admin database import command.

Use query parameters

Always use query parameters instead of hardcoding or concatenating values into queries. Besides protecting from Cypher injections, this allows to better leverage the database query cache.

Good practices

driver.executableQuery("MATCH (p:Person {name: $name}) RETURN p")
    .withParameters(Map.of("name", "Alice"))
    .withConfig(QueryConfig.builder().withDatabase("<database-name>").build())
    .execute();
try (var session = driver.session(SessionConfig.builder().withDatabase("<database-name>").build())) {
    session.run("MATCH (p:Person {name: $name}) RETURN p", Map.of("name", "Alice"));
}

Bad practices

driver.executableQuery("MATCH (p:Person {name: 'Alice'}) RETURN p")
    .withConfig(QueryConfig.builder().withDatabase("<database-name>").build())
    .execute();
// or
String name = "Alice";
driver.executableQuery("MATCH (p:Person {name: '" + name + "'}) RETURN p")
    .withConfig(QueryConfig.builder().withDatabase("<database-name>").build())
    .execute();
try (var session = driver.session(SessionConfig.builder().withDatabase("<database-name>").build())) {
    session.run("MATCH (p:Person {name: 'Alice'}) RETURN p");
    // or
    String name = "Alice";
    session.run("MATCH (p:Person {name: '" + name + "'}) RETURN p");
}

Concurrency

Use asynchronous querying. This is likely to be more impactful on performance if you parallelize complex and time-consuming queries in your application, but not so much if you run many simple ones.

Use MERGE for creation only when needed

The Cypher clause MERGE is convenient for data creation, as it allows to avoid duplicate data when an exact clone of the given pattern exists. However, it requires the database to run two queries: it first needs to MATCH the pattern, and only then can it CREATE it (if needed).

If you know already that the data you are inserting is new, avoid using MERGE and use CREATE directly instead — this practically halves the number of database queries.

Filter notifications

Switch to Netty native transports

Netty native transports add features specific to a particular platform, generate less garbage, and generally improve performance when compared to the NIO based transport.

You need to provide a valid native dependency in your package manager. The Netty version the driver depends on is 4.2, and the Netty version you specify for the transport dependency must be compatible with that.

Example dependency for native transports with Maven
<dependency>
    <groupId>io.netty</groupId>
    <artifactId>netty-transport-native-io_uring</artifactId>
    <version>${netty-version}</version>
    <classifier>linux-x86_64</classifier>
</dependency>

Glossary

LTS

A Long Term Support release is one guaranteed to be supported for a number of years. Neo4j 4.4 and 5.26 are LTS versions.

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.

bookmark

A bookmark is a token representing 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.

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.