Trust me, Redis really makes your app super fast.
Tags: redis, javascript, opensource, programming
Published: 2022-09-16 11:46:41

> Redis is super fast, Trust me. At the end of this article our sample app shows you how we went from a response time of 742 milliseconds to 5 milliseconds using Redis.

## What is Redis?
Redis, which stands for Remote Dictionary Server, is a fast, key-value data store initially created to improve application scalability and speed. Today, Redis is now used as a database, cache, message broker, and queue.

Redis provides sub-millisecond response times, allowing for millions of requests per second for real-time applications in a lot of industries Today, Redis is one of the most popular open-source engines, having been named the "Most Loved" database by Stack Overflow for five years in a row and currently ranking second in 2022. 

> Redis is a popular choice for caching, session management, gaming, leaderboards, real-time analytics, geospatial, ride-hailing, chat/messaging, media streaming, and pub/sub apps due to its fast performance.



## Benefits of using Redis

**Performance**
Redis's memory-based design allows for low latency and high throughput data access. In-memory data stores, as opposed to conventional databases, don't require a trip to the disk, cutting engine latency to microseconds. In-memory data stores can therefore support orders of magnitude more operations and provide quicker responses. As a result, operations like reads and writes typically take less than a millisecond, and millions of operations can be supported per second.


**Flexible data structures**
Redis offers a wide range of data structures to satisfy the requirements of your application. Data types in Redis include:

- **Strings** – a sequence of characters, either as a literal constant or as some kind of variable or binary data up to 512MB in size
- **Lists** – abstract data type that represents a finite number of ordered values
- **Sets** – a collection of elements in an unordered collection of strings with the ability to intersect, union, and diff other set types
- **Sorted Sets **– well-defined objects or sets ordered by a value
- **Hashes** – a data structure for storing a list of fields and values
- **Bitmaps** – a compact data structure to store binary logic and states. It is a data type that offers bit-level operations
- **HyperLogLogs** – a probabilistic data structure to estimate the unique items in a data set
- **Streams** - a log data structure message queue
- **Geospatial** - a longitude-/latitude-based entries Maps
- **JSON** - a named value object that supports nested, semi-structured objects such as numbers, strings, Booleans, arrays, and others.


**Simplicity and ease-of-use**
Redis makes it possible to write traditionally complex code in smaller, more concise chunks. Redis allows you to store, access, and use data in your applications with fewer lines of code.


**Persistence and Replication**
Redis uses a primary-replica architecture and asynchronous replication, which allows data to be replicated to multiple replica servers so as to improve read performance (as requests can be distributed among the servers) and allows for faster recovery when the primary server fails.



## Popular Redis Use Cases

**Caching**
Redis is an excellent choice for building a highly available in-memory cache to reduce data access latency, increase throughput, and relieve load on your relational or NoSQL database and application. Redis can serve frequently requested items in sub-milliseconds and allows you to easily scale for higher loads without expanding the more expensive backend.


**Messaging, and Queues**
Redis is an excellent choice for high-performance chat rooms, real-time comment streams, social media feeds, and server-to-server communication. A lightweight queue can be easily implemented using the Redis List data structure. Lists support atomic operations as well as blocking, making them suitable for a wide range of applications that require a dependable message broker.


**Session handling**
Redis provides the sub-millisecond latency, scalability, and resilience needed to manage session data such as user profiles, credentials, session state, and user-specific personalization.


**Media streaming**
Redis can be used to store metadata about video viewing histories alongside user details for millions of users, as well as media manifest files to enable scalable and optimized video streaming to millions of users at once.


**Real-time Analytics**
Redis can be used as an in-memory data store with streaming solutions such as Apache Kafka and Amazon Kinesis to ingest, process, and analyze real-time data with sub-millisecond latency.


**Rate Limiting**
One of the best ways to implement a rate-limiting mechanism in your application is to use an integer-based Redis key that expires after a set period of time to prevent your users or other malicious agents from abusing server resources.



## How to use Redis
When running Redis, you have several options. You can use the Redis CLI on your development or production machines, you can use Redis Stack, which is an extension of Redis that adds modern data models and processing engines to provide a complete developer experience, or you can run Redis on the cloud via Redis Labs, which is a cloud-based solution for running Redis at scale.

In our example project, we will work with the Redis CLI. 
Let’s proceed to installing Redis on a windows machine.



## How to Install Redis CLI
How you install Redis depends on your development workflow. If you’re installing Redis on your local development machine, you can install natively, or you can install using docker container.


