Client applications

This section describes how to manage database connections within an application.

The Driver Object

Neo4j client applications require a Driver Object which, from a data access perspective, forms the backbone of the application. It is through this object that all Neo4j interaction is carried out, and it should therefore be made available to all parts of the application that require data access.

In languages where thread safety is an issue, the Driver Object can be considered thread-safe.

A note on lifecycle

Applications will typically construct a Driver Object on startup and destroy it on exit.

Destroying a Driver Object will immediately shut down any connections previously opened via that Driver Object, by closing the associated connection pool.

This will have the consequence of rolling back any open transactions, and closing any unconsumed results.

To construct a driver instance, a connection URI and authentication information must be supplied.

Additional configuration details can be supplied if required. The configuration details are immutable for the lifetime of the Driver Object. Therefore, if multiple configurations are required (such as when working with multiple database users) then multiple Driver Objects must be used.

Example 1. The driver lifecycle
public class DriverLifecycleExample : IDisposable
    private bool _disposed;
    public IDriver Driver { get; }

    ~DriverLifecycleExample() => Dispose(false);

    public DriverLifecycleExample(string uri, string user, string password)
        Driver = GraphDatabase.Driver(uri, AuthTokens.Basic(user, password));

    public void Dispose()

    protected virtual void Dispose(bool disposing)
        if (_disposed)

        if (disposing)

        _disposed = true;

Connection URIs

A connection URI identifies a graph database and how to connect to it.

The encryption and trust settings provide detail to how that connection should be secured.

Starting with Neo4j 4.0, client-server communication uses only unencrypted local connections by default. This is a change from previous versions, which switched on encryption by default, but generated a self-signed certificate out of the box.

When a full certificate is installed, and encryption is enabled on the driver, full certificate checks are carried out (refer to Operations Manual → SSL framework). Full certificates provide better overall security than self-signed certificates as they include a complete chain of trust back to a root certificate authority.

Neo4j Aura is a secure hosted service backed by full certificates signed by a root certificate authority.

To connect to Neo4j Aura, driver users must enable encryption and the complete set of certificate checks (the latter of which are enabled by default).

For more information, see Examples below.

Initial address resolution

The address provided in a neo4j:// URI is used for initial and fallback communication only.

This communication occurs to bootstrap the routing table, through which all subsequent communication is carried out. Fallback occurs when the driver is unable to contact any of the addresses held in the routing table. The initial address is once again reused to bootstrap the system.

Several options are available for providing this initial logical-to-physical host resolution. These include regular DNS, custom middleware such as a load balancer, and the Driver Object resolver function, all of which are described in the following sections.

DNS resolution

DNS resolution is the default, and always-available option. As it is possible to configure DNS to resolve a single host name down to multiple IP addresses, this can be used to expose all core server IP addresses under a single host name.

dns resolution
Figure 1. Initial address resolution over DNS

Custom middleware

Middleware, such as a load balancer, can be used to group the core servers under a single public address.

custom middleware
Figure 2. Initial address resolution using custom middleware

Resolver function

Neo4j Drivers also present an address resolution intercept hook called the resolver function.

This takes the form of a callback function that accepts a single input address and returns multiple output addresses. The function may hard code the output addresses or may draw them from another configuration source, as required.

resolver function
Figure 3. Initial address resolution using resolver function

The example below shows how to expand a single address into multiple (hard-coded) output addresses:

Example 2. Custom Address Resolver
private IDriver CreateDriverWithCustomResolver(string virtualUri, IAuthToken token,
    params ServerAddress[] addresses)
    return GraphDatabase.Driver(virtualUri, token,
        o => o.WithResolver(new ListAddressResolver(addresses)).WithEncryptionLevel(EncryptionLevel.None));

public void AddPerson(string name)
    using (var driver = CreateDriverWithCustomResolver("neo4j://",
               AuthTokens.Basic(Username, Password),
               ServerAddress.From("", 7687), ServerAddress.From("", 7877),
               ServerAddress.From("", 9092)))
        using (var session = driver.Session())
            session.Run("CREATE (a:Person {name: $name})", new {name});

private class ListAddressResolver : IServerAddressResolver
    private readonly ServerAddress[] _servers;

    public ListAddressResolver(params ServerAddress[] servers)
        _servers = servers;

    public ISet<ServerAddress> Resolve(ServerAddress address)
        return new HashSet<ServerAddress>(_servers);

Routing table

The routing table acts like the glue between the driver connectivity layer and the database surface. This table contains a list of server addresses, grouped as readers and writers, and is refreshed automatically by the driver as required.

The driver does not expose any API to work directly with the routing table, but it can sometimes be useful to explore when troubleshooting a system.

Load balancing policies

A policy parameter can be included in the query string of a neo4j:// URI, to customize the routing table and take advantage of multi-data center routing settings.

A prerequisite for using load balancing policies with the driver is that the database is operated on a cluster, and that some server policies are set up.


Connection URIs are typically formed according to the following pattern:


This targets a routed Neo4j service that may be fulfilled by either a cluster or a single instance. The HOST and PORT values contain a logical hostname and port number targeting the entry point to the Neo4j service (e.g. neo4j://

In a clustered environment, the URI address will resolve to one of more of the core members; for standalone installations, this will simply point to that server address. The policy parameter allows for customization of the routing table and is discussed in more detail in load balancing policies.

An alternative URI form, using the bolt URI scheme (e.g. bolt://, can be used when a single point-to-point connection is required. This variant is useful for the subset client applications (such as admin tooling) that need to be aware of individual servers, as opposed to those which require a highly available database service.


Each of the neo4j and bolt URI schemes permit variants that contain extra encryption and trust information. The +s variants enable encryption with a full certificate check, and the +ssc variants enable encryption, but with no certificate check. This latter variant is designed specifically for use with self-signed certificates.

Table 1. Available URI schemes
URI scheme Routing Description






Secured with full certificate



Secured with self-signed certificate






Secured with full certificate



Secured with self-signed certificate

Neo4j 3.x did not provide a routing table in single instance mode and therefore you should use a bolt:// URI if targeting an older, non-clustered server.

The table below provides example code snippets for different deployment configurations. Each snippet expects an auth variable to have been previously defined, containing the authentication details for that connection.

Connecting to a service

The tables below illustrate examples of how to connect to a service with routing:

Table 2. Neo4j Aura or Neo4j >= 4.x, secured with full certificate


Neo4j Aura, Neo4j >= 4.x


Secured with full certificate

Code snippet

GraphDatabase.Driver("neo4j+s://", auth)


This is the default (and only option) for Neo4j Aura.

Table 3. Neo4j >= 4.x, unsecured


Neo4j >= 4.x



Code snippet

GraphDatabase.Driver("neo4j://", auth);


This is the default for Neo4j >= 4.x series

Table 4. Neo4j >= 4.x, secured with self-signed certificate


Neo4j >= 4.x


Secured with self-signed certificate

Code snippet

GraphDatabase.Driver("neo4j+ssc://", auth)
To connect to a service without routing, you can replace neo4j with bolt.


Authentication details are provided as an auth token which contains the user names, passwords or other credentials required to access the database. Neo4j supports multiple authentication standards but uses basic authentication by default.

Basic authentication

The basic authentication scheme is backed by a password file stored within the server and requires applications to provide a user name and password. For this, use the basic auth helper:

Example 3. Basic authentication
public IDriver CreateDriverWithBasicAuth(string uri, string user, string password)
    return GraphDatabase.Driver(uri, AuthTokens.Basic(user, password));

The basic authentication scheme can also be used to authenticate against an LDAP server.

Kerberos authentication

The Kerberos authentication scheme provides a simple way to create a Kerberos authentication token with a base64 encoded server authentication ticket. The best way to create a Kerberos authentication token is shown below:

Example 4. Kerberos authentication
public IDriver CreateDriverWithKerberosAuth(string uri, string ticket)
    return GraphDatabase.Driver(uri, AuthTokens.Kerberos(ticket),
        o => o.WithEncryptionLevel(EncryptionLevel.None));

The Kerberos authentication token can only be understood by the server if the server has the Kerberos Add-on installed.

Custom authentication

For advanced deployments, where a custom security provider has been built, the custom authentication helper can be used.

Example 5. Custom authentication
public IDriver CreateDriverWithCustomizedAuth(string uri,
    string principal, string credentials, string realm, string scheme,
    Dictionary<string, object> parameters)
    return GraphDatabase.Driver(uri, AuthTokens.Custom(principal, credentials, realm, scheme, parameters),
        o => o.WithEncryptionLevel(EncryptionLevel.None));



The maximum amount of time a session will wait when requesting a connection from the connection pool. For connection pools where all connections are currently being used and the MaxConnectionPoolSize limit has been reached, a session will wait this duration for a connection to be made available. Since the process of acquiring a connection may involve creating a new connection, ensure that the value of this configuration is higher than the configured ConnectionTimeout.

Setting a low value will allow for transactions to fail fast when all connections in the pool have been acquired by other transactions. Setting a higher value will result in these transactions being queued, increasing the chances of eventually acquiring a connection at the cost of longer time to receive feedback on failure. Finding an optimal value may require an element of experimentation, taking into consideration the expected levels of parallelism within your application as well as the MaxConnectionPoolSize.

Default: 60 seconds

Example 6. Configure connection pool
public IDriver CreateDriverWithCustomizedConnectionPool(string uri, string user, string password)
    return GraphDatabase.Driver(uri, AuthTokens.Basic(user, password),
        o => o.WithMaxConnectionLifetime(TimeSpan.FromMinutes(30))

The maximum amount of time to wait for a TCP connection to be established. Connections are only created when a session requires one unless there is an available connection in the connection pool. The driver maintains a pool of open connections which can be loaned to a session when one is available. If a connection is not available, then an attempt to create a new connection (provided the MaxConnectionPoolSize limit has not been reached) is made with this configuration option, providing the maximum amount of time to wait for the connection to be established.

In environments with high latency and high occurrences of connection timeouts it is recommended to configure a higher value. For lower latency environments and quicker feedback on potential network issues configure with a lower value.

Default: 30 seconds

Example 7. Configure connection timeout
public IDriver CreateDriverWithCustomizedConnectionTimeout(string uri, string user, string password)
    return GraphDatabase.Driver(uri, AuthTokens.Basic(user, password),
        o => o.WithConnectionTimeout(TimeSpan.FromSeconds(15)));

Specify a custom server address resolver used by the routing driver to resolve the initial address used to create the driver. See Resolver function for more details.


Specify whether to use an encrypted connection between the driver and server.

Default: False

Example 8. Unencrypted configuration
public IDriver CreateDriverWithCustomizedSecurityStrategy(string uri, string user, string password)
    return GraphDatabase.Driver(uri, AuthTokens.Basic(user, password),
        o => o.WithEncryptionLevel(EncryptionLevel.None));

The maximum duration the driver will keep a connection for before being removed from the pool. Note that while the driver will respect this value, it is possible that the network environment will close connections inside this lifetime. This is beyond the control of the driver. The check on the connection’s lifetime happens when a session requires a connection. If the available connection’s lifetime is over this limit it is closed and a new connection is created, added to the pool and returned to the requesting session. Changing this configuration value would be useful in environments where users don’t have full control over the network environment and wish to proactively ensure all connections are ready.

Setting this option to a low value will cause a high connection churn rate, and can result in a performance drop. It is recommended to pick a value smaller than the maximum lifetime exposed by the surrounding system infrastructure (such as operating system, router, load balancer, proxy and firewall). Negative values result in lifetime not being checked.

Default: 1 hour (3600 seconds)


The maximum total number of connections allowed, per host (i.e. cluster nodes), to be managed by the connection pool. In other words, for a direct driver using the bolt:// scheme, this sets the maximum number of connections towards a single database server. For a driver connected to a cluster using the neo4j:// scheme, this sets the maximum amount of connections per cluster member. If a session or transaction tries to acquire a connection at a time when the pool size is at its full capacity, it must wait until a free connection is available in the pool or the request to acquire a new connection times out. The connection acquiring timeout is configured via ConnectionAcquisitionTimeout.

This configuration option allows you to manage the memory and I/O resources being used by the driver and tuning this option is dependent on these factors, in addition to number of cluster members.

Default: 500 connections


The maximum amount of time that a managed transaction will retry for before failing. Queries that are executed within a managed transaction gain the benefit of being retried when a transient error occurs. When this happens the transaction is retired multiple times up to the MaxTransactionRetryTime.

Configure this option higher in high latency environments or if you are executing many large transactions which could limit the number of times that they are retired and therefore their chance to succeed. Configure lower in low latency environments and where your workload mainly consists of many smaller transactions. Failing transactions faster may highlight the reasons behind the transient errors making it easier to fix underlying issues.

Default: 30 seconds

Example 9. Configure maximum retry time
public IDriver CreateDriverWithCustomizedMaxRetryTime(string uri, string user, string password)
    return GraphDatabase.Driver(uri, AuthTokens.Basic(user, password),
        o => o.WithMaxTransactionRetryTime(TimeSpan.FromSeconds(15)));

Specify how to determine the authenticity of encryption certificates provided by the Neo4j instance that you are connecting to. If encryption is disabled, this option has no effect.

Possible values are:

  • TrustManager.CreateChainTrust() - [Default] Accept any certificate that can be verified against the system store.

  • TrustManager.CreateCertTrust(new []{"/path/ca1.crt", "/path/ca2.crt"}) - Accept certificates at specified paths.

  • TrustManager.CreateInsecure() - Accept any certificate, including self-signed ones. Not recommended for production environments.

Example 10. Configure trusted certificates
public IDriver CreateDriverWithCustomizedTrustStrategy(string uri, string user, string password)
    return GraphDatabase.Driver(uri, AuthTokens.Basic(user, password),
        o => o.WithTrustManager(TrustManager.CreateInsecure()));

Specify whether TCP keep-alive should be enabled. To ensure that the connection between the driver and server is still operational, the TCP layer can periodically send messages to check the connection.

Default: True


All official Neo4j Drivers log information to standard logging channels. This can typically be accessed in an ecosystem-specific way.

The code snippet below demonstrates how to redirect log messages to standard output:

#Please note that you will have to provide your own console logger implementing the ILogger interface.
IDriver driver = GraphDatabase.Driver(..., o => o.WithLogger(logger));