Redis Common Commands

Introduction

Redis is an in-memory data store commonly used for caching, session management, counters, queues, and other high-performance applications.

This guide covers commonly used Redis commands for connecting to Redis, managing keys and data types, checking server statistics, changing runtime configuration, working with databases and replication, debugging latency, creating backups, managing client connections, and monitoring Redis traffic.

Prerequisites

Before using the commands in this guide, make sure:

  • Redis is installed and running on the server.
  • You have access to the Redis server or redis-cli.
  • You know the Redis host and port if connecting remotely.
  • You have appropriate permissions to execute administrative commands.
  • Be careful when running commands such as KEYS, FLUSHDB, FLUSHALL, and MONITOR on production systems.

Implementation

Step 1: Connect to Redis

You can connect to Redis using telnet or the Redis CLI client.

Using Telnet:

telnet localhost 6397

Using Redis CLI:

redis-cli

The redis-cli client provides command-line history and a convenient interface for executing Redis commands.

Note: Redis commonly uses port 6379 by default. The original article uses 6397, so verify the port configured on your Redis server before connecting.

Step 2: Monitor Live Redis Commands

The MONITOR command displays commands being executed on the Redis server in real time:

monitor

Use this command carefully on production systems because it can generate significant output and overhead.

Press Ctrl-C to stop monitoring.

Step 3: Check Slow Queries

Redis provides the SLOWLOG feature for identifying slow commands.

To display the top 25 slow queries:

slowlog get 25

Check the number of entries in the slow log:

slowlog len

Reset the slow log:

slowlog reset

Step 4: Search for Keys

You can use the KEYS command to find keys matching a pattern:

keys pattern
keys pattern*
keys *pattern*
keys *pattern

For example:

keys user*

Warning: Avoid using KEYS on large production databases because it performs a full scan of the keyspace and can block Redis while processing. For production workloads, SCAN is generally safer for iterating through keys.

Step 5: Use Generic Key Commands

Some commonly used commands for managing Redis keys are:

del <key>
dump <key>
exists <key>
expire <key> <seconds>

For example:

exists testkey
expire testkey 3600
del testkey

Step 6: Work with String Values

Use the following commands to store and retrieve simple string values:

get <key>
set <key> <value>
setnx <key> <value>

SETNX sets a value only when the key does not already exist.

Batch Commands

Multiple keys can be handled using:

mget <key> <key> ...
mset <key> <value> <key> <value> ...

Counter Commands

Redis can also be used for counters:

incr <key>
decr <key>

Step 7: Work with Lists

Redis lists support operations such as adding, retrieving, removing, and trimming elements.

lrange <key> <start> <stop>
lrange mylist 0 -1
lindex mylist 5
llen mylist

lpush mylist "value"
lpush mylist 5
rpush mylist "value"

lpushx mylist 6
rpushx mylist 0

lpop mylist
rpop mylist

lrem mylist 1 "value"
lset mylist 2 6
ltrim <key> <start> <stop>

For example:

lrange mylist 0 -1

returns all elements from mylist.

Step 8: Work with Hashes

Redis hashes store field-value pairs.

Check whether a field exists:

hexists myhash field1

Retrieve, delete, and set hash fields:

hget myhash field1
hdel myhash field2
hset myhash field1 "value"
hsetnx myhash field1 "value"

Retrieve all fields and values:

hgetall myhash

Retrieve all fields:

hkeys myhash

Check the number of fields:

hlen myhash

Batch Hash Commands

hmget <key> <key> ...
hmset <key> <value> <key> <value> ...

Hash Counter Commands

hincrby myhash field1 1
hincrby myhash field1 5
hincrby myhash field1 -1

hincrbrfloat myhash field2 1.123445

Note: Some commands in the original article reflect older Redis versions. Check the command syntax supported by your installed Redis version before using them.

Step 9: Run Redis CLI Scripts

You can pipe Redis output through standard Linux commands.

For example, to check the number of connected clients:

redis-cli INFO | grep connected

Example output:

connected_clients:2
connected_slaves:0

Server Statistics

Step 10: Check Redis Server Information

The INFO command provides statistics and configuration information about the Redis server.

redis-cli INFO

Example output:

redis_version:2.2.12
redis_git_sha1:00000000
redis_git_dirty:0
arch_bits:64
multiplexing_api:epoll
process_id:8353
uptime_in_seconds:2592232
uptime_in_days:30
lru_clock:809325
used_cpu_sys:199.20
used_cpu_user:309.26
used_cpu_sys_children:12.04
used_cpu_user_children:1.47
connected_clients:2
connected_slaves:0
client_longest_output_list:0
client_biggest_input_buf:0
blocked_clients:0
used_memory:6596112
used_memory_human:6.29M
used_memory_rss:17571840
mem_fragmentation_ratio:2.66
use_tcmalloc:0
loading:0
aof_enabled:0
changes_since_last_save:0
bgsave_in_progress:0
last_save_time:1371241671
bgrewriteaof_in_progress:0
total_connections_received:118
total_commands_processed:1091
expired_keys:441
evicted_keys:0
keyspace_hits:6
keyspace_misses:1070
hash_max_zipmap_entries:512
hash_max_zipmap_value:64
pubsub_channels:0
pubsub_patterns:0
vm_enabled:0
role:master
db0:keys=91,expires=88

Important values include:

  • connected_clients – Number of connected clients.
  • used_memory_human – Human-readable Redis memory usage.
  • role – Indicates whether the instance is acting as a master or replica in the replication setup.
  • keyspace_hits and keyspace_misses – Useful for understanding cache hit and miss activity.

Changing Runtime Configuration

Step 11: View Redis Configuration

Use CONFIG GET * to display active configuration parameters:

CONFIG GET *

Example output:

1) "dir"
2) "/var/lib/redis"
3) "dbfilename"
4) "dump.rdb"
5) "requirepass"
6) (nil)
7) "masterauth"
8) (nil)
9) "maxmemory"
10) "0"
11) "maxmemory-policy"
12) "volatile-lru"
13) "maxmemory-samples"
14) "3"
15) "timeout"
16) "300"
17) "appendonly"
18) "no"
19) "no-appendfsync-on-rewrite"
20) "no"
21) "appendfsync"
22) "everysec"
23) "save"
24) "900 1 300 10 60 10000"
25) "slave-serve-stale-data"
26) "yes"
27) "hash-max-zipmap-entries"
28) "512"
29) "hash-max-zipmap-value"
30) "64"
31) "list-max-ziplist-entries"
32) "512"
33) "list-max-ziplist-value"
34) "64"
35) "set-max-intset-entries"
36) "512"
37) "slowlog-log-slower-than"
38) "10000"
39) "slowlog-max-len"
40) "64"

The output contains configuration keys and values alternately.

Step 12: Change Runtime Configuration

You can use CONFIG SET to change a supported configuration parameter at runtime.

For example:

CONFIG SET timeout 900

Runtime configuration changes take effect immediately. If the change needs to persist after a Redis restart, make sure the corresponding Redis configuration is updated according to the Redis version and configuration method being used.

Managing Redis Databases

Step 13: Select a Redis Database

Redis supports multiple logical databases. Database 0 is selected by default.

To switch to database 1:

SELECT 1

Example:

redis 127.0.0.1:6379> SELECT 1
OK
redis 127.0.0.1:6379[1]>

The [1] in the prompt indicates that database 1 is currently selected.

To check database information:

redis-cli INFO | grep ^db

Example:

db0:keys=91,expires=88
db1:keys=1,expires=0

Step 14: Delete Database Data

To remove all keys from the currently selected database:

FLUSHDB

To remove all keys from all Redis databases:

FLUSHALL

Warning: These commands permanently remove Redis data. Use them with extreme care, especially on production servers.

Redis Replication

Step 15: Check Replication Status

Use the INFO command to determine whether a Redis instance is a master or replica:

INFO

Look for the role value:

role:master

or:

role:slave

Modern Redis versions use the term replica instead of slave in configuration and documentation.

For older Redis versions, replication information may look like:

slave0:ip=127.0.0.1,port=6380,state=online,offset=281,lag=0

Step 16: Configure Replication

In older Redis versions, the following command can be used to configure an instance as a replica:

SLAVEOF <IP> <port>

For example:

SLAVEOF 192.168.1.10 6379

To stop the replication relationship:

SLAVEOF NO ONE

Note: SLAVEOF is retained for compatibility with older Redis versions. Modern Redis configurations commonly use REPLICAOF.

For a complete master-replica setup, refer to the related Redis replication guide below.

Debugging Redis Latency

Step 17: Measure Intrinsic System Latency

Redis provides a command for measuring intrinsic system latency:

redis-cli --intrinsic-latency 100

You can also measure latency from a Redis client:

redis-cli --latency -h <host> -p <port>

If you experience high latency, investigate system-level factors such as CPU, memory, disk I/O, network performance, and kernel configuration.

The original guide also recommends checking Transparent Huge Pages (THP):

echo never > /sys/kernel/mm/transparent_hugepage/enabled

Note: THP configuration is system-specific. Test any kernel-level change before applying it to a production server.

Redis Database Backup

Step 18: Create an RDB Backup

Redis can create an RDB snapshot in the background using:

BGSAVE

Redis creates the snapshot in the background without blocking the main Redis process for the duration of the dump.

To check when the last successful save occurred:

LASTSAVE

For a synchronous save, use:

SAVE

Important: SAVE can block Redis while the snapshot is being created, so use it carefully on production systems. For routine backups, BGSAVE or an appropriate Redis backup strategy is generally preferable.

Managing Redis Connections

Step 19: List Active Connections

Use the following command to list connected clients:

CLIENT LIST

Step 20: Terminate a Client Connection

The original command format is:

CLIENT KILL <IP>:<port>

Use client-management commands carefully because terminating an active application connection may affect the application using Redis.

Monitoring Redis Traffic

Step 21: Monitor Commands in Real Time

The MONITOR command displays incoming Redis commands in real time:

MONITOR

Example:

redis 127.0.0.1:6379> MONITOR
OK
1371241093.375324 "monitor"
1371241109.735725 "keys" "*"
1371241152.344504 "set" "testkey" "1"
1371241165.169184 "get" "testkey"

This can be useful for troubleshooting application behavior.

Warning: MONITOR can generate a large amount of output and may impact Redis performance. Avoid running it continuously on busy production instances.

Step 22: Monitor Slow Commands

You can combine SLOWLOG RESET and SLOWLOG GET to inspect slow commands during a specific period:

SLOWLOG RESET

Wait for the required monitoring period and then run:

SLOWLOG GET 25

This returns the 25 slowest commands recorded during that period.

Conclusion

Redis provides a wide range of commands for managing keys, strings, lists, hashes, databases, replication, backups, connections, configuration, and performance.

Commands such as GET, SET, DEL, INFO, SLOWLOG, CLIENT LIST, BGSAVE, and MONITOR are useful for everyday Redis administration and troubleshooting.

When working with production Redis servers, take extra care with commands such as KEYS, FLUSHDB, FLUSHALL, and MONITOR, as they can have a significant impact on performance or data.

FAQs

1. What is the default Redis port?

The standard Redis port is 6379. Always verify the port configured on your Redis server before connecting.

2. How can I check Redis server information?

Run:

redis-cli INFO

This provides information about memory usage, connected clients, commands processed, replication, databases, and other server statistics.

3. What is the difference between FLUSHDB and FLUSHALL?

FLUSHDB removes keys from the currently selected database, while FLUSHALL removes keys from all Redis databases.

4. How can I find Redis keys?

You can use:

KEYS pattern

However, avoid KEYS on large production databases. SCAN is generally more appropriate for safely iterating through a large keyspace.

5. How can I check Redis replication status?

Run:

INFO

Then check the role field to determine whether the Redis instance is a primary or replica.

  • Redis Master and Slave Setup – Learn how to configure Redis replication between a master and slave/replica server and understand the basic Redis replication setup.
    Read the article

admin

Writes about Web & Architecture at Pheonix Solutions.

Leave a Reply

Scroll to Top