Redis Cluster y sharding
Aprenda cómo Redis Cluster escala horizontalmente una caché entre muchos nodos mediante hash slots, cómo se enrutan las claves y cómo mantener juntas las claves relacionadas usando hash tags.
Redis Cluster y sharding es una lección gratuita de Caching Strategies: Redis + CDN + Edge Computing en CoddyKit. Esta es la lección 4 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Caching Strategies: Redis + CDN + Edge Computing, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Caching Strategies: Redis + CDN + Edge Computing incluye 4 lecciones en total.
Partes de esta lección aún no han sido traducidas y se muestran en inglés.
Why Scale Beyond One Node?
A single Redis instance is limited by one server's memory and throughput. Redis Cluster spreads data across many nodes so the cache can grow far beyond a single machine.
Hash Slots
Redis Cluster divides the keyspace into 16384 hash slots. Each node owns a range of slots. A key belongs to exactly one slot, determined by hashing the key.
TOTAL_SLOTS = 16384
def slot_for(crc):
return crc % TOTAL_SLOTS
print('Slot:', slot_for(123456789))CRC16 Routing
The slot is computed as CRC16(key) mod 16384. The client (or cluster) uses this to know which node holds the key, so reads and writes go directly to the right place.
Slot Distribution
With three nodes, slots split roughly into thirds. Adding a node means moving some slots to it; removing one redistributes its slots. This is how the cluster rebalances.
nodes = 3
per_node = 16384 // nodes
print('Approx slots per node:', per_node)MOVED and ASK Redirects
If a client contacts the wrong node, the node replies with a MOVED redirect pointing to the correct node. During slot migration, a temporary ASK redirect is used. Smart clients cache the slot map.
The Multi-Key Limitation
Operations across multiple keys (like MGET or transactions) only work if all keys live in the same slot. Otherwise the cluster rejects the command, because the keys may be on different nodes.
Hash Tags
Hash tags solve this. Only the part inside curly braces is hashed, so keys sharing a tag land in the same slot. user:{42}:profile and user:{42}:cart are co-located.
def hash_part(key):
if '{' in key and '}' in key:
start = key.index('{') + 1
end = key.index('}')
return key[start:end]
return key
print(hash_part('user:{42}:cart'))Replicas for Availability
Each master node can have replicas. If a master fails, a replica is promoted automatically, so the slot range stays available. This combines sharding with high availability.
Cluster vs Client-Side Sharding
Before Redis Cluster, apps sharded manually by hashing keys to instances in client code. Cluster mode moves that logic into Redis itself, handling rebalancing and failover automatically.
Trade-offs of Clustering
Clustering adds power but also constraints: cross-slot operations are limited, multi-key Lua scripts need same-slot keys, and operations are more complex. Use it when a single node truly is not enough.
When to Cluster
Reach for Redis Cluster when memory or throughput exceeds one node, when you need automatic failover at scale, or when a region demands many nodes. For smaller caches, a single primary with a replica is simpler.
Quick Check
You need MGET to fetch two related keys atomically in a Redis Cluster. How do you guarantee they live on the same node?
Recap
You learned Redis Cluster and sharding:
- The keyspace splits into 16384 hash slots owned by nodes.
- CRC16 routing plus MOVED/ASK redirects locate keys.
- Multi-key ops need same-slot keys; hash tags co-locate them.
- Replicas add automatic failover.
Clustering scales a cache horizontally when one node is not enough.
Aprende Caching Strategies: Redis + CDN + Edge Computing con un tutor de IA — gratis
Escribe y ejecuta código real en tu navegador, obtén ayuda instantánea de un tutor de IA disponible 24/7 y continúa donde lo dejaste en la web o en la aplicación.
- Cursos
- 12
- Lecciones
- 48
Preguntas frecuentes
¿La lección «Redis Cluster y sharding» es gratis?
Sí — el texto completo de «Redis Cluster y sharding» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Caching Strategies: Redis + CDN + Edge Computing, actualiza a CoddyKit PRO. El curso de Caching Strategies: Redis + CDN + Edge Computing incluye 4 lecciones en total.
¿Qué aprenderé en «Redis Cluster y sharding»?
Aprenda cómo Redis Cluster escala horizontalmente una caché entre muchos nodos mediante hash slots, cómo se enrutan las claves y cómo mantener juntas las claves relacionadas usando hash tags. Practicas Caching Strategies: Redis + CDN + Edge Computing con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.
¿Necesito experiencia previa para empezar Caching Strategies: Redis + CDN + Edge Computing?
No se requiere experiencia previa. Caching Strategies: Redis + CDN + Edge Computing en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 4 de 4.
¿Cuánto tiempo toma la lección «Redis Cluster y sharding»?
La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.
¿Puedo escribir y ejecutar código en esta lección de Caching Strategies: Redis + CDN + Edge Computing?
Sí. Cada lección de Caching Strategies: Redis + CDN + Edge Computing incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.
Todas las lecciones de este curso
- Persistencia y alta disponibilidad en Redis
- Almacenamiento en caché distribuido con Redis
- Redis Pub/Sub para la invalidación
- Redis Cluster y sharding