A Beginners Guide to Redis
Tags: beginners, redis, programming, cache
Published: 2021-04-04 09:53:00

As a backend developer, transitioning from junior to middle is a pretty steep curve.

I've realized that I have to learn all sorts of technologies. 

Cloud? AWS, Azure.

Caching? Redis, Memcached.

Message Brokers? RabbitMQ, Kafka.

The list is endless, this is why I'm dedicating a blog post to every single tool that I'm not familiar with, starting with Redis.

## Table of Contents

- [What is Redis?](#1)
- [Prerequisites](#2)
- [Installing Redis](#3)
- [Redis Commands](#4)
- [Redis Data Structures](#5)
- [Where to learn more?](#6)
- [Concluding Thoughts](#7)

## What is Redis? <a name="1"></a>

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/heslrb6j936ykx0s19ug.png)

Redis is an in-memory database that persists on disk. The data model is key-value, but many different kinds of values are supported: Strings, Lists, Sets, Sorted Sets, Hashes, Streams, HyperLogLogs, Bitmaps. 

This is a very fair description but for the sake of simplicity let us break this down. 

"*Redis is an in-memory database that persists on disk"*

There are two statements here:

- Redis is a database that gets stored on the random access memory (RAM).
- Redis is persistent, meaning that even if your system is off, you won't lose data.

*PS: There's a lot more to persistence than that, which we will discuss further down the post.*

*"The data model is key-value, but many different kinds of values are supported: Strings, Lists, Sets, Sorted Sets, Hashes, Streams, HyperLogLogs, Bitmaps."*

Redis supports many data types but the default data model is of the key-value. Think hashmaps or associative arrays.

### How is Redis better than my SQL/No-SQL database?

Speed.

Yup, that just it, Redis is much faster than your average database.

But why is that?

It mainly comes down to where they are being stored.

Redis databases get saved in the random access memory (RAM) which is much faster than its counterpart where it gets saved in non-volatile storage (hard-drives, solid-state-drives, etc...).

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5jsczasf77tf9r4dlvns.png)

The downside is that it can't outgrow your usual database, but the bar is pretty high. So it's **technically** possible to use Redis as your main database.

### When would I want to use Redis?

While Redis seems, all nice and dandy. You most likely can't simply replace your database with it. It's mostly used in caching data. Caching is the mechanism of storing frequently requested data in memory so that it will be faster to fetch and ease the load to the database. But this is not the only use case for Redis. As of 2021, you can use Redis as a:

- Database
- Cache
- Message Broker
- Server for machine/deep learning models

We will delve deep into each use case further down the post.

## Prerequisites <a name="2"></a>

We will work on a containerized version of Redis, for that we need to install:

- Docker (I'm using version 20.10.5) but you simply use the latest version.

## Installing Redis <a name="3"></a>

Make sure your docker service is running if not then run this command on Linux.

`sudo systemctl start docker`

Let us create a Redis instance.

`docker run --name redis -d redis`

Here we are basically creating a new docker container called redis using the Redis image take from [DockerHub](https://hub.docker.com/_/redis).

To make sure your container us up and running, run the command to list all containers:

`docker ps`

You should see something like this.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/v29p7nm8kwjfr2vy84fo.png)

Moving on, run the command to bash into the Redis docker container.

`docker exec -it redis bash`

Now you should be inside the docker container.

### Redis-CLI

Redis comes bundled in with its command-line interface (CLI) tool called plainly Redis-CLI. To check whether Redis-CLI is working run this command inside the Redis container:

`redis-cli -v`

You should see something like this:

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wamz2y1ker3gdf3sxmj5.png)

Currently, I'm using version 6.0.7 but using any other version is fine.

Congratulations you got Redis setup, let us go over the data structures that Redis provides us.

## Redis Commands <a name="4"></a>

Before we move on to specific data structure commands let us go over the basic commands that the redis-CLI provides for us.

**Entering the Redis-CLI**

Make sure your Redis server is running, and run the command:

`redis-cli`

**Exiting the Redis-CLI**

`exit`

**Setting a key**

`SET key value`

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/w28wf6iwyhkkmx36npcz.png)

**Getting a key**

`GET key`

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/al7c3ocku35a794i8xy8.png)

**Listing all keys** 

`KEYS *`

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wd03n88krgy7s4e5y7jj.png)

**Deleting a key**

`DEL key`

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dv1d94rsiofz4861sg0o.png)

**Dumping a key**

`DUMP key`

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bkcj6xbl0cyyo32pjvrx.png)

**Check whether a key exists**

`EXISTS key`

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1gabpafc3jajs786t0in.png)

**Set key expiry**

`EXPIRE key seconds`

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0breji8vmfzcjdd2qam3.png)

**Gets the remaining time in keys expiry in seconds.**

`TTL key`

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i4spq4kma2t4l5m3orwa.png)

## Redis Data Structures <a name="5"></a>

### How are they implemented?

Redis is implemented in C, so naturally, all data structures internally are also implemented in C. Furthermore to allocate memory to these data structures, Redis wraps `malloc` in something called [zmalloc](https://github.com/redis/redis/blob/unstable/src/zmalloc.h). This allows Redis to select between different alloc libraries. A popular one is [jemalloc](https://github.com/jemalloc/jemalloc) due to its focus on avoiding fragmentation.

### Strings

Strings are the most basic data type in Redis, they are binary safe, meaning we can store any kind of data, such as a JPEG image or a Ruby object.

A String value can be at a maximum of 512 MB.

You can read more about the string commands [here](https://redis.io/commands/#string).

### Lists

Lists in Redis are basically a list of strings, sorted by insertion order. You can add items in both ends of the list (head and tail) by using the commands `LPUSH` and `RPUSH`.

You can read more about list commands [here](https://redis.io/commands#list).

### Sets

Redis sets are unordered collection of strings. There time complexity for insertion and deletion is constant time O(1). Like normal sets, Redis sets only contain unique values, meaning that if you try to put a duplicated value it won't show up in the set. With that in mind, Redis gives us some useful commands to manipulate sets:

- Union
- Intersection
- Difference

You can read more about set commands [here](https://redis.io/commands#set).

### Hashes

Redis hashes like normal hashes represent key-value pairs. You usually use hashes to represent objects. Hashes are the most versatile data type out there, so you can represent lots of different elements.

You can read more about hash commands [here](https://redis.io/commands#hash).

### Sorted Sets

Redis sorted sets are very similar to sets, the only big difference is that sorted sets keep score of an element. Elements are unique but scores may be repeated. This is useful in gaming leader-boards where you can rank the users from smallest to largest in x-category.

You can read more about sorted sets commands [here](https://redis.io/commands#sorted_set).

### Bitmaps

Redis Bitmaps are basically arrays of bits. It internally works under the Redis string data structure. 

Thus, the largest domain that Redis can map as a Bitmap is 232 (512 MB = 2^29 bytes = 2^32 bits).

You can read more about bitmap commands [here](https://redis.io/commands/SETBIT).

### HyperLogLogs

Redis HyperLogLog is an algorithm that uses randomization in order to provide an approximation of the number of unique elements in a set using just a constant, and small amount of memory.

HyperLogLog provides a very good approximation of the cardinality of a set even using a very small amount of memory around 12 kbytes per key with a standard error of 0.81%. There is no limit to the number of items you can count unless you approach 2^64 items.

You can read more about HyperLogLog commands [here](https://redis.io/commands/PFCOUNT).

## Where can I learn more? <a name="6"></a>

Below I've compiled down a list of useful resources which may help you in your journey to master Redis.

### Starting out?

You can take the official Introduction to Redis Course: 

[https://university.redislabs.com/courses/ru101/](https://university.redislabs.com/courses/ru101/)

FreeCodeCamp also has a great introductory video to Redis.

[https://www.youtube.com/watch?v=XCsS_NVAa1g&t=2279s](https://www.youtube.com/watch?v=XCsS_NVAa1g&t=2279s)

Redis University also has an official YouTube channel with great videos, you should check them out.

[https://www.youtube.com/channel/UCybK6TMZFQeSN74jzTiDWfg](https://www.youtube.com/channel/UCybK6TMZFQeSN74jzTiDWfg)

### Useful Links

[Best Practices](https://redislabs.com/redis-best-practices/introduction/)

[Documentation](https://redis.io/documentation)

[Slideshow](https://static.simonwillison.net/static/2010/redis-tutorial/)

## Closing Thoughts <a name="7"></a>

Today we went through the basic introduction to Redis. I hope you learned something today, if you got any questions leave them down in the comments, and I will answer with the best of my ability.