Search code examples
cachingredisnode-redis

How to update Radis for dynamic values?


I am working with some coaching using Redis in Nodejs.

Here is my code implementation:

redis.get(key)

if (!key) {
    redis.set(key, { "SomeValue": "SomeValue", "SomeAnohterValue": "SomeAnohterValue" }
}
return redis.get(key)

Till here everything works well.

But let's assume a situation where I need to get the value from a function call and set it to Redis and then I keep getting the same value from Redis whenever I want, in this case, I don't need to call the function again and again for getting the value.

But for an instance, the values have been changed or some more values have been added to my actual API call, now I need to call that function again to update the values again inside the Redis corresponding to that same key.

But I don't know how can I do this.

Any help would be appreciated.

Thank you in advance


Solution

  • First thing is that your initial code has a bug. You should use the set if not exist functionality that redis provides natively instead of doing check and set calls

    What you are describing is called cache invalidation and is one of the hardest parts in software development

    You need to do a 'notify' in some way when the value changes so that the fetchers know that it is time to grab the most up to date value.

    One simple way would be to have a dirty boolean variable that is set to true when the value is updated and when fetching you check that variable. If dirty then get from redis and set to false else return the vue from prior