SkillByAIOpen interactive version →

Lesson 14 / 25

Redis, Memcached and Cache Clusters

Compare Redis and Memcached and understand how cache clusters shard and replicate.

Two popular distributed caches

Memcached is a simple, multi-threaded, in-memory key-value cache: strings in, strings out, LRU eviction, no persistence or replication built in. Clients usually shard keys across servers with consistent hashing, so adding a server remaps only a fraction of keys. It is fast and predictable for plain caching. Redis (and its open-source fork Valkey) is an in-memory data structure server: strings, hashes, lists, sets, sorted sets, streams, with atomic operations, Lua scripting, optional persistence, replication and pub/sub. Its command execution is essentially single-threaded per instance, which keeps operations atomic but means one slow command blocks others. Redis Cluster splits the keyspace into 16,384 hash slots spread over primary nodes, each with replicas for failover; multi-key operations work only when keys share a slot, which you can force with hash tags such as {user:42}:profile. Managed services include Amazon ElastiCache, Azure Cache for Redis and Google Memorystore.

Keeping related keys in one Redis Cluster slot

Only the part inside braces is hashed, so these keys land together and can be used in one transaction.

redis-cli -c SET "{user:42}:profile" '{"name":"Asha"}'
redis-cli -c SET "{user:42}:cart"    '{"items":3}'
redis-cli -c CLUSTER KEYSLOT "{user:42}:profile"   # same slot as {user:42}:cart

# without a hash tag these two keys may live on different nodes,
# and MGET or MULTI across them fails with a CROSSSLOT error

Pigeonholes in a staff room

Redis Cluster has 16,384 numbered pigeonholes spread over a few cabinets. A key's name decides its pigeonhole. Writing {user:42} on several letters makes them all go into the same pigeonhole, so you can collect them together.

Quick check: What is a key difference between Memcached and Redis?

  • Memcached supports sorted sets and streams
  • Redis cannot be used as a cache
  • Memcached uses 16,384 hash slots
  • Redis offers rich data structures, replication and optional persistence; Memcached is a simple key-value cache
Answer

Redis offers rich data structures, replication and optional persistence; Memcached is a simple key-value cache — Redis is a data-structure server with replication and persistence; Memcached focuses on simple caching.