python-3.xsentrylru

Does LRU caching prevent sentry from creating multiple instances?


I am using sentry to monitor my application. The initialization is done like thus:

from functools import lru_cache
import sentry_sdk

@lru_cache
def start_sentry():
    sentry_instance = sentry_sdk.init(DSN)
    return sentry_instance

Now, if i were to execute start_sentry multiple times, the multiple sentry_instances created are actually all pointing to the same object in memory. Without using the lru_cache decorator, new sentry instances are crated in memory. So my question is: is using lru caching doing what I am expecting, that is - will it only initialize sentry once even though i attempt to do it multiple times?

i am on python3.6.7 sentry-sdk==0.10.2


Solution

  • It will work like that provided it's called within the same process.

    That's a big if. Depending on your web application, workers might be pre-forked, and in this case the cache doesn't work across processes.

    A minimal example to reproduce that is:

    from functools import lru_cache
    from multiprocessing import Process
    
    
    @lru_cache
    def start_sentry():
        print("starting sentry")
        ...
        return
    
    
    if __name__ == "__main__":
        proc1 = Process(target=start_sentry)
        proc1.start()
        proc1.join()
        proc2 = Process(target=start_sentry)
        proc2.start()
        proc2.join()
    

    You will see "starting sentry" printed twice with this code, because each process got its own cache and they have no way of talking to eachother.