To install Redis on your computer, [click here](https://redis.io/docs/getting-started/installation/) to access the official installation guide for your preferred operating system.


To install Redis on Windows, you must first enable WSL2 (Windows Subsystem for Linux). WSL2 allows you to run Linux binaries on Windows natively. To use this method, you must be running Windows 10 version 2004 or higher, or Windows 11.

If you're a windows user, follow the steps as outlined below:


**Step 1:**
Install or activate WSL2 using the instruction [here](https://docs.microsoft.com/en-us/windows/wsl/install)

**Step 2:**
Open command prompt or power shell and execute the following commands:

```
curl -fsSL https://packages.redis.io/gpg | sudo gpg --dearmor -o /usr/share/keyrings/redis-archive-keyring.gpg

echo "deb [signed-by=/usr/share/keyrings/redis-archive-keyring.gpg] https://packages.redis.io/deb $(lsb_release -cs) main" | sudo tee /etc/apt/sources.list.d/redis.list

sudo apt-get update

sudo apt-get install redis
```

**Step 3:**
Start the Redis server like so using command prompt or your preferred terminal:

```
sudo service redis-server start
```

**Step 4:**
Connect to Redis
You can test that your Redis server is running by connecting with the Redis CLI using your preferred terminal

```
redis-cli
127.0.0.1:6379> ping
PONG
```

If you entered the command **ping** and received **PONG** as response, you're good to go. Redis is now running on your machine.

Using the Redis CLI, we can send commands to and read replies from the Redis server. This is how we perform a variety of operations using Redis Commands.


[Click here](https://redis.io/commands/) to see the list of commands curated by the Redis team.


A quick example of adding and reading replies from the Redis server.


```
SET username "marvelous"

GET username

DELETE username
```

## Practical Example
Setup an expressjs application.

```
# initialise a new node project
npm init -y

# install expressjs, redis and node-fetch
npm i express redis node-fetch

# for the purpose of this example i am using nodejs v18
# open the project in your favorite code editor
```


Create a new file called `main.js` and add the following code snippet to the file.


```
import redis from 'redis';
import fetch from 'node-fetch'
import express, { response } from 'express'
import {itemCache} from './middleware.js'

//set constant express port
const PORT = 3000;

//set constant redis port
const RPORT = 6379;

// initialise node redis client
export const client = redis.createClient({
    legacyMode: true,
    RPORT
})

// connect to redis client
client.connect();

// create express app instance
const app = express()

// set public API base url
const factApiBase = 'https://jsonplaceholder.typicode.com'

// fetch todos from jsonplaceholder api
async function getItems(req, res) {
    try {
        // fetch todos from jsonplaceholder API
        const response = await fetch(`${factApiBase}/todos`)
        const result = await response.json()
        // cache stringified data to redis
        client.set("items", JSON.stringify(result))
        res.send(result)
    } catch (err) {
        console.error(err);
        res.status(404)
    }
}

// express route
app.get(`/items`, itemCache, getItems)

// launch express app
app.listen(PORT, () => {
    console.log(`App is listening on port ${PORT}`);
});
```

Create a `middleware.js` file, and add the following code expressjs middleware snippet to the file.

```
// cache middleware for fetching todos from redis
import {client} from './main.js'
export function itemCache(req, res, next) {
    client.get("items", (err, data) => {
        if (err) throw err;
        if (data !== null) {
            res.send(JSON.parse(data))
        } else {
            next()
        }
    })
}

```


Now run your application using the following command.

```
node main.js
```

To test the performance of our app, open up postman or an alternative API testing/development tool.


This is our response time without a cache (742 milliseconds)
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/onp70jyr12tgu2l5mtlp.png)

This is our response time with the cached response from Redis (5 milliseconds)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6tfqlpipb61i59grbqu9.png)



## Conclusion
Redis is an open-source project with a thriving community.
It has no vendor or technology lock-in, supports open data formats, and has a diverse set of clients.

We stringified and passed JSON strings in the preceding example; however, when working with JSON in Redis, it is preferable to use Redis JSON via the Redis stack. Redis has numerous practical use cases in modern applications.
While the list above is not exhaustive, I will be writing about the Redis stack and Redis toolings to help speed up your apps and development workflows.
If your application requires fast response times and scalability, you should always consider using an in-memory database.

This post is in collaboration with Redis.

- [Try Redis Cloud for free](https://redis.info/3NBGJRT)
- [Watch this video on the benefits of Redis Cloud over other Redis providers](https://redis.info/3Ga9YII)
- [Redis Developer Hub - tools, guides, and tutorials about Redis](https://redis.info/3LC4GqB)
- [RedisInsight Desktop GUI](https://redis.info/3wMR7PR)