Cache API Data in Node.js Application using Redis


Objectives

Learn how to cache API data in a Node.js application using Redis.

Tech Stack

What is Redis

Redis is an open source, in-memory data structure store used as a database, cache, message broker, and streaming engine. It is a NoSQL database that stores data in key-value pairs.

Fetching API without Redis

Setup

Create a new directory and initialize a new Node.js project. Install Express.js and Nodemon. We will use the JSONPlaceholder API to get some data.

Then, we setup a simple Express.js server that will make a request to the API and return the data. Everything familiar so far. 😇

Run the server and make a request to the API. In this post, we will use Postman to make the API request. The response is shown below. Notice that the response time is around 100ms. However, this is a simple API and the response time is not that long. In a real world application, the response time can be much longer. Therefore, we need to cache the data to improve the performance of the application.

Use Redis

Setup

Install Redis and the Node.js Redis client. Then, we create a Redis client and connect to the Redis server. We will use the GET and SET methods to get and set data in Redis.

Checkout the Node-redis documentation for more information. This guide is amazing and it has a lot of code examples. I highly recommend you to check it out!

In the code below, we create a Redis client and connect to the Redis server. Then, we use the GET method to get the data from Redis. If the data is not in Redis, we will make a request to the API and store the data in Redis using the SET method.

Now we run the server and make a request to the API. The response is shown below. Notice that the response time is around 100ms if we don't cache the API data (our previous approach). However, the response time is around 20ms when we cache the API data using Redis. This is a huge improvement!

Send query parameters

We can also send query parameters to the API. In the code below, we cache the data with the query parameters.

Now, the key of the data in Redis becomes: `photos?albumId=${albumId}`. We can check the key of the data in the redis server using the KEYS * command.

Let's make a request to the API with query parameters. The response time is significantly reduced. This is because we cache the data with the query parameters. The data is smaller and it is faster to retrieve the data from Redis.

That's it! We have successfully cached the API data using Redis. Isn't it amazing? Fast and simple!

Conclusion

In this post, we have learned how to cache API data using Redis. We have also learned how to send query parameters to the API and cache the data with the query parameters. This is a simple example, but the concept can be applied to a real world application. I hope you find this post useful. Thanks for reading! 😃

Resources