Django.fun

Django: Why does database login every query?

In my settings.py, I have a database configured. I have a page that issues a sql query against the database defined in settings.py every 10 seconds.

I have been using it for 1 year now and never had any issues with it.

My database admin ran a login audit on our database. As it turns out, each individual single sql query has a unique login to the database. His audit took 5 minutes to run just today and it is because of my django application logging in.

I was pretty surprised to find out that every query that is issues has a unique login attempt to the database.

Is there anyway to create a "session" for the backend database in settings.py. I really feel that the application should have a single login and use that session to issue commands.

Did I miss a setting to do this?

enter image description here

Sql login audit: enter image description here

Answers: 1

Answered by Adithya, Sept. 17, 2021, 8:12 a.m.

Consider setting CONN_MAX_AGE in DATABASES setting.

From the docs

Persistent connections avoid the overhead of re-establishing a connection to the database in each request. They’re controlled by the CONN_MAX_AGE parameter which defines the maximum lifetime of a connection. It can be set independently for each database. The default value is 0, preserving the historical behavior of closing the database connection at the end of each request. To enable persistent connections, set CONN_MAX_AGE to a positive integer of seconds. For unlimited persistent connections, set it to None.