Does an API connection close when browser is closed?

I have a streamlit app that is connected to MongoDB Atlas. When a user goes to the link to the app, the database connection starts, and they can do insert or delete documents in that DB.

Currently a rough implementation looks like:

import os
from pymongo import MongoClient

URI = os.getenv("URI")
DB = os.getenv("DB")

if st.session_state.get("client") is None:
    st.session_state["client"] = MongoClient(URI)

st.text_input("Enter collection name:", key="coll_name")

db = st.session_state["client"][DB]
collection = db[st.session_state["coll_name"]]
# do stuff with `collection`

The question is, I want to close the connection when the user closes the webpage tab. Where do I put that code? Ideally, I need to put st.session_state["client"].close() somewhere in this code but I don’t know where? Or do I even need to? Does the connection die when I close the webpage?

Hey cottontail!

Just curious, is there a specific reason you feel the need to close the MongoDB connection?

MongoDB’s MongoClient is designed with connection pooling, which means it efficiently manages connections in the background. Once a connection is established, it remains available and can be reused for future operations. Unless you’re facing issues with resource limits or performance, there’s usually no need to manually close the connection every time.

In fact, keeping the connection open is generally a good thing since the client reuses the pool of connections, minimizing overhead from repeatedly opening and closing connections.

As far as I know, Streamlit doesn’t have a built-in way to detect when a user closes their browser tab.

In most cases, though, MongoDB’s connection pooling should handle everything for you, so manually closing the connection isn’t usually necessary.

Hope this helps! Let me know if you have more questions.

Hi @Nico, thanks for the reply. In my use case, most users of this app may interact with this app only once and never again, so I thought it probably wouldn’t make sense to keep a connection open for that user. So you’re saying that even in that case, it doesn’t matter because MongoDB’s connection pooling will take care of this in the background?

I understand that now this question doesn’t have anything to do with Streamlit anymore, so yeah, you don’t have to respond.

After looking into this a bit further, a couple things you could look into that I think would help are:

and

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