When to close pymongo client

I am making a fastapi app

should i make am a global pymongo client object
if my app crashes when will the connection to mongodb close??

or create a pymongo client for each api
and close it at end of api

please help

Hi @Rohit_Krishnamoorthy , and welcome to the forums!

Generally you should only have one instance of PyMongo MongoClient for the life cycle of your application. In the case of a server, you could try creating a singleton class pattern to manage a MongoClient instance. For more information on singleton please see Python3: Singleton

This is trickier to handle as “crash” could mean a few things. From FastAPI point of view itself, you could include a clean up method of MongoClient in shutting down event

from fastapi import FastAPI
app = FastAPI()
@app.on_event("shutdown")
def shutdown_event():
    # Invoke MongoClient close()
    # ... 

See also FastAPI: shutdown event for more information.

If the “crash” event is happening on gunicorn layer, then depending on the type of ‘crash’ you may be able to catch the signal and handle it appropriately. At this point, this is more related to the WSGI server instead of the Python MongoDB driver itself.

Regards,
Wan.

2 Likes

Thank you so much for replying

Your answer makes sense ill look into singleton design pattern
and fastapi shutdown event.

ill ellaborate on “crash” event

This is my setup
I have gcp VM and deploy my fastapi backend api inside a docker container

  1. The one I am majorly concerned about is that

I am deploying my app in a docker container
and when redeploying the app i am removing the old container
and rebuilding a new image and container

does the mongo db connection close when i remove my old container of fastapi
the command i use to remove the container is this
docker rm -f <container_name>

  1. maybe my server stopped because of memory issue etc
    these are unlikely events i am not worried much about these but i am curious to know what would happen then

Sorry extending the question a bit more

lets say my server stoped for some reason without closing connection.
what is going to happens
What happens on the mongoDB side
how long it will hold inactive connections

Hi @Rohit_Krishnamoorthy

In MongoDB v3.6+, by default a reaper process would clean up an expired Server Sessions every 5 minutes.

Regards,
Wan.

2 Likes

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