Too many connections from one server

Hello.
I have several databases with different data. I have a multi-page flask application. Approximately 100 different visualizations.
And I’ve have a problem.
One of the databases is postgresql and there is a limit on the number of connections of 100 pieces. The problem is that after starting the server, a huge number of connections are added at once.
And there are two servers, the second is a test one, and there are many other different scripts that also need connections.
And all this leads to the fact that if I launch a test version of the server, then many cannot use the main one, since there are not enough connections for everyone.

Maybe I’m doing something wrong?
A typical page looks like this:

from dash_dangerously_set_inner_html import DangerouslySetInnerHTML
import dash
from dash import html, dcc, callback, Input, Output, register_page, dash_table
import plotly.express as px
from flask import request
from datetime import datetime, timedelta, date
import dash_mantine_components as dmc

dash.register_page(__name__)

import psycopg2
from psycopg2.extras import RealDictCursor

register_page(__name__, path_template="/watch/order/<order_id>", icon="fa-solid:home", title="Сockpit")
layout = html.Div(children=[
    html.Div([
        html.Div(id='w_order', style={'text-align':'center'}),
    ], style={'width':'100%', 'display':'flex','align-items':'center','justify-content':'center'}),
])

@callback(
    Output('w_order', 'children'),
    Input('url', 'pathname'),
)
def w_order(url):
    order = url[13:]
    conn = psycopg2.connect(database="", user="", password='', host='', port='') 
    cursor = conn.cursor(cursor_factory=RealDictCursor)
    cursor.execute(
        f"""
SELECT *
FROM orders
WHERE ordernum = '{order}'
LIMIT 1
        """)
    row = cursor.fetchone()
    cursor.close()
    
    #make html table here
    
    return DangerouslySetInnerHTML(table)

The connection is created inside the callback, exists as long as necessary and then is terminated.
The guides say that cursor.close() is enough to close the connection, but what happens then?
Can someone explain where I’m wrong?

Hello @uk141,

Is there any way for you to see how many connections the db has active? This might help you with troubleshooting.

And yes, cursor close or connection quit is typically enough. I also believe that when ran inside a function, it drops after execution anyways… But I use SQL.


I think my last statement is incorrect looking at my connections on my db. XD