Retry mechanism in verify_connectivity for Python

I am trying to use verify_connectivity function (API Documentation — Neo4j Python Driver 5.14) to verify the database connection for my application.

I have some follow up questions for this function:

  1. If the connection fails, does this function 'retry' a few times internally?
  2. Can we specify the number of retries while invoking the function?
  3. If there is no retry feature for this function, do you recommend that we should implement a retry pattern for it?

Hi :wave:

  1. Nope. There are no retries built into verify_connectivity.
  2. Answered with 1 :grin:
  3. That really depends on what circumstances you expect your application to run in. If you only call verify_connectivity at the very beginning before using the driver for anything else, a failure will mean that driver cannot reach the server. Whether that's worth retrying depends on if you expect the server or network to recover or not. For instance if you know you're starting the DBMS at the same time as the driver, I'd argue it makes sense to retry because the server might need a little longer to fully come online.

Should you decide to implement a retry mechanism, here's a brief sketch of how it could work

from time import sleep

import neo4j
from neo4j.exceptions import DriverError, Neo4jError


URL = "neo4j://localhost:7687"
AUTH = ("neo4j", "pass")
MAX_RETRIES = 30
RETRY_DELAY = 1


with neo4j.GraphDatabase.driver(URL, auth=AUTH) as driver:
    for _ in range(MAX_RETRIES):
        try:
            driver.verify_connectivity()
            break
        except (DriverError, Neo4jError) as e:
            if not e.is_retryable():
                raise
            sleep(RETRY_DELAY)  # maybe want to do exponential back-off instead

    print("good to go!")
    print(driver.execute_query("RETURN 1 AS n"))
1 Like