Reputation: 2223
The example Node.js file for neo4j contains the following:
const neo4j = require('neo4j-driver')
const driver = neo4j.driver(uri, neo4j.auth.basic(user, password))
const session = driver.session()
const personName = 'Alice'
try {
const result = await session.run(
'CREATE (a:Person {name: $name}) RETURN a',
{ name: personName }
)
const singleRecord = result.records[0]
const node = singleRecord.get(0)
console.log(node.properties.name)
} finally {
await session.close()
}
// on application exit:
await driver.close()
It makes sense that a session should be created for each transaction and destroyed afterwards, but should the driver be closed between transactions in production as well?
On the one hand, I assume that there's a good bit of overhead associated with spinning up a driver instance, so doing so on each request might cause performance issues. On the other hand, I haven't seen any documentation indicating that the driver will be closed after a certain period of time, and I don't want to just have these hanging processes left behind even after the user has navigated away from the site.
Any guidance on a performant way to balance these things would be appreciated. If anyone has any production instances of how they use neo4j that would be very helpful to link to as well.
Upvotes: 1
Views: 247
Reputation: 2223
I found the answer here, I hope it helps someone else:
Drivers are reasonably expensive to create - you should strive to keep one driver instance around per Neo4j Instance you connect to.
Sessions should be created for each transaction, since at most one transaction can be running in a session at a time, but drivers should be reused. A good way to do this is to declare the driver at startup and set it in the global scope, then only close it when the application is shut down.
Upvotes: 3