{"record":{"id":"3f77a7571718fcca","repo":"redis/redis-py","slug":"command-all-keys-must-map-to-the-same-key-slot-3f77a7","errorCode":null,"errorMessage":"{command} - all keys must map to the same key slot","messagePattern":"(.+?) - all keys must map to the same key slot","errorType":"exception","errorClass":"RedisClusterException","httpStatus":null,"severity":"error","filePath":"redis/cluster.py","lineNumber":1494,"sourceCode":"                # FCALL can call a function with 0 keys, that means the function\n                #  can be run on any node so we can just return a random slot\n                if command.upper() in (\"FCALL\", \"FCALL_RO\"):\n                    return random.randrange(0, REDIS_CLUSTER_HASH_SLOTS)\n                raise RedisClusterException(\n                    \"No way to dispatch this command to Redis Cluster. \"\n                    \"Missing key.\\nYou can execute the command by specifying \"\n                    f\"target nodes.\\nCommand: {args}\"\n                )\n\n        # single key command\n        if len(keys) == 1:\n            return self.keyslot(keys[0])\n\n        # multi-key command; we need to make sure all keys are mapped to\n        # the same slot\n        slots = {self.keyslot(key) for key in keys}\n        if len(slots) != 1:\n            raise RedisClusterException(\n                f\"{command} - all keys must map to the same key slot\"\n            )\n\n        return slots.pop()\n\n    def get_encoder(self):\n        \"\"\"\n        Get the connections' encoder\n        \"\"\"\n        return self.encoder\n\n    def get_connection_kwargs(self):\n        \"\"\"\n        Get the connections' key-word arguments\n        \"\"\"\n        return self.nodes_manager.connection_kwargs\n\n    def _is_nodes_flag(self, target_nodes):","sourceCodeStart":1476,"sourceCodeEnd":1512,"githubUrl":"https://github.com/redis/redis-py/blob/6a6b581b48225afa0b76912d1028c6035baee932/redis/cluster.py#L1476-L1512","documentation":"Raised as a RedisClusterException by determine_slot() when a multi-key command has keys that hash to more than one distinct slot. Redis Cluster requires all keys in a single command (MSET, MGET, RENAME, SUNIONSTORE, etc.) to reside in the same hash slot so the command can be routed to a single node. The guard at cluster.py:1492-1496 computes the slot for each key and rejects cross-slot key sets.","triggerScenarios":"Calling client.mset({'k1': 'v1', 'k2': 'v2'}) where k1 and k2 hash to different slots, or client.rename('src', 'dst') where src and dst are in different slots, or any multi-key operation without hash-tag coordination.","commonSituations":"Developer assumes multi-key commands work like standalone Redis, or forgets to use hash tags to force keys into the same slot.","solutions":["Use Redis hash tags to force keys into the same slot, e.g. client.mset({'{user1}:name': 'a', '{user1}:email': 'b'}).","Split the multi-key operation into individual per-key commands so each is routed independently.","Use pipeline to batch per-key commands without cross-slot constraints."],"exampleFix":"// before\nclient.mset({'k1': 'v1', 'k2': 'v2'})\n\n// after (hash tag forces same slot)\nclient.mset({'{tag}:k1': 'v1', '{tag}:k2': 'v2'})","handlingStrategy":"validation","validationCode":"# Validate all keys share a slot before multi-key ops\nfrom redis.cluster import key_slot\ndef same_slot(keys):\n    slots = {key_slot(k.encode()) for k in keys}\n    return len(slots) == 1\n\nif not same_slot(['k1', 'k2']):\n    raise ValueError('Keys must share a hash slot; use hash tags like {tag}:k1')","typeGuard":"def keys_in_same_slot(keys: list) -> bool:\n    from redis.cluster import key_slot\n    return len({key_slot(k.encode() if isinstance(k, str) else k) for k in keys}) == 1","tryCatchPattern":"from redis.exceptions import RedisClusterException\ntry:\n    client.mset({'k1': 'v1', 'k2': 'v2'})\nexcept RedisClusterException as e:\n    if 'same key slot' in str(e):\n        # use hash tags or split into individual ops\n        for k, v in {'k1': 'v1', 'k2': 'v2'}.items():\n            client.set(k, v)","preventionTips":["Use hash tags ({tag}) to group related keys in the same slot.","Validate multi-key commands with a same-slot check before sending.","Split cross-slot multi-key operations into individual per-key commands."],"tags":["cross-slot","multi-key","cluster-routing","hash-tags"],"backgroundTag":null,"analyzedSha":"6a6b581b48225afa0b76912d1028c6035baee932","analyzedAt":"2026-08-10T12:52:44.840Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-21T04:17:39.646Z"}