47

When using the Redis expire commands like SETEX and TTL, there are scenarios in which there is no need for the key to hold a value at all, because the time to live acts as such.

However, Redis requires any key to have a value.

What would be the most reasonable value to use - if you don't ever want to read it?

Pang
  • 9,564
  • 146
  • 81
  • 122
RienNeVaPlu͢s
  • 7,442
  • 6
  • 43
  • 77

4 Answers4

61

Who said that you should actually store anything in redis key?

Empty string "" is a perfectly valid value for a redis key, and it's a shortest possible one:

> SET foo ""
OK
> GET foo
""
> BITCOUNT foo
(integer) 0
Leonid Beschastny
  • 50,364
  • 10
  • 118
  • 122
  • When using the StackExchange Redis client this can be detected by seeing that a RedisValue.IsNull is false but IsNullOrEmpty is true (what an api!). – Svend Jul 09 '18 at 09:51
  • this should be more clear that it is the value for a key 'foo' and not setting key to "" – botbot Jul 28 '19 at 10:15
  • 3
    When examined with `MEMORY USAGE [key]`, a value of `0` has a smaller footprint than an empty string. [See the answer below.](https://stackoverflow.com/a/59292672) – Daniel Mar 12 '21 at 09:02
19

I would avoid using "". How about simple 0 ?

127.0.0.1:6379> set akey 0
OK
127.0.0.1:6379> memory usage akey
(integer) 48
127.0.0.1:6379> set akey ""
OK
127.0.0.1:6379> memory usage akey
(integer) 50
127.0.0.1:6379>
null
  • 423
  • 5
  • 7
  • I think this is probably a better answer, in terms of real memory consumption. – Nathan Lutterman May 22 '20 at 03:14
  • 2
    A `0` has a greater likelihood of being a _useful_ value, whereas `""` already essentially means empty or nothing. `""` is better when dealing with integer values is a possibility (or becomes a possibility in the future). – AlexPi Sep 30 '22 at 19:20
9

I would store one byte of data that could also be broadly interpreted as "truthy", such as the ASCII character 1.

platforms
  • 2,666
  • 1
  • 18
  • 23
0

Do you serialize everything coming to and from redis, yourself? If so, you may consider using a sentinel value (like a NONE constant, etc.) which is set to something like 'None'.

Greg M. Krsak
  • 2,102
  • 1
  • 18
  • 28