pythoncachingaws-lambdaredisin-memory-cache

Does it make sense to add some in-memory cache when using AWS lambda?


Let's say that I have a value stored in Redis that it's periodically updated. Now, let's say that I want to avoid fetching this value every time I need it in my application: I could cache this value in memory since I know that it's guaranteed that the value won't be updated given one periodic schedule and the next.

Something similar to this implementation.

Given the ephemeral nature of serverless, would this make any sense in an AWS lambda environment? I can imagine that it doesn't for cold start, but does it for warm starts?!


Solution

  • You should be able to achieve this relatively simply, by declaring the variable outside the function handler, just below the imports.

    Once your function sets that value, it remains set for the lifetime of the lambda instance until it's shutdown and needs to be initialised again when it cold starts.

    import json
    
    cached_value = None
    
    def function_handler(event):
      if cached_value == None:
        cached_value = go_get_from_cache()