How to Find Size of a Redis Key Value

Before we find out size of a Redis key & its value, let me clarify few things. In Redis, we can store data in two places.

  • We can use Redis as a pure caching layer & store key value pairs only in memory (RAM).
  • We can also store in-memory key value pairs in disk (e.g. SSD) to get data persistence & use Redis as a durable persistent data store.

Redis stores data differently in memory & disk. While storing in RAM, there will be additional overhead for in-memory data structures that Redis use for fast data access. On the other hand, while storing data in disk as a backup, Redis can compress the value.

Now let’s see how we can find a single Redis key value size in memory & also in disk.

Find Redis Key Value Size in Memory:

We can use “MEMORY USAGE” command in redis-cli to get the number of bytes a Redis key & its value require to be stored in RAM. The value returned will include any additional overhead for in-memory data structures.

127.0.0.1:6379> set testKey ""
OK
127.0.0.1:6379> memory usage testKey
(integer) 64

I stored a Redis key with empty value. As we can see above, “testKey” is taking 64 bytes which is more than what we expected for a key with empty value. This is because of additional overhead. If we increase the value size, we will see somewhat linear increase in number of bytes from now on.

127.0.0.1:6379> set testKey "abcdefghijklmnop"
OK
127.0.0.1:6379> memory usage testKey
(integer) 80

I added 16 characters in Redis value. Now total bytes consumed is (64 + 16) = 80 bytes.

Find Redis Key Value Size in Disk:

“DEBUG” is an internal command which is meant for developing & testing Redis. We can leverage that to find the value size in bytes when it is serialized & stored in disk. The command to use in redis-cli is “debug object <key>”.

127.0.0.1:6379> set testKey ""
OK
127.0.0.1:6379> debug object testKey
Value at:0x7f6a362632d0 refcount:1 encoding:embstr serializedlength:1 lru:14717760 lru_seconds_idle:50
127.0.0.1:6379> set testKey "abcdefghijklmnop"
OK
127.0.0.1:6379> debug object testKey
Value at:0x7f6a3621d528 refcount:1 encoding:embstr serializedlength:17 lru:14717820 lru_seconds_idle:4

As you can see above, when I stored empty value, the serialized length is 1 byte. I added 16 characters to the value. Serialized length became 17 bytes. By the way, “DEBUG OBJECT” command returns only the value size. It doesn’t include the key size.

So we can observe that same key value takes less space when stored in disk than in RAM. Anyways, now we know how to check Redis key value size in memory & disk.

Leave a Comment