Let's say I have 4 load-balanced Python API processes that calculate the factorial of a number.
Let's say factorial returns a Pydantic object or deeply nested dict. I do not want to use Redis for caching because nested dict/list serialization is expensive. So I use the LRU function cache.
Problem: 4 LRU caches exist for each process. When I clear the cache it clears for only 1 process (whichever catches the request).
- I want to share the LRU cache between all 4 processes. Would a custom decorator using multiprocessing.shared_memory be possible?
- If that is not possible, I want to at least clear the cache of all processes. Using multi-processing Queue or Listener/Client blocks the API functionality as I have to
while True.
Multiple Python API processes running this code:
from functools import lru_cache
# result:
# caches factorial for this process
# wanted:
# caches factorial for all 4 processes
@lru_cache
def factorial(n):
return n * factorial(n-1) if n else 1
@api.get("http://localhost:5000/purge/factorial/") # pseudo API decorator
def cache_clear():
# result:
# clears cache for this process
# wanted:
# clears cache for all processes
factorial.cache_clear()
I use:
Thank you very much!