Redis (REmote DIctionary Server) is an advanced NoSQL key-value data store used as a database, cache, and message broker. Redis is known for its fast read and write operations, rich data types, and advanced memory structure. It is ideal for developing high-performance, scalable web applications.
Redis is one of the most popular key-value databases, ranking at #4 in user satisfaction for NoSQL databases. The popularity of Redis continues to rise, and many companies are seeking Redis developers for roles like database administrator and beyond.
In this tutorial, we will introduce you to Redis and show you everything you need to get started.
This tutorial a glance:
Learn Redis the easy way
In this go-to guide, you will learn everything you need to get started with Redis, from data types to caching.
Redis is an open-source, in-memory data structure store used as a database, cache, and message broker. Redis was created by Salvatore Sanfilippo in 2006 and is written in C.
It is a NoSQL advanced key-value data store, and is often referred to as a data structure server because its keys contain strings, hashes, lists, sets, sorted sets, bitmaps, and hyperloglogs. Redis’ read and write operations are very fast because it stores data in memory. Data can also be stored on the disk or written back to the memory.
Since Redis stores its data in memory, it is most commonly used as a cache. Some large organizations that use Redis are Twitter, GitHub, Instagram, Pinterest, and Snapchat.
According to the official documentation, the recommended way to install Redis is to compile it from sources. First, download it from the official site and then compile it with these steps:
wget http://download.redis.io/redis-stable.tar.gz
tar xvzf redis-stable.tar.gz
cd redis-stable
make
You can then test your build by typing make test
. The src
directory will be populated with the Redis executables.
It is recommended to copy the Redis server and the command line interface into the proper places using one of two strategies.
sudo make install
sudo cp src/redis-server /usr/local/bin/
sudo cp src/redis-cli /usr/local/bin/
From there, start the Redis server by executing the redis-server
binary (without arguments). Since there are no explicit configuration files, all parameters use the internal default. This is the best way to start if you’re new to Redis and want to explore the environment.
To use Redis from your application, download and install a Redis client library based on the programming language you want to use.
Redis is a key-value store, but it supports many types of data structures as values other than strings. The key in Redis is a binary-safe string, with a max size of 512 MB.
Let’s discuss the data types that are supported in values.
A string in Redis is a sequence of bytes. They are binary safe, so they have a known length that is not determined by any terminating characters. You can store up to 512 megabytes in a Redis string. It can store any type of data, like text, integers, floats, videos, images, or audio files.
redis 127.0.0.1:6379> SET name "educative"
OK
redis 127.0.0.1:6379> GET name
"educative"
In this example, SET
and GET
are Redis commands, which we will discuss later. name
is the key, and educative
is the string value that we are storing.
In Redis, lists are lists of strings that are sorted by an insertion order, so the elements are stored in a linked list. You can add elements to either on the head or tail. If we need to insert an element in a list with 500 records, then it will take the same amount of time as adding the element to a list of 50,000 records.
Here are some examples operations for list the resulting lists:
LPUSH mylist x # now the list is "x"
LPUSH mylist y # now the list is "y","x"
RPUSH mylist z # now the list is "y","x","z" (RPUSH was used this time)
Sets in Redis are unordered collections of strings. This value type is similar to List, but sets don’t allow for duplicates, and the elements are not sorted in any order. You can add or remove members in time complexity.
Sets are useful when we want to store data where uniqueness matters. For example, storing the number of unique visitors to a website.
We can sort elements with a Sorted Set value type. Each element will is associated with a number, which we call a score. This determines the order.
For example, if we have a key called vegetables
, and we want to store carrot
and celery
as the value. The score of carrot
is 10, and celery
is 15. Carrot will be first, followed by celery.
If the score of two different elements is the same, then we check which String is lexicographically bigger.
In Redis, the hash value type is a field-value pair. They are used to represent objects, but can store many elements and are useful for other tasks as well. A hash takes very little space, so you can store millions of objects in a small hash instance.
In fact, a hash can store up to field-value pairs, which equates to more that 4 billion.
Say we want to store the information about the grades of students. The subject can be the key. The value can be a field-value pair, with the field being the student name and the value being the grade of each student.
Here is another example to familiarize you with a Redis hash.
HMSET user:1000 username antirez password P1pp0 age 34
HGETALL user:1000
HSET user:1000 password 12345
HGETALL user:1000
Get a solid Redis foundation without scrubbing through videos or documentation. In this course, you will learn about the various commands that you can use to store different types of data structures.
Educative’s text-based courses are easy to skim and feature live coding environments, making learning quick and efficient.
Redis commands are used to perform operations. There are different commands that we can apply to our various data types. Below, we will go over one command per data type discussed above, but keep in mind that there are tons of commands in Redis.
The simplest form of data that can be stored in the Redis database is string. We will look at two commands used to store and fetch records from the Redis database when using strings.
SET
commandWe can store a record in Redis using the SET
command. This will set a key to hold a string value. If a key already holds a value, it will be overwritten. It has the following syntax:
SET keyValue
GET
commandThe GET
command gives us the value of a key. If the key does not exist, it will return nil
. GET
only handles string values. The syntax is:
GET key
We can also store lists, and The Redis database stores them as a linked list. When we insert a new element, we can insert it either at the head (left-most element) or tail (right-most element). We will look at two commands used to add and remove records from the head when using lists.
LPUSH
command:The LPUSH
command is used to insert a value at the head of the list. We can use one or more values, and the syntax is:
LPUSH key value
Note: Elements are inserted in the reverse order because each element is picked and inserted at the head.
LPOP
commandThe LPOP command is used to remove an element from a list at the head (or the left).
LPOP key
When it comes to list, we allows for duplicate elements. So, if we need to add unique elements, we should use a set, which are internally stored as a hash table. This means that elements are stored randomly, and repetition is not allowed. Let’s see the command to add an element from a Redis set.
SADD
commandThis allows us to add specified members to a set stored at a key. If a key does not exist, a new set is created.
SADD key value
The elements in a Redis set are not stored in any order. So, if we want to store the elements in sorted order, we can use sorted sets, also called ZSets
.
Each element should be assigned a score before it is inserted. The Redis database will sort elements in ascending score order. Let’s see the command to add elements to a sorted set.
ZADD
commandThis command will add elements to the sorted set in the Redis database. We can specify multiple score or member pairs. If a member is already in that sorted set, the score is updated, and the element reinserted at the right position to maintain scoring. Here is the syntax:
ZADD key score value
In Redis, a value can also be a field-value pair, which we call the Hash data structure. Let’s see the command for store a hash in Redis.
HMSET
commandThis command is used to store a hash in Redis. It wills set the fields to their respective values in the hash. This command overwrites fields that already exist in the hash. The syntax of this command is:
HMSET key field value
If using Redis 4.0.0,
HMSET
is considered deprecated, andHSET
is preferred.
Now that we understand some of the basics of Redis and have introduced commands, let’s look at some advanced concepts.
An Important Note on Redis
For this tutorial, in place of Model/Slave terminology, we will be using a progressive
leader
/follower
metaphor. Our use of this terminology will not interfere with your understanding of Redis.Redis’ official documentation uses the Master/Slave model that has been prevalent in computer science for decades, dating back to 1904.
In recent years, there has been a significant push by many organizations to confront and replace this problematic metaphor.
At Educative, we believe in empowering developers and changing the industry for the better. Embracing inclusive terminology is part of that cultural shift.
If you would like to read more about this ongoing discussion, we recommend this article from Wired.
When data is stored on a server and there is a server crash, data can be lost. We use technique of data replication to avoid this issue. This basically means that data is stored on two or more servers to prevent losses or crashes. Data replication also reduces the load on our servers, as user requests are load balanced.
Redis follows a leader/follower approach for server-based data replication. One of the servers is a leader
, and the others servers are the followers
, which are all connected to the leader
. We write everything to the leader
, which then sends the changes to the followers
.
If a follower
is disconnected, it will automatically reconnect and replicate the leader
exactly. This can be done through two methods:
Note: In Redis, the replication process is asynchronous. The
follower
servers asynchronously acknowledge the data from theleader
, so theleader
knows which commands have been processed.
Since Redis is an in-memory database, data is stored in memory (or RAM). If a server crashes, all the data stored is lost. Redis has back-up mechanisms in place for the data on the disk. This way, the data is loaded from the disk to the memory when the server reboots. Redis has two persistence options:
dump.rdb
file. Durability depends on how frequently the data is being dumped to the disk.When the client requires data, they ask a Redis server to provide it, which takes a lot of bandwidth each request. We can cache the results for the most commonly used keys on the client side to improves performance.
Redis provides support for client-side caching, which is called tracking. There are two different approaches:
You should now have a good idea how Redis works and what it can do for your applications. This is a powerful tool that is growing in popularity. Any developer should have some solid Redis skill in their tool belt. But there is still more to learn.
Next you should look into:
To get started with these concepts, and to get some practice with Redis commands, check out Educative’s course Complete Guide to Redis. This is your go-to guide to Redis. You will learn about the various commands that you can use to store different types of data structures in Redis. You will also become familiar with transactions, security, partitioning, and clustering.
Happy learning!
Free Resources