1

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?!

Murilo Sitonio
  • 270
  • 7
  • 30
  • This might make sense depending on your goal. What are you optimizing? I've only used Redis as a cache on top of a slower data store; I don't need a cache on top of a cache. Are you trying to make Lambda faster? Or trying to remove load from Redis? – Kirk Broadhurst Jul 25 '23 at 01:39
  • Neither of those. I just need a key-value store. – Murilo Sitonio Jul 25 '23 at 01:49
  • You said "I want to avoid fetching this value every time I need it in my application". Why do you want to do that? You already have a key-value store, it's called Redis. – Kirk Broadhurst Jul 25 '23 at 02:01
  • I know. I still want to avoid calling Redis because I pay per command. So imagine I have a periodic task that updates Redis every hour but my users uses these values every minute. It's guaranteed that the value won't change between 2pm and 3pm so I don't need to go check Redis if I keep these values in memory (it's just a few). – Murilo Sitonio Jul 25 '23 at 02:08

1 Answers1

1

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()
chromebookdev
  • 305
  • 2
  • 11
  • 1
    My doubt is not regarding implementation, but rather if it makes sense to do it in the first place. Given your answer, I'd say it does for warm starts. Do you know of any documentation stating this?! – Murilo Sitonio Jul 25 '23 at 11:01
  • Absolutely, and is part of their best practice recommendation https://docs.aws.amazon.com/lambda/latest/dg/best-practices.html "Take advantage of execution environment reuse to improve the performance of your function." – chromebookdev Jul 26 '23 at 12:18
  • If this answers your question, please mark this as your answer @MuriloSitonio :) – chromebookdev Jul 28 '23 at 01:20