Maximizing API Efficiency: A Guide to Using Redis

Introduction

Redis is a powerful in-memory database that stores data in a key-value format. When integrated into your application, it can significantly boost performance and reduce response times, especially for frequently accessed data.

This guide walks you through how to configure and use Redis to improve your API’s efficiency. You’ll learn how to apply Redis to optimize GET, POST endpoints using practical caching strategies.

Begin by installing Redis on your local machine.

  • For Windows, download it from the official Redis website or use a compatible Redis build like package called Memurai.

  • For macOS, run brew install redis via Homebrew.

To demonstrate this, you will use this sample project RESTAURANT-MENU API GitHub repository, which is a simple CRUD-based backend for managing restaurant menu items. You can clone this project from GitHub and follow the setup instructions in the README file to get it running locally on your machine.

Once set up, you will test the API by:

  • Creating a new menu with a POST request.

  • Fetching the menu list with a GET request where Redis will play a role in accelerating the response.

Upon initiating a POST request to craft a menu listing for the restaurant, the ensuing outcome is as follows:

This process exemplifies how the RESTAURANT-MENU API facilitates menu management and interaction via the implemented endpoints.

Upon sending a GET request to retrieve the restaurant's menu list, you will receive the following outcome.

Essential Redis Commands for API Development.

Most used Redis commands:

  1. GET Command:

    Purpose: Retrieves the value associated with a given key.

    Usage:

     GET <key-name>
    

    This command returns the value stored in the specified key, or nil If the key doesn't exist.

  2. SET Command: Stores a value under a specific key. The value must be stringified before storing.

     SET key-name "value"
    

    You can also set an expiration time (in seconds) for automatic deletion:

  3.   SET key-name "value" EX 3600  // Expires in 1 hour
    
  4. DEL Command: Deletes a key and its associated value from Redis.

     DEL key-name
    

    This is commonly used to invalidate cached data manually.

While Redis supports many other commands, these three are among the most commonly used for basic caching operations: storing, retrieving, and deleting key-value pairs.

Installing Redis and ioredis.

To integrate Redis into your Node.js application, you will need to install the ioredis library, a popular and robust Redis client.

To install the package using the ioredis library, Use the following command with your preferred package manager:

yarn add ioredis
npm install ioredis

Setting Up Redis

After installing the ioredis package the next step is to configure Redis in your application.

Follow these steps:

  1. Create a new folder named config inside the src directory.

  2. Inside the config folder, create a file called redis.config.ts.

  3. In redis.config.ts, import the ioredis package and set up the Redis connection:

import { Redis } from 'ioredis';
import dotenv from 'dotenv';
dotenv.config();

const connection = new Redis({
    host: process.env.REDIS_HOST,
    port: Number(process.env.REDIS_PORT),
    password: process.env.REDIS_PASSWORD,
});

connection.on('connect', () => {
    console.log('Connected to redis');
}).on('error', (error) => {
    console.log(error);
}).on('close', () => {
    console.log('Connection to redis closed');
})


export default connection;

This code establishes a connection to your Redis server using the specified host, port, and optional password from environment variables. You can customize the configuration further if needed, for example, by enabling TLS or setting retry strategies.

Make sure your .env file includes the following entries:

REDIS_HOST=127.0.0.1
REDIS_PORT=6379
REDIS_PASSWORD=

Once you've created the Redis connection file (redis.config.ts), the next step is to use it in your application. Inside your src/server.ts file (which initializes your server and database connections), import the Redis config to ensure the Redis client connects when the server starts.

When you run your server, you should see a message in your terminal like: connected to Redis.

This confirms that Redis is successfully connected and ready to use within your application.

Implementation of Redis

To start using Redis in your application logic, import the Redis client into your controller.

Open menu.controller.ts and add the following import at the top of the file:

This gives you access to Redis methods such as get, set, and del, allowing you to integrate caching functionality directly within your controller logic.

In your menu.controller.ts file, you'll use the dotenv package to access environment variables. Specifically, define a Redis cache key (e.g., MENU_RESTAURANT_CACHE) using:

const MENU_CACHE_KEY = process.env.MENU_RESTAURANT_CACHE;

This variable will act as the Redis key used to store or retrieve your restaurant menu data. To set this up, add the following line to your .env file:

MENU_RESTAURANT_CACHE=restaurant:menu:list

Since Redis stores data as key-value pairs, this environment variable helps standardize the key name used throughout your application.

Redis in POST Request – Ensuring Cache Freshness

In the provided image, the utilization of the Redis client is demonstrated to delete a specific key using the DEL command. This Redis command is used here as a cache invalidation strategy. The rationale behind deleting the key when creating a new record is to guarantee that any subsequent retrieval of data does not rely on outdated or stale values that may exist in the cache.

Redis in GET Request – Lazy Loading with Cache-Aside

In the provided image, a method within the MenuController class is responsible for retrieving all menus associated with a restaurant. It uses Express’s request and response objects to handle the API call.

The method begins by attempting to fetch the data from Redis using:

await redisClient.get(key);

This checks whether the required data is already cached.

  • If the data exists in Redis (a cache hit), it’s returned immediately, significantly improving response time.

  • If the key is missing (a cache miss), possibly because it was deleted during a POST request, the method fetches the data from the database.

After retrieving fresh data from the database, the method stores it back in Redis using:

await redisClient.set(key, JSON.stringify(data));

An expiration time of 7 days is also set to ensure the cache remains fresh.

This technique follows the Cache-Aside pattern (also known as Lazy Loading), where the application manually handles both reading from and writing to the cache, depending on whether the data is already present.

Consequently, any subsequent attempts to retrieve the same data will involve fetching it from the Redis cache rather than directly from the database. This approach significantly improves the server's response time to client requests. This pattern continues as long as no new records are created. During this period, data retrieval will consistently utilize the cached data stored in the Redis cache.

The results above show that the subsequent request to fetch the data will be provided from the cache. Now, go to your terminal and enter the following command to check the data stored inside the redis cache.

Redis CLI Usage:

redis-cli

Once you open your terminal and run redis-cli, you will be connected to your local Redis instance at 127.0.0.1:6379.

From there, you can inspect cached data using:

sada

Once you type redis-cli in your terminal, you will be connected to the Redis port, which is 127.0.0.1:6379. In your redis-cli terminal, you can now use the GET method by typing GET <key>. Here, the key is the name you give to the Redis key for it to store your value. When you press the Enter key, you should be able to see the value stored in that key.

Conclusion

In summary, this guide explored how to maximize API efficiency using Redis. You learned how to install and configure Redis, use essential commands like GET, SET, and DELand integrate Redis into your API endpoints to enhance performance.

We demonstrated the Cache-Aside (Lazy Loading) pattern to accelerate GET requests and maintain cache consistency when handling POST operations. By caching frequently accessed data and invalidating outdated entries, your APIs become faster, more efficient, and scalable.

Redis, when used correctly, becomes a powerful ally in building high-performance backend systems.

💡 If this guide helped you, feel free to connect with me on Twitter | LinkedIn | GitHub

See you in my next blog article. Take care!!!

0
Subscribe to my newsletter

Read articles from Alao Abiodun AbdulRahman directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Alao Abiodun AbdulRahman
Alao Abiodun AbdulRahman

I'm a backend Engineer. I love building microservices, doing some API integrations.