The system can't reach postgres database minutes after being deployed

Description of the problem (please keep it simple and short):
When I deply the system, it works perfectly;
however, after some downtime, the system can no longer connect to the database.
After entering the login, the screen stays blank.
To make the system return to work, I have to pause and resume the deployment…

The deployment log shows the following errors:
psycopg2.InterfaceError: cursor already closed

Explain what you were trying to do:
Access the system in production.

What areas or features are involved?
postgres database access

Repl Cover Page Link/Screenshots/Etc: (to protect you and your code, never share your Repl join link outside of PMs)

Hello @fotografiadmd!

Are you deploying your app as Autoscale or Reserved VM?

Won’t matter.

This is because cursors and connections automatically close after 5 minutes. I have some code that automatically reconnects it, if you’d like it.

1 Like

But then what’s the point? Shouldn’t the db be always up or at least be turned on when receiving a request?

Not sure. That is how Neon works.

If you could send me the code s, I will appreciate very much.
Thank you for your help

You can create a new connection every request. Are you using Flask? If so, this code will (hopefully, it’s from memory) work:

# change "app" to whatever your app is actually called
def create_connection():
    # make sure "g" is imported from flask,
    # and change pool to whatever you've called it
    g.connection = pool.getconn()

def put_connection(response):
    connection = getattr(g, 'connection')
    if connection:
    return response
1 Like

I’m using auto scale

Exactly ! It´s what is written in the postgres docs, by the way… I think it is a bug.

I don’t use Flask, but creating a new connection every request sounds kind of insane. I would have to change all my code.
Furthermore, migrating the code from development to test/production would be quite laborious.
But thank you very much for your help. If nothing else solves this problem, I will try this code.

I don’t think so, the docs don’t have an app that’ll run forever, it just shows how to edit the database once (iirc)

Ok, so what am I doing wrong? I can’t find any solution about this.

Well did you try what I said? Creating a new connection every request seems to be how psycopg2 was intended to be used.

Guys, I found out what happened…
I was using the database URL, instead of usual connection with user, host, password, etc…

Sorry for waste your time…

Please mark your own reply as the solution.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.