Tech C**P
15 subscribers
161 photos
9 videos
59 files
304 links
مدرس و برنامه نویس پایتون و لینوکس @alirezastack
Download Telegram
Today we had hundreds of connections to MongoDB that compared to previous days was so high and one of our modules initiating the connections every time a new request was initiated. To address the issue, I used a singleton design pattern to prevent creating many connections. Although pymongo has its own connection pool, we reduced the connections by 40 to 60!

Singleton design pattern makes sure to only create a new object from your class only ONCE:

class Singleton(object):
_instance = None

def __new__(class_, *args, **kwargs):
if not isinstance(class_._instance, class_):
class_._instance = object.__new__(class_, *args, **kwargs)

return class_._instance

__new__ will be called automatically when a new instance of the class is initiated. Here we check whether _instance is set or not, in case it is set we will return the old instance and will not create a new object.

Now you just need to send Singleton as parent class to your classes:

class MongoConnnection(Singleton):
def __init__(self):
pass

def get_connection(self):
pass

Create as many object as you want from MongoConnnection. And now when you print the initiated class you will see one memory address not different ones.

#mongodb #mongo #singleton #design_pattern #__new__