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:
- What is Redis?
- How to install Redis
- Redis Data Types
- Redis Commands
- Advanced Redis Concepts
- What to learn next
What is Redis?
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.
Advantages of Redis
- Speed: Redis is very fast. It can perform 110,000 SETs per second and 81,000 GETs per second.
- Supports rich data types: Redis supports most of the data types, such as list, set, sorted set, and hashes. This gives you a ton of flexibility
- Operations are atomic: This ensures that if two clients access data concurrently, the Redis server will receive an updated value.
- Versatile uses: Redis can be used for caching, messaging-queues, and short-lived data such as web application sessions.
- Easy to set up: Redis is easy to configure
How to install Redis
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
- Manually with the following commands:
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 Data Types
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.
String
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.
List
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
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 O(1) 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.
Sorted Sets
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.
Hash
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.
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
Redis Commands
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.
Storing strings 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
command
We 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
command
The 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
Storing lists in Redis
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
command
The LPOP command is used to remove an element from a list at the head (or the left).
LPOP key
Storing sets in Redis
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
command
This 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
Storing sorted sets in Redis
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
command
This 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
Storing a Hash in Redis
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
command
This 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.
Advanced Redis Concepts
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.
Data Replication in Redis
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:
- Partial Synchronization
- Full Synchronization
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.
Persistence
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:
-
RDB persistence (snapshotting): Snapshots of the data are stored in a disk in a
dump.rdb
file. Durability depends on how frequently the data is being dumped to the disk. - Append-only file (AOF) persistence: Every write operation received by the server is logged into a file, so all the commands in the AOF file are run again when rebooted.
Client-side caching
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:
- Default mode: The server stores the information of which key is stored by which client. If a key is changed, the server sends the message only to the relevant clients.
- Broadcasting mode: The server does not need to keep track of the keys cached by clients. Instead, clients subscribe to key prefixes and receive notification messages when a key matching a certain prefix is used.
What to learn next
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:
- Partitioning in Redis
- Advanced commands
- Security in Redis
- Clusters in Redis
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!
Top comments (2)
This is great, I've been meaning to learn to use Redis for a while!
It's important to note that redis does not have password-based authentication enabled by default - its design philosophy is that it should never be connected to an untrusted network.
If you are using redis in a production environment, or if your redis server is on the public internet, remember to set a password and to put strict firewall rules in place such that only hosts that need to be able to connect to it are able to.
An unsecured redis can result in data leakage, and older versions can be abused to achieve remote code execution by abusing its replication features.
Clear and concise. Thanks for sharing!