Yue Wang’s Post

So I recently encountered another shocking and sad accident in my code, which is the race condition introduced by using singleton. I used to think singleton is good for storing things that only exist one copy in the system and can be reused. I saw a few of programs store their Redis connection pool in a singleton class, which looks nice. Then bad thing happens when I use that SDK I wrote in a Flask service with multithread enabled and save user states inside singleton. Then race condition happens, before one session finished, another already came in and overwrote the states. I would say from now I would really be extra meticulous about any designs and patterns I feel good about and then judge them before I put them in any running services. And for the solution? Actually it was quite straightforward, just save the states in each client object, no other tricks. Here is an example from Supervisely, which is an MLops platform which also support running services with their SDK as part of the code. https://lnkd.in/gc9bD8U7 #python #race_condition #singleton

To view or add a comment, sign in

Explore content categories