Bagee
Bagee

Reputation: 150

Do I need to hash a Redis key before using *SET?

I'm under the impression that one should hash (i.e. sha3) their Redis key before adding data to it. (It might have even been with regard to memcache.) I don't remember why I have this impression or where it came from but I can't find anything to validate (or refute) it. The reasoning was the hash would help with even distribution across a cluster.

When using Redis (in either/both clustered and non-clustered modes) is it best pracatice to hash the key before calling SET? e.g. set(sha3("username:123"), "owlman123")

Upvotes: 1

Views: 1598

Answers (2)

user1277186
user1277186

Reputation: 115

It might be a good idea if your keys are very long, as recommended in the official documentation:

A few other rules about keys:

  • Very long keys are not a good idea. For instance a key of 1024 bytes is a bad idea not only memory-wise, but also because the lookup of the key in the dataset may require several costly key-comparisons. Even when the task at hand is to match the existence of a large value, hashing it (for example with SHA1) is a better idea, especially from the perspective of memory and bandwidth.

source: https://redis.io/docs/data-types/tutorial/#keys

Upvotes: 1

Kevin Christopher Henry
Kevin Christopher Henry

Reputation: 49082

No, you shouldn't hash the key. Redis Cluster hashes the key itself for the purpose of choosing the node:

There are 16384 hash slots in Redis Cluster, and to compute what is the hash slot of a given key, we simply take the CRC16 of the key modulo 16384.

You can also use hash tags to control which keys share the same slot.

Upvotes: 1

Related Questions