Using Redis for Caching

As mentioned, Redis is a key value store. Super simple concept, we set a value for a key, and later we can retrieve that value by using that key. There are a lot of things to consider here however. Redis stores all of this in memory and we do not have infinite memory to store values. How should we choose which keys to eventually dispose of? We'll worry about that in a bit. First, let's quickly demo the key value functionality of Redis in redis-cli.

We call set on a key and a value to set that key value pair. We call get on the key to retrieve the value.

Easy.

Let's also look at how to use a hash in Redis using hset and hget.

How can we leverage this in node for caching? Well, we're going to specifically be concerned with caching queries to our DB. Imagine if you will, several users want to query a list of books, or a specific book even. In this imaginary scenario, we know that our list and our individual books don't change often. And we also know our users are querying for these items several thousand times per minute. Why tax our database with queries when we know that all thousand requests in that minute are going to return the same results? What if we could store the results of that query and first check if we already know the results to that query before we ask that database for the results? That is exactly how we are going to use Redis in this example.