Because of the issue I described in this thread, I have been taking a look at how Django handles opening and closing of db connections.
In particular, when a db connection is opened, I’m trying to track down when and where it gets closed. I want to understand how connections are treated in relation to the CONN_MAX_AGE setting.
In django.db.backends.base, method
connect, I can see that the CONN_MAX_AGE setting is used to set a value
close_at on the returned wrapper object for the connection.
Then, there’s a method called close_if_unusable_or_obsolete, in which the connection’s
close_at is evaluated to see if the connection must be closed.
Per my understanding, that method is registered as a signal handler in django.db.init.py, and runs every time a request starts or finishes.
It appears to me the method is always executed synchronously, and its execution depends on there being a new request. If no new request arrives, no old connections are closed, even if their age is past the max setting. Is this correct?
Anyway, here’s what I tried: using sqlite as my db backend and ATOMIC_REQUESTS=True, I added a debug print inside of the connect method and one inside of the the close method, to try and see when the opened connections get closed.
With CONN_MAX_AGE set to 0, what I observed was that, for each request to my application, one or more connections got opened, and they all got immediately closed after the request was served.
Here’s the interesting thing though: with CONN_MAX_AGE set to anything greater than 0 (I tried with many values including 1), what happened was I didn’t see anything printed to the console. Inspecting the way the signal handler is registered, I would imagine it’d get called on the next request and close the older connection, but the method doesn’t get called.
Somehow though, printing the number of connections from this line (by simply counting the iterations of the loop) always showed one active connection, so either the old one was being re-used, or it was being closed from somewhere else and a new one was opened. Either way, could somebody please help me clarify when and where the connections get closed? I feel like this could help me solve the issue I described in the thread I linked.