title: Does fastapi keep database connection allive when it was stored in app.state?
body: <p>I used <code>psycopg2</code> to connect <code>postgresql</code> database.</p>
  <p>To avoid creating database connection every time I communicate with database, I create one connection and stored it in app.state when serve starting up by:</p>
  <pre class="lang-py prettyprint-override"><code>def startup(app: FastAPI) -&gt; Callable:
      &quot;&quot;&quot;
      :param app: FastAPI
      :return: start_app
      &quot;&quot;&quot;
      def app_start() -&gt; None:
          
          # create a new connection
          conn = get_conn()
          # store the connection
          app.state.conn = conn
          app.state.cur = cur
  
      return app_start
  
  # register startup func 
  app.add_event_handler(&quot;startup&quot;, startup(app))
  
  </code></pre>
  <p>And call it by:</p>
  <pre class="lang-py prettyprint-override"><code>request.app.state.conn
  </code></pre>
  <p>My questions are:</p>
  <ol>
  <li>What happend to the connection variable <code>conn</code> stored in  state.app? <br>
  Does the <code>conn</code> keep alive ? Or <code>conn</code> was just shut down after timeout and fastapi would automatically make a new connection when <code>conn</code> was called ?</li>
  <li>Would variable <code>conn</code> be shared between multiple threads or fastapi would create new connections and giving to differnt threads?</li>
  </ol>