When should we close the database connection?

With the following example:

class MyDatabase(object):
  def __init__(self, uri, user, password):
    self._driver = GraphDatabase.driver(uri, auth=(user, password))
  def close(self):
    self._driver.close()

When should we call the close method?

Looking at this post, it states not to close the connection. So, I'm in dilemma what to do and what not to do.

Because, we can use the database queries in different interval of time or simultaneously such as post books, post authors, etc. So, should I keep my database connection always open? Is there any downside if I close the connection after every database query in neo4j?

You should definitely not close the connection after every query. Connections are relatively heavyweight objects that involve setup and network roundtrips to authenticate you. If you close the connection after every query, your experience will be that queries are a lot slower as your code does a lot of extra unnecessary work.

That being said, connections are also resources to be managed. And so you also don't want to go willy-nilly creating thousands of them, or not closing them when you're finished.

Most simple programs will find that they can create one connection when they start, reuse the same one throughout the program, and close it only when the program is completely finished.

A driver object in Neo4j manages a connection pool for you - so keep in mind you don't get much benefit from creating say 5 and using 1 per thread. Just issue more queries against the same driver, and let the driver manage the actual TCP connections for you.

2 Likes

Thanks David.

So, I should never close the connection in my application? Because, I am not sure where the application ends.

If your connection is open-ended and used continuously, then it's probably fine if you don't close it at all.

The mental model to have here is that as you create sessions and run queries, it borrows connections from a pool that is maintained by the driver. You can use as many as you like and let the driver manage this for you. If you don't ever shut down operations then you don't ever really have a need to close the connection, except if something else were to happen (database migration, DNS change, etc)

1 Like

Do you mean I should close the connection before database migration? Can you show an example or pseudo code?