Retry on database connection failures

Hi folks!

I have a question about database connection: Is it possible to make Django retry on database connection failures?

According to the official documentation, Django will close the db connection if it’s no longer alive (https://docs.djangoproject.com/en/3.1/ref/databases/#persistent-connections). Is there a way (a library or configuration setting) to make it retry on connection errors instead of closing it directly?

Thanks!

There is an open Django ticket about this: #24810 (Reopen database connection automatically when no transaction is active) – Django

There is also a django-dbconn-retry app which monkeypatches the Django: GitHub - jdelic/django-dbconn-retry: Patches Django to reconnect on a failed database connection once before failing. Helping with running Django ORM through HAProxy, for example. I have not used it myself and don’t know how well it works.

The retries could also potentially be done in a database connection pooler sitting between Django and the database. Here’s a pgDog developer saying that, although they do not have this feature at the moment, they are open to adding it: Some HTTP proxies can do retries -- if a connection to one backend fails, it is ... | Hacker News

you could also use tenacity library of python to test

@shubh-gitpush how would you use it, where would you plug it in?

We could wrap around the orm like this @retry(
stop=stop_after_attempt(3),
wait=wait_fixed(2),
retry=lambda retry_state: isinstance(retry_state.outcome.exception(), OperationalError)
def get_data():
return MyModel.objects.all()
it will try to connect to databse if it fails it will retry three times if still fails it will throw error.