Redis: Key Management

Redis is a key-based data structure storage system. This a key-value storage system, where we don’t have any table or rows or columns like a relational database.

The whole modeling/storing/retrieving of data depends on the key. So naming the key becomes very important.

Here is how to effectively name keys in a Redis database-

Redis Key Naming Convention

Empty string is a valid key name in Redis.

Key names are binary safe, so we can use binary sequences in the Redis key name.

Maximum allowed size of a key in Redis is 512MB.

Maximum number of keys that Redis can handle is 2^32.

Here are the things to consider while naming a Redis key-

  • Redis keys are strings. Any valid string is fine, including empty string and binary sequences are valid keys.
  • Do not use a very long key. A very long key name will make it expensive while managing data and comparing keys.
  • Do not name it too short. Make sure the key is readable and expressive. For example, for storing the user name, instead of naming it like u101nm, use user:101:name. Or for product discount use product:200:discount, instead of p200d.
  • As a standard, use the format object_type:object_id(i.e. user:200, customer:1001) for storing an object. Or, for storing a property of an object object_type:object_id:object_property_name (i.e. product:1001:sku, product:2001:price, user:200:name)

The following commands are the most used and useful Redis commands for managing key and/or value.
Here we have discussed commands – KEYS, GET, SET, DEL, EXISTS, TYPE, EXPIRE, TTL, PERSIST.

Redis Command: KEYSretrieve keys


KEYS <pattern>


Get the list of all keys in the database that matches the provided pattern(<pattern>)

Use with care in a production database. As, getting all the keys in a database with a huge dataset is an expensive task, and can harm the performance of the database in production.

Pattern Details:

The <pattern> in the command follows the Glob-style patterns. For example-

*Matches anything, as the asterisk means any character any number of times.
big*Any string that starts with “big” and then has any characters.
i.e. bigb, bigbox, bigboxcode
b[a-z]gAny string that starts with “b”, then has 1 character between a to z, and then has “g” at the end.
i.e. big, bag, bcg, bmg
b[ai]gAny string that starts with “b”, then has any of “a” or “i” once, and then has “g” at the end.
i.e. bag, big (only these 2 are possible in this case)
b[a-z]*gKey name that starts with “b”, then has character between “a” to “z” any number of times, and then ends with “g”.
i.e. bag, baaaaaag, babcdg, bworeinoweirnonfoiwejriidjfljasldkfjasldg
b[^ai]gKey name that starts with “b”, then has any character other than “a” and “i”, then has “g” at the end.
i.e. bbg, bng, byg, bcg
b?gKey name that starts with “b”, ends with “g” and has any 1 character in the middle.
i.e. bag, bbg, bcg, bdg
c??eString starts with “c”, and ends with “e”. And has 2 characters(any character) in between “c” and “e”.
i.e. cabe, code, cone, cute, cure
c[a-z]?deString that starts with “c”, ends with “de”. And has any character between “a” to “z” once.
i.e. cade, code, cnge

These patterns follow the Glob style.

Then patterns are case sensitive.

Use a backslash(\) to escape any special character.


Check the example below-> keys *
1) "a"
2) "site:domain"
3) "site:topic"
4) "somekey"
5) "site:name"> keys site:*
1) "site:domain"
2) "site:topic"
3) "site:name"> keys SIte*
(empty array)> keys s???k*
1) "somekey"

Redis Command: GETretrieve a value


GET <key>


Get value of the <key>.

Return Type:

Return valueCase for the return value
Value saved for the keyWhen the key exits, and key has a valid value saved for it.
nilWhen the key does not exist.
errorWhen the saved value for the key is not a valid string.

Examples:> get a
"dd"> get wrongkey
(nil)> get site:domain
""> get site:wrong

Redis Command: SETset key/value


Simple signature-

SET <key> <value>

Complete signature-

SET <key> <value> [NX | XX] [GET] [EX <seconds> | PX <milliseconds> | EXAT <unix-time-seconds> | PXAT <unix-time-milliseconds> | KEEPTTL]


NXOnly perform the set operation if the key doesn’t already exist.
XXOnly perform the set operation if the key already exists.
EX <seconds>Expire time in seconds.
PX <milliseconds>Expire time in miliseconds.
EXAT <unix-time-seconds>Unix timestamp in seconds when the key/value pair will be expired.
PXAT <unix-time-miliseconds>Unix timestamp in milliseconds when the key/value pair will be expired.
KEEPTTLKeep the set TTL.
GETReturn the value for the key, that was already existing(old value).
nil is returned if the key did not exist.


Set value for a key.

  • If the key does not already exist, then it will be created and the value will be set.
  • If the key already exists then the value is replaced with the newly provided value.
  • If the key is already existing and has a TTL, then replace the TTL upon successful command execution.

Return Type:

Return valueCase for the return value
OKSuccessfully execution.
nilIf the command failed for some reason.
Possible reason- for NX or XX options.


# set a key/value> set firstkey "some value"

# check the key/value> get firstkey
"some value"

# set key/value with expire time of 10 seconds> set secondkey "another value" ex 10

# check within 10 seconds of setting, and the we will get the value> get secondkey
"another value"

# check after 10 seconds of setting the value, and the value does not exist> get secondkey

# Try setting somekey and check if it not exists already> set somekey newval nx
(nil)> set differentkey newval nx

# Set key/value only if that exists> set somekey newval xx

Redis Command: DELdestroy key/value


DEL <key> [<anotehr_key> … ]


Delete specific key or keys.

Return Type:

The number of keys that are deleted.


# Set some vlaues> set firstkey "value 123"
OK> set secondkey "value 345"
OK> set thirdkey "9876"

# Delete firstkey. The command executes successfully> del firstkey
(integer) 1

# Try to get firstkey, that returns error as the key no longer exists.> get firstkey

# Delete secondkey adn thirdkey. Both are deleted successfully.> del secondkey thirdkey
(integer) 2

# Now try to delete secondkey again. It returns 0, s the secondkey does not exist anymore> del secondkey
(integer) 0

A similar command is “UNLINK <key> [<another_key> … ]“. The Unlink command works like DEL, the difference is in the process.
Del deletes keys one by one, synchronously, and makes it a blocking command. That makes the memory reclaiming of the DEL command slower.
On the other hand, the UNLINK command is non-blocking, as the processing is done synchronously in different threads. In UNLINK the command the actual removal operation happens asynchronously, so the memory reclaiming is much faster than DEL.

Redis Command: EXISTScheck existence


EXISTS <key> [<another_key> … ]


Check if the key exists in keyspace or not.

Return Value:

Number(integer) of the keys that exist in the database.

If the same key name is passed twice and the key exists in the database, then 2 is returned. So the command does not consider the unique number of keys, which are passed.

Examples:> keys *
1) "a"
2) "site:domain"
3) "b"
4) "site:topic"
5) "somekey"
6) "site:name"> exists a
(integer) 1> exists a b somekey
(integer) 3> exists a a b somekey b
(integer) 5> exists wrongkey
(integer) 0> exists a wrongkey
(integer) 1

Redis Command: TYPEcheck value type


TYPE <key>


Check the type of value saved in the key.

Return Value:

Returned ValueDescription
String representation of the type of valueThe type name(string) of the value.
i.e. string, list, set, hash, stream.
noneIf the key does not exist.

Examples:> type somekey
string> type hash1
hash> type list1
list> type wrongkey

Redis Command: RENAMErename key


RENAME <key> <new_key_name>


Rename an existing key.

If the <new_key_name> already exists, then this command overrites the <new_key_name>. In the background, this RENAME command deletes the existing key <new_key_name> first and then creates a new entry with the <new_key_name>. So, if the value is large, then deleting and recreating the entry can cause performance issues.

Return Value:

Returned ValueDescription
OKIf rename of the key is successful.
errorIf the key does not exist.

Examples:> set firstkey 99

# Rename key> rename firstkey changedkey

# Try to rename the same key. We get error as the "firstkey" does not exist anymore> rename firstkey changedkey
(error) ERR no such key

# Let's check another example> set firstkey 100
OK> set secondkey 200

# Let's rename the firstkey to second key> rename firstkey secondkey

# After rename the firstkey deos not exist any more> get firstkey

# After rename the secondkey has the value(100) of first key> get secondkey

A similar command is “RENAMEX <key> <new_key_name>“. In RENAMEX the key name is changed only if the key <new_key_name> does not exist. If the <new_key_name> already exists then the command returns Zero(0).

Redis Command: EXPIREset expiry time


Simple use of the command-

EXPIRE <key> <seconds>

Full signature of the command-

EXPIRE <key> <seconds> [NX | XX | GT | LT]


Set expiration time(timeout) for a key.


NXOnly when there is no expiry time set already for the key.
XXOnly when the expiry time is already set for the key.
GTOnly when the new expiry time is greater that the existing one.
LTOnly when the new expiry time is less than the existing one.

Return Value:

An integer value is returned-

Return ValueDescription
1If the command is successful (the expiry time is set properly)
0If the command is not successful, for reasons like- key does not exist or for the “GT” or “LT” option the time-limit does not satisfy.

Examples:> set firstkey "first value"
OK> expire firstkey 10
(integer) 1> ttl firstkey
(integer) 4> set firstkey "first value"
OK> expire firstkey 20
(integer) 1> expire firstkey 2 XX
(integer) 1> expire firstkey 200 LT
(integer) 1> ttl firstkey
(integer) 194

A similar command is “PEXPIRE<key> <milliseconds> [NX|XX|GT|LT]“. In the PEXPIRE command, we set the expiry time in milliseconds.

Another similar command is “EXPIREAT<key> <unix_time_in_seconds> [NX|XX|GT|LT]“. In the EXPIREAT command, we set an absolute UNIX timestamp (seconds since Jan 1, 1970) for when the key should expire.

Another similar command is “PEXPIREAT<key> <unix_time_in_milliseconds> [NX|XX|GT|LT]“. In the PEXPIREAT command, we set an absolute UNIX timestamp (milliseconds since Jan 1, 1970) for when the key should expire.

Redis Command: TTLget remaining time


TTL <key>


Get the remaining time for the key expiry timeout, in seconds.

Return Value:

An integer value is returned-

Return ValueDescription
Some positive intergerSome positive integer
-1If the key exists but does not have any expiery time associated.
-2If the key does not exist.


#set value with expiery time with 20 seconds> set firstkey "somevalue" ex 20

# check TTL> ttl firstkey
(integer) 15> ttl firstkey
(integer) 10> ttl firstkey
(integer) 8> ttl firstkey
(integer) 2> ttl firstkey
(integer) 1

# TTL response when key is removed for timeout> ttl firstkey
(integer) -2

# set the value without any TTL> set firstkey "some value"

# response when no TTL is associated> ttl firstkey
(integer) -1

A similar command is “PTTL <key>“. The PTTL command returns the remaining time in milliseconds.

Redis Command: PERSISTremove timeout




Remove the timeout from the key. This command makes the key to persist with no more timeout.

Return Value:

An integer value is returned-

Return ValueDescription
1If the command is successful, and timeout is removed from the key.
0If there is an error while command execution- the key does not exist, or the key does not have any timeout associated.


# Set value with 200 seconds timeout> set firstkey "some value" ex 200

# Check the ttl> ttl firstkey
(integer) 196

# Persist to remove the timeout> persist firstkey
(integer) 1

# Check the ttl again. -1 is returned to indicate that, it does not have any expiry associated> ttl firstkey
(integer) -1> set firstkey 99

# Then if we try to persist again then return value is 0 as not expiery time is associated with it> persist firstkey
(integer) 0

# Let's try to persist a non existing key, 0 is returned> persist wrongkey
(integer) 0

Leave a Comment

The reCAPTCHA verification period has expired. Please reload the page.