Storing integers in Redis

I’ve been looking into Redis. I wondered about storing integers as keys and values rather than plain old strings. After asking on Stackoverflow, I did my own experiments.

It looks like it is possible to use any byte string as a key.

For my application’s case it actually didn’t make that much difference storing the strings or the integers. I imagine that the structure in Redis undergoes some kind of alignment anyway, so there may be some pre-wasted bytes anyway. The value is hashed in any case.

I used Python for my testing, so I was able to create the values using the struct.pack function. long longs weigh in at 8 bytes, which is quite large if there are a lot of them. Given the distribution of integer values, I discovered that it could actually be advantageous to store the strings, especially when coded in hex.

As redis strings are ‘Pascal-style’:

struct sdshdr {
long len;
long free;
char buf[];
};

and given that we can store anything in there, I did a bit of extra Python to code the type into the shortest possible type: