Redis Server Tutorial

In this Redis tutorial we learn how to interact with and manage the server and its clients with special server commands.

We cover how to save the datasets to the disk and restore or import that saved data, how to find more information on clients and how to pause or close those client connections among others.

What are Redis Server Commands

Redis allows us to interact with and manage the server and its clients with special server commands.

The table below shows all the server commands available in Redis.

CommandDescription
BGREWRITEAOFUsed to asynchronously rewrite the append-only file.
BGSAVEUsed to asynchronously save the dataset to the disk.
CLIENT KILL [ip:port] [ID client-id]Used to kill the connection of a client.
CLIENT LISTUsed to get the list of client connections to the server.
CLIENT GETNAMEUsed to get the name of the current connection.
CLIENT PAUSE timeoutUsed to stop processing commands from the clients for a specified time.
CLIENT SETNAME connection-nameUsed to set the current connection name.
CLUSTER SLOTSUsed to get an array of Cluster slot to node mappings.
COMMANDUsed to get an array of Redis command details.
COMMAND COUNTUsed to get total number of Redis commands.
COMMAND GETKEYSUsed to extract the keys given a full Redis command.
COMMAND INFO command-nameUsed to get an array of specific Redis command details.
CONFIG GET parameterUsed to get the value of a configuration parameter.
CONFIG REWRITEUsed to rewrite the configuration file with the in-memory configuration.
CONFIG SET parameter valueUsed to get a configuration parameter to the given value.
CONFIG RESETSTATUsed to reset the stats returned by INFO.
DBSIZEUsed to return the number of keys in the selected database.
DEBUG OBJECT keyUsed to get debugging information about a key.
DEBUG SEGFAULTUsed to make the server crash.
FLUSHALLUsed to remove all the keys from all databases.
FLUSHDBUsed to remove all the keys from the current database.
INFO [section]Used to get information and statistics about the server.
LASTSAVEUsed to retrieve the UNIX time stamp of the last successful save to the disk.
MONITORUsed to listen for all the requests received by the server in real time.
ROLEUsed to return the role of the instance in the context of replication.
SAVEUsed to synchronously saves the dataset to the disk.
SHUTDOWN [NOSAVE] [SAVE]Used to synchronously saves the dataset to the disk and then shuts down the server .
SLAVEOF host portUsed to make the server a slave of another instance, or promotes it as a master .
SLOWLOG subcommand [argument]Used to manage the Redis slow queries log.
SYNCUsed for replication.
TIMEUsed to return the current server time.

We take a deeper look at some of the commands below.

How to return all information about the Redis server

We can get a quick overview with statistics about the server by using the INFO command.

Example:
INFO
Output:
# Server
redis_version:6.0.5
redis_git_sha1:00000000
redis_git_dirty:0
redis_build_id:db63ea56716d515f
redis_mode:standalone
os:Linux 4.19.76-linuxkit x86_64
arch_bits:64
multiplexing_api:epoll
atomicvar_api:atomic-builtin
gcc_version:8.3.0
process_id:1
run_id:eb1029a95aa9c5c6989f4761aec26edaa6c583ec
tcp_port:6379
uptime_in_seconds:13788
uptime_in_days:0
hz:10
configured_hz:10
lru_clock:9881556
executable:/data/redis-server
config_file:

# Clients
connected_clients:2
client_recent_max_input_buffer:2
client_recent_max_output_buffer:0
blocked_clients:0
tracking_clients:0
clients_in_timeout_table:0

# Memory
used_memory:888152
used_memory_human:867.34K
used_memory_rss:7151616
used_memory_rss_human:6.82M
used_memory_peak:888152
used_memory_peak_human:867.34K
used_memory_peak_perc:100.17%
used_memory_overhead:836820
used_memory_startup:802848
used_memory_dataset:51332
used_memory_dataset_perc:60.18%
allocator_allocated:880904
allocator_active:1159168
allocator_resident:3522560
total_system_memory:2087813120
total_system_memory_human:1.94G
used_memory_lua:37888
used_memory_lua_human:37.00K
used_memory_scripts:0
used_memory_scripts_human:0B
number_of_cached_scripts:0
maxmemory:0
maxmemory_human:0B
maxmemory_policy:noeviction
allocator_frag_ratio:1.32
allocator_frag_bytes:278264
allocator_rss_ratio:3.04
allocator_rss_bytes:2363392
rss_overhead_ratio:2.03
rss_overhead_bytes:3629056
mem_fragmentation_ratio:8.46
mem_fragmentation_bytes:6305968
mem_not_counted_for_evict:0
mem_replication_backlog:0
mem_clients_slaves:0
mem_clients_normal:33972
mem_aof_buffer:0
mem_allocator:jemalloc-5.1.0
active_defrag_running:0
lazyfree_pending_objects:0

# Persistence
loading:0
rdb_changes_since_last_save:0
rdb_bgsave_in_progress:0
rdb_last_save_time:1603703288
rdb_last_bgsave_status:ok
rdb_last_bgsave_time_sec:-1
rdb_current_bgsave_time_sec:-1
rdb_last_cow_size:0
aof_enabled:0
aof_rewrite_in_progress:0
aof_rewrite_scheduled:0
aof_last_rewrite_time_sec:-1
aof_current_rewrite_time_sec:-1
aof_last_bgrewrite_status:ok
aof_last_write_status:ok
aof_last_cow_size:0
module_fork_in_progress:0
module_fork_last_cow_size:0

# Stats
total_connections_received:4
total_commands_processed:14
instantaneous_ops_per_sec:0
total_net_input_bytes:539
total_net_output_bytes:18979
instantaneous_input_kbps:0.00
instantaneous_output_kbps:0.00
rejected_connections:0
sync_full:0
sync_partial_ok:0
sync_partial_err:0
expired_keys:0
expired_stale_perc:0.00
expired_time_cap_reached_count:0
expire_cycle_cpu_milliseconds:149
evicted_keys:0
keyspace_hits:0
keyspace_misses:0
pubsub_channels:0
pubsub_patterns:0
latest_fork_usec:0
migrate_cached_sockets:0
slave_expires_tracked_keys:0
active_defrag_hits:0
active_defrag_misses:0
active_defrag_key_hits:0
active_defrag_key_misses:0
tracking_total_keys:0
tracking_total_items:0
tracking_total_prefixes:0
unexpected_error_replies:0

# Replication
role:master
connected_slaves:0
master_replid:11cae53d2996f3a75e8b4b727d25903b90ecb0aa
master_replid2:0000000000000000000000000000000000000000
master_repl_offset:0
second_repl_offset:-1
repl_backlog_active:0
repl_backlog_size:1048576
repl_backlog_first_byte_offset:0
repl_backlog_histlen:0

# CPU
used_cpu_sys:6.979082
used_cpu_user:6.335137
used_cpu_sys_children:0.003158
used_cpu_user_children:0.002699

# Modules

# Cluster
cluster_enabled:0

# Keyspace

We can filter the information by using one of these sections as an argument.

Example:
INFO clients
Output:
# Clients
connected_clients:2
client_recent_max_input_buffer:2
client_recent_max_output_buffer:0
blocked_clients:0
tracking_clients:0
clients_in_timeout_table:0

The table below shows the available sections to filter by.

serverclientsmemorypersistencestats
replicationcpumodulesclusterkeyspace

How to save the dataset to the disk (synchronously & asynchronously)

As mentioned before, Redis is an in-memory storage. To save the data permanently, we would still need a database solution like MongoDB.

The BGSAVE command will save the dataset asynchronously in the background in the form of a RDB file.

Example:
RPUSH firstname John Jane Jack Jill

BGSAVE

In the example above we create a list called ‘firstname’ with four elements. Then we attempt to save it to the disk with the BGSAVE command.

Redis will immediately return a confirmation message that the process has started, then fork. The parent will continue to serve any clients while the child save the dataset on the disk.

Output:
Background saving started

A client can check if the file was saved with the LASTSAVE command.

Example:
LASTSAVE
Output:
(integer) 1603717970

We can also save the dataset synchronously with the SAVE command.

Example:
SAVE

Redis will return an OK status if the operation was successful.

How to restore or import saved data

To restore/import the Redis data saved in the previous section, we simply copy the saved file (dump.rdb) into the Redis directory and restart the server.

To get the directory, use the CONFIG command.

Example:
CONFIG get dir
Output:
1) "dir"
2) "/data"

We’re currently working in a docker image so our path may look different than yours.

On a typical Linux installation, it should look something like the following.

Output:
1) "dir"
2) "/user/USERNAME/redis-v*/src"

Where USERNAME is your installation username and v* is your Redis version number.

How to list all clients connected to the server

We can return information and statistics about all the clients connected to the Redis server by using the CLIENT LIST command.

Example:
CLIENT LIST

Redis will output the information in a human-readable format, each client on its own line.

Output:
id=4 addr=127.0.0.1:47126 fd=8 name= age=14579 idle=12023 flags=N db=0 sub=0 psub=0 multi=-1 qbuf=0 qbuf-free=0 obl=0 oll=0 omem=0 events=r cmd=ping user=default
id=7 addr=127.0.0.1:47132 fd=9 name= age=11008 idle=0 flags=N db=0 sub=0 psub=0 multi=-1 qbuf=26 qbuf-free=32742 obl=0 oll=0 omem=0 events=r cmd=client user=default

From the output above, we can see that two clients are connected with a bunch of extra info.

The table below offers a breakdown of each field.

FieldDescription
idUnique 64-bit client ID (introduced in Redis 2.8.12)
addrAddress/port of the client
fdFile descriptor corresponding to the socket
ageTotal duration of the connection in seconds
idleIdle time of the connection in seconds
flagsClient flags (see below)
dbCurrent database ID
subNumber of channel subscriptions
psubNumber of pattern matching subscriptions
multiNumber of commands in a MULTI/EXEC context
qbufQuery buffer length (0 means no query pending)
qbuf-freeFree space of the query buffer (0 means the buffer is full)
oblOutput buffer length
ollOutput list length (replies are queued in this list when the buffer is full)
omemOutput buffer memory usage
eventsFile descriptor events (see below)
cmdLast command played

How to close a client's connection to the server

We can forcibly close one or more client’s connection the server by using the CLIENT KILL command.

This command has several options depending on which connections we want to close.

FieldDescriptionExample
CLIENT KILL ADDR ip:portKill the connection of the client with the specified ip:portCLIENT KILL ADDR 127.0.0.1:47126
CLIENT KILL ID client_idKill the connection of the client with the specified IDCLIENT KILL ID 4
CLIENT KILL TYPE typeKill all connections of type normal (MONITOR included), slave or pubsubCLIENT KILL TYPE normal
CLIENT KILL SKIPME yes/noSkip the client calling the command (Default is yes)CLIENT KILL SKIPME yes

How to pause command processing from all clients

We can suspend all Redis clients for a specified amount of time with the CLIENT PAUSE command.

The command accepts the time (in milliseconds) to pause the clients as the argument.

When the CLIENT PAUSE command is executed, it will stop processing all pending commands from normal and pubsub clients. Commands from slaves however, will continue normally.

Syntax:
CLIENT PAUSE timeout_in_milliseconds
Example:
CLIENT PAUSE 5000

The example above will pause all pending commands from clients for 5 seconds.

When the specified time has elapsed, the clients are unblocked. This will trigger processing of all the commands in the query buffer from all the clients during the pause.

Output:
OK

Redis will immediately return an OK status to the caller, so the PAUSE execution isn’t paused itself.

How to get and set the name of a client

Redis allows us to set the name of the current client with the CLIENT SETNAME command so that it’s possible to identify a client with the CLIENT LIST command.

Syntax:
CLIENT SETNAME connection_name

Note that client names cannot contain spaces, newlines or special characters.

Example:
CLIENT SETNAME "MyConnection"

If the operation was successful, Redis will return an OK status.

We can also return the name of the current connection with the CLIENT GETNAME command.

Example:
CLIENT GETNAME
Output:
"MyConnection"

As mentioned before, we can now identify a client by its name when we run the CLIENT LIST command.

If we run the CLIENT LIST command now, we will see that one of the clients has the name ‘MyConnection’ associated with the name field.

Output:
id=4 addr=127.0.0.1:47126 fd=8 name= age=34543 idle=31987 flags=N db=0 sub=0 psub=0 multi=-1 qbuf=0 qbuf-free=0 obl=0 oll=0 omem=0 events=r cmd=ping user=default
id=7 addr=127.0.0.1:47132 fd=9 name=MyConnection age=30972 idle=0 flags=N db=0 sub=0 psub=0 multi=-1 qbuf=26 qbuf-free=32742 obl=0 oll=0 omem=0 events=r cmd=client user=default

Until a client sets its name explicitly, the name field will be empty.

How to get and set configuration parameters and write them to the conf file

Redis allows us to reconfigure the configuration file on the fly without stopping and restarting the service.

To set the value of a config parameter, we use the CONFIG SET command.

Syntax:
CONFIG SET parameter value

For example, we can change the password for a client with the requirepass parameter.

Example:
CONFIG SET requirepass "mypass"

Redis will return with an OK status if the operation was successful.

The list of configuration parameters, and their meaning and intended usage is available in the self-documented example redis.conf shipped into the Redis distribution.

The SAVE parameter works a little differently with the CONFIG SET command than it does in the redis.conf file.

Example:
save 900 1
save 300 10

On the first line, we tell Redis to save after 900 seconds if there is at least 1 change to the dataset.

On the second line we tell Redis to save after 300 seconds if there are at least 10 changes to the dataset.

If we use the CONFIG SET command, the same save configuration would look as follows.

Example:
CONFIG SET SAVE "900 1 300 10"

We can also return the value of a parameter with the CONFIG GET command. The first argument is the parameter we want to return.

Example:
CONFIG GET SAVE
Output:
1) "save"
2) "900 1 300 10"

The save parameter will display the data in this special way. Normally, just the value will be displayed.

Example:
CONFIG GET list-max-ziplist-size

In the example above we check what the maximum size of compression is for a list.

Output:
1) "list-max-ziplist-size"
2) "-2"

A value of -2 means the maximum size is 8 Kb.

Modifying the configuration file with the CONFIG commands has no effect on the redis.conf file itself. On the next restart of Redis, the old configuration will be used instead.

To apply the changes to the redis.conf file, we have to use the CONFIG REWRITE command.

Example:
CONFIG REWRITE