Redis is a type of database that you can add to your production level applicaiton to make it more performant.

In this article, I'll go over some Redis basics and show a real world example of Redis in action.

Here's everything we'll go over:

  1. What is Redis?
  2. Why the Hype Around Redis?
  3. When Should You Use Redis?
  4. How to Install Redis
  5. Basic Redis Commands
    1. Lists
    2. Sets
    3. Hashes
  6. How to Use Redis to Increase Performance in Your Applications
  7. How to Use Redis as a Primary Database

Let's dive in.

What is Redis?

Redis stands for Remote Dictionary Service, and is an in-memory database with latency that can be less than 1 millisecond.

What makes Redis so powerful is that it stores the data in RAM and not on slower hard disks. Every data point a Redis database is a key-value pair.

The value can be any of the following fields:

  1. String: "Hello World"
  2. Bitmap: 0011001
  3. Bitfield: {325}{655}{678}
  4. Hash: {a: "Hello", b: "World"}
  5. List: [ A > B > C ]
  6. Set: { A, B, C}
  7. Sorted set: {A: 1, B: 2, C: 3}
  8. Geo-spatial: {A:(52, 2, 3)}
  9. Hyperlog
  10. Stream

Why the Hype Around Redis?

Redis is so popular because of it's speed.

Unlike a relational database where the data is stored on slower hard disks, Redis stores the data in RAM, which is much faster. Redis takes milliseconds to access data as opposed to many hundreds of milliseconds using traditional methods.

But due to its usage of RAM, Redis is volatile, meaning that, when the system shuts down, your data is also lost. Hence, Redis is usually used for caching, and not as a persistent database like MongoDb or PostgresSQL.

Nowadays, Redis is more capable. We'll get to this towards the end of the article.

When Should You Use Redis?

Redis is not a replacement for traditional, hard disk based databases. Instead, it complements your existing database.

If you have data that needs to be accessed frequently, or you have some queries that take a lot of time to execute, Redis is a great choice.

How to Install Redis

Basic Redis Commands

Startup Commands

To start Redis, open a terminal and run the following commands:

  • redis-server: Starts the Redis server
  • redis-cli: Opens the Redis CLI. To quit, use the quit command

Basic commands

  • SET name your-name: Sets a key to a value
  • GET name: Gets the value of a key
  • DEL name: Deletes a key-value pair
  • EXISTS name: Checks if a key exists
  • KEYS *: Gets all the stored keys
  • flushall: Clears all data

Expiration

  • ttl key-name: Checks how long a key has before being deleted automatically. If the result is -1 it means ttl (Time To Live) is not set and it wont expire
  • expire key-name 10: Sets a ttl of 10 seconds
  • setex name 10 your-name: Set a ttl of 10 seconds while setting a the key-value pair

Lists

Lists are useful when you want to implement a queue or stack, like in the case of a messenger app, where you need to cache some recent messages.

  • lpush fruits apple: Pushes an item to the left of a list
  • rpush fruits mango: Pushes an item to the right of a list
  • lrange fruits 0 -1: Gets all the items from a list. -1 stands for the index at the end of the list
  • LPOP fruits: Removes the leftmost item in the list
  • RPOP fruits: Removes the rightmost item in the list

Sets

Sets are similar to lists. What makes a set different is that it will only store unique values.

  • SADD todo "read book": Adds an item to the set. If you try to add "read book" to the same set, it won't be added because it's a duplicate
  • SMEMBERS todo: Shows all the items in the todo set
  • SREM todo "read book": Removes an item from the set

Hashes

Whereas listss and setss in Redis hold sequences of items, Redis hashes store a map of keys and values

  • HSET person name John: Stores the key name with the value John
  • HGET person name: Returns the value associated with the key name. In this case, it returns John
  • HGETALL person: Gets all the keys and values associated with person
  • HDEL person name: Removes the name property
  • HEXISTS person name: Checks if the name propery exists in person

How to Use Redis to Increase Performance in Your Applications

First, install Redis:

npm i redis

Start the Redis server:

redis-server

Import the Redis package and create and instance:

// Import Redis
const Redis = require('redis')

// Create a Redis client for local development
const redisClient = Redis.createClient()
// Or for production, pass in your production instance's URL 
const redisClient = Redis.createClient({ url: "your-production-url"})

Then, you can use the redisClient instance to do everything mentioned earlier in the article. For example:

redisClient.setex('photos', 3600, JSON.stringyfy(some-value-to-store))

Without Redis caching, this code takes about 480ms to fetch 900kB of data:

app.get("/photos", async(req, res) => {
    const albumId = req.query.albumId
    const { data } = await axios.get(
        "https://jsonplaceholder.typicode.com/photos"
        { params: { albumId }}
    )
})

After adding Redis caching, fetching photos still takes around 480ms to fetch 900kB of data the first time around. But after that, each subsequent fetch only takes about 37ms:

// Import redis package
const Redis = require('redis');

// Create redis client, in case ofer development only
const redisClient = Redis.createClient();
// Incase of production pass your production instance url and use the below line
const redisClient = Redis.createClient({ url: 'your-production-url' });

app.get('/photos', async (req, res) => {
  const albumId = req.query.albumId;
  redisClient.get('photos', async (error, photos) => {
    if (error) console.error(error);
    if (photos != null) {
      return res.json(JSON.parse(photos));
    } else {
      const { data } = await axios.get('https://jsonplaceholder.typicode.com/photos', {
        params: { albumId }
      });
      redisClient.setex('photos', 3600, JSON.stringyfy(data));
      res.json(data);
    }
  });
});

Now that's a serious performance gain!

In the example above, first it checks if you already cached a photo in your Redis cache. If it's cached, the cached value is returned. Otherwise, the photos are fetched from the API.

How to Use Redis as a Primary Database

By nature, Redis is super fast, and doesn't need additional caching layers. But a necessary requirement of a database is to model complex relationships.

Don't worry — Redis has you covered.

Redis can be used a multi-model database. It supports a variety of database paradigms with the help of various modules. Some of the most popular Redis modules are:

  1. RediSearch: Full-text search of Redis
  2. RedisGraph: A graph database with a cypher-based querying language
  3. RedisBloom: Scalable Bloom filters
  4. RedisJson: A JSON data type for Redis
  5. RedisAI: A module for deep learning
  6. Neural-redis: Neural networks that work as Redis data types
  7. RedisTimeSeries: A time-series data structure

You can check out all these modules and more at redis.io/modules.

And you can play around with all of the Redis modules on the Redis Enterprise Cloud (free tier).

Until Next Time

👋 Do you want to code and learn along with me? You can find more web development related content here on my blog. Just open up your favorite code editor and get started.