Redis Partitioning
Partitioning is the process of splitting data across multiple Redis instances, so each instance only holds a subset of the keys.
Advantages of Partitioning
- By leveraging the combined memory of multiple computers, we can build larger databases.
- Through multiple cores and multiple computers, we can scale computing power; through multiple computers and network adapters, we can scale network bandwidth.
Disadvantages of Partitioning
Some of Redis's features do not perform well with partitioning:
- Operations involving multiple keys are generally not supported. For example, when two sets are mapped to different Redis instances, you cannot perform an intersection operation on those two sets.
- Redis transactions involving multiple keys cannot be used.
- When using partitioning, data processing is more complex; for example, you need to handle multiple rdb/aof files and back up persistence files from multiple instances and hosts.
- Adding or removing capacity is also more complex. Most Redis clusters support transparent data rebalancing when adding or removing nodes at runtime, but other systems such as client-side partitioning and proxies do not support this feature. However, a technique called presharding can help with this.
Partition Types
There are two types of partitioning in Redis. Suppose there are 4 Redis instances R0, R1, R2, R3, and multiple keys representing users such as user:1, user:2. For a given key, there are various ways to choose which instance it is stored in. That is, different systems map a key to a particular Redis service.
Range Partitioning
The simplest partitioning method is range partitioning, which maps a certain range of objects to a specific Redis instance.
For example, users with IDs from 0 to 10000 are saved to instance R0, users with IDs from 10001 to 20000 are saved to R1, and so on.
This approach is feasible and used in practice, but its drawback is that it requires a mapping table from ranges to instances. This table must be managed, along with mapping tables for various objects, which is usually not a good approach for Redis.
Hash Partitioning
Another partitioning method is hash partitioning. It applies to any key and does not need to be in the object_name:
- Use a hash function to convert the key into a number, such as the crc32 hash function. Running crc32(foobar) on the key foobar outputs an integer similar to 93024922.
- Take the modulus of this integer to convert it to a number between 0 and 3, which maps the integer to one of the 4 Redis instances. 93024922 % 4 = 2, meaning the key foobar should be stored in instance R2. Note: the modulo operation gives the remainder of division, usually implemented with the % operator in many programming languages.