SSL connection has been closed unexpectedly

Dear all,
I connected my Streamlit app with a PostgreSQL database in Heroku. Everything was just right. But recently, they eliminated their free PostgreSQL offer. Now I use a server as a PostgreSQL database. Once in every 3-4 hours we were seeing, the connection has lost. So we had to restart the PostgreSQL server. Now, we set the server to restart automatically every 3-4 hours. But now I face another error, which can be solved simply by rebooting my app. How can I solve this issue without having to reboot the app? Because I need my app to work constantly.

the traceback is:

psycopg2.OperationalError: terminating connection due to administrator command
SSL connection has been closed unexpectedly

If necessary, I share the whole traceback text.
Thanks in advance.

Hi @Sinakian,

Thanks for sharing your question! I think it will be difficult for community members to make suggestions without seeing the code, in this case – can you share a minimal code snippet that allows us to reproduce the issue?

Hi @Sinakian , as @Caroline said it’s difficult to understand your question without some code.

However, I think your problem could be related to the PostgreSQL connection closing because it timed out. If I understand correctly, as of version 1.17, the @st.experimental_singleton decorator supports a validate parameter to solve this.

In a previous version I made a simple adjustment to my app:

def init_connection(reloadvar):
    return psycopg2.connect(**st.secrets["postgres"])

# Add boolean var as argument of function
reloadvar = False
conn = init_connection(reloadvar)

# Reconnect button, if necessary
if st.button(label='Reconnect'):
    reloadvar = not(reloadvar)
    conn = init_connection(reloadvar)

Basically, the cache decorators would only run the function if an input argument changes. So I just added an input argument so the user can restablish the connection if needed to.

This is not the most elegant solution and I’m quite sure something better could be made using the session_state, but it worked for me that time.

Hope that helps.

Hello @Sinakian,
I am facing exactly the same problem. Did you solve the problem? If you did, could you please let me know how to solve this problem? It would have been a great help.

Hope this issue will solve soon. Many people face this issue that SSL connection closing automatically.