Кластер Redis и сегментирование
Узнайте, как Redis Cluster горизонтально масштабирует кэш между множеством узлов с помощью хеш-слотов, как маршрутизируются ключи и как объединять связанные ключи с помощью хеш-тегов.
«Кластер Redis и сегментирование» — бесплатный урок Caching Strategies: Redis + CDN + Edge Computing на CoddyKit. Это урок 4 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Caching Strategies: Redis + CDN + Edge Computing, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Caching Strategies: Redis + CDN + Edge Computing содержит 4 уроков всего.
Части этого урока еще не переведены и отображаются на английском.
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.
Часто задаваемые вопросы
Урок «Кластер Redis и сегментирование» бесплатный?
Да — полный текст урока «Кластер Redis и сегментирование» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Caching Strategies: Redis + CDN + Edge Computing, подпишись на CoddyKit PRO. Курс Caching Strategies: Redis + CDN + Edge Computing содержит 4 уроков всего.
Чему я научусь в уроке «Кластер Redis и сегментирование»?
Узнайте, как Redis Cluster горизонтально масштабирует кэш между множеством узлов с помощью хеш-слотов, как маршрутизируются ключи и как объединять связанные ключи с помощью хеш-тегов. Ты практикуешь Caching Strategies: Redis + CDN + Edge Computing с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать Caching Strategies: Redis + CDN + Edge Computing?
Предыдущий опыт не требуется. Caching Strategies: Redis + CDN + Edge Computing на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 4 из 4.
Сколько времени занимает урок «Кластер Redis и сегментирование»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке Caching Strategies: Redis + CDN + Edge Computing?
Да. Каждый урок Caching Strategies: Redis + CDN + Edge Computing включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.
Все уроки этого курса
- Сохранность данных и HA в Redis
- Распределённое кэширование с Redis
- Redis Pub/Sub для аннулирования кэша
- Кластер Redis и сегментирование