Introduction to Caching (Redis + Node.js)

Emad Elmogy
tajawal
Published in
3 min readFeb 23, 2019

This article is a very simple introduction to Redis and how caching works, by means of an example, show you how you can take advantage of Redis for caching in order to improve your application speed and performance.

What is Redis?

According to official definition on redis.io, Redis is an open source (BSD licensed), in-memory data structure store, used as a database, cache and message broker. It supports data structures such as strings, hashes, lists, sets, sorted sets with range queries, bitmaps, hyperloglogs, geospatial indexes with radius queries and streams. Redis has built-in replication, Lua scripting, LRU eviction, transactions and different levels of on-disk persistence, and provides high availability via Redis Sentinel and automatic partitioning with Redis Cluster.

Let’s look into what caching is and how it can make your web application faster.

What is Caching?

Caching is the process of storing data into a cache. A cache is a temporary data store where data is kept for later use.

A cache as a data store is easier for the client (or server) to reach, as opposed to a permanent data store that might be located on a different service, which takes more time and resources to reach (a database or an external API endpoint).

Now that you have an understanding of what Caching and Redis are, let’s build a very basic project that implements caching using Redis.

Install Redis :

If you an OSX user, you can install using the command below. For other platforms, please follow the guide on https://redis.io/download.

brew install redis

Create a new directory

mkdir redis-cache

Navigate to the new directory

cd redis-cache

Generate a package.json file

npm init --force

--force tells npm to use the default options while generating the package.json so you are not asked any questions.

After running the command above, you should have a package.json file in the redis-cache directory.

Create a file server.js in the directory.

Install Express, Redis, and node-fetch npm modules with below command

npm install --save node-fetch express redis

Now that you have Redis installed, add the following code to the server.js file.

All set now , start you node server with node server.js command from your terminal.

Go to localhost:3000/photos . via Postman and you should see something like that .

First Request :

Second Request :

Take note of the time in the images above .

The first request took 3325 milliseconds while the second one only took 1048 milliseconds.

Conclusion

Redis is very powerful in-memory data-store that we can use in our applications. It’s very simple to save and get data without much overhead. refer https://www.npmjs.com/package/redis for more use cases and refer https://redis.io/commands for more redis commands.

Feel free to clone the repo created for the sake of this tutorial.

--

--