Skip to content

Distributed Caching with Redis and Memcached

Intermediate 40 min read Part 7 of 18

Running a cache across many nodes: client, proxy and server-side sharding, Redis vs Memcached, replication and failover, Meta-style invalidation, tiers, cost.

Summary#

A distributed cache spreads cached data over many nodes so it can hold more data and serve more requests than one server, and so that every application server shares the same copy. Keys are split across nodes by client-side sharding (the client library hashes the key), a proxy (Twemproxy, Envoy, mcrouter) or server-side sharding (Redis Cluster's hash slots). Redis offers rich data structures, replication and persistence; Memcached is a simpler, multi-threaded pure cache. Replication and failover keep the cache available when nodes die. At very large scale, keeping caches consistent with the database needs a deliberate design, as in Meta's memcache with commit-log-driven invalidation and leases. Most systems use multi-tier caching (in-process plus distributed). Size it for the hot set and peak throughput, and weigh the cost of RAM against the database load it saves.

Why It Exists#

An in-process cache lives inside each application server. With 200 servers, there are 200 separate copies: memory is wasted, each copy can be stale in a different way, a restart loses everything, and invalidating a key means telling 200 processes. A single shared cache server fixes that, until it runs out of memory or throughput: one Redis node handles roughly 100k-200k simple operations per second and holds whatever RAM it has. A distributed cache shares one logical cache across a cluster that scales by adding nodes. This page builds on Consistent Hashing.

How It Works#

Why a distributed cache#

  • Capacity: the hot set (say 300 GB) is larger than one machine's RAM.
  • Throughput: 1 million reads per second needs many nodes.
  • Shared view: all app servers see the same value; one delete invalidates it everywhere.
  • Survives app restarts and deploys: the cache stays warm while apps roll.
  • Availability: with replicas, losing a node loses only part of the cache, or none of it.

Why a distributed cache, in depth#

Memory versus disk, in numbers. A distributed cache is fundamentally a way to answer reads from RAM instead of from storage. Main-memory access takes about 100 ns, an SSD random read about 0.1 ms and a spinning-disk seek about 10 ms, so memory is roughly 1,000 times faster than SSD and 100,000 times faster than a hard disk. In operations per second, memory serves millions of reads per second per machine, a fast SSD on the order of 100,000 IOPS, and a hard disk only 100 to 200. Over a network, a Redis read takes 0.2 to 1 ms end to end because the network hop dominates. The command itself runs in microseconds. A database read that touches disk or does real query work takes 5 to 50 ms.

What teams actually put in a distributed cache.

  • Expensive query results: a timeline that joins follows, posts and users, computed once and read many times.
  • Precomputed aggregates: an analytics dashboard whose metrics are recomputed hourly by a background job and stored in the cache, so dashboard views never trigger the heavy computation.
  • Hot entities: products, profiles, short-URL mappings. In a URL shortener, the short-code-to-URL mapping is read far more than it is written and almost never changes, so the cache is nearly free of invalidation work, and a redirect can be served in about a millisecond.
  • Shared ephemeral state: user sessions, rate-limit counters, distributed locks, leaderboards. Here the cache is the store, and its durability matters.

Name the data structure, not just "the cache". Redis is a data-structure server, so the structure is part of the design. Popular events for a ticketing site can live in a sorted set scored by popularity, so "top 20 events" is one ZREVRANGE call. A product can be a hash, so a price update changes one field with HSET. Unique visitors per page can be a HyperLogLog, about 12 KB per counter with a standard error of about 0.81%, whatever the number of visitors. Saying "a sorted set keyed by city, scored by sales in the last hour" shows far more understanding than "I'll cache the events".

One node goes surprisingly far. Before distributing, check whether one node would do. A single Redis node handles on the order of 100,000 writes per second and more reads, and cloud instances offer hundreds of gigabytes of RAM. A single primary with a replica is simpler to run than a cluster: there are no cross-slot restrictions and no resharding. Distribute when the hot set exceeds a comfortable single-node size (say 50 to 100 GB, since large nodes take long to resync and fork), when throughput exceeds one node, or when one failure would remove too much of the cache at once.

Round trips, not commands, are the cost. Because each command costs the server microseconds, patterns that would be ruinous on a SQL database, such as one lookup per item in a list, are survivable on Redis if you batch them. MGET fetches many keys in one call, and pipelining sends many commands without waiting for each reply, so 100 lookups cost one round trip instead of 100. In a cluster, a client library splits an MGET by node and issues the parts in parallel.

Client-side vs proxy vs server-side sharding#

Client-side shardingProxyServer-side (cluster)
HowLibrary hashes keys to nodes (consistent hashing)Apps send everything to a proxy that routesCluster owns the key map; clients cache it and follow redirects
Extra hopNoneOne (about 0.1-0.5 ms)None once the map is cached
Client complexityEvery client language needs the logic and the same configSimple clientsCluster-aware client needed
Membership changesAll clients must update config togetherOnly proxies changeCluster rebalances slots; clients follow
Examplesketama Memcached clients, Jedis/Lettuce shardingTwemproxy, mcrouter (Meta), Envoy Redis proxyRedis Cluster (16,384 hash slots), ElastiCache cluster mode

Redis Cluster computes CRC16(key) mod 16384 to find a key's slot. Multi-key operations work only when all keys share a slot; hash tags ({user:42}:profile, {user:42}:settings) force related keys into the same slot. When slots move between nodes, a node answers MOVED or ASK and the client retries at the right node.

Sharding, in depth#

Why not hash modulo N. The naive rule node = hash(key) mod N moves almost every key when N changes. Going from 10 to 11 nodes keeps a key on the same node only if its hash gives the same remainder for both moduli, which is true for about 1 in 11 keys, so about 91% of keys move. For a cache, "move" means "miss", so adding capacity briefly costs the database almost the whole read load. Consistent hashing, hash slots and rendezvous hashing all reduce the movement to about 1/N of the keys.

Consistent hashing with virtual nodes. Each server is placed on a hash ring at many points (Memcached's ketama clients use about 100 to 160 points per server), and a key belongs to the first server point clockwise from the key's hash. Adding a server takes over only the arcs just before its points, about 1/N of the keys, taken evenly from all existing servers. Virtual nodes smooth out the load. With only one point per server, arc sizes vary wildly and some servers get several times the average share. See Consistent Hashing.

Alternatives. Rendezvous (highest random weight) hashing (Thaler and Ravishankar, 1998) computes a score for every (key, server) pair and picks the highest. It needs no ring, moves only the minimum number of keys and makes replica selection easy (take the top two scores), at the cost of O(N) work per lookup, which is fine for tens of nodes. Jump consistent hash (Lamping and Veach, 2014) maps a key to one of N numbered buckets with no memory at all and near-perfect balance, but it supports only adding or removing the last bucket, so it suits storage shards more than cache nodes that fail at random.

Redis Cluster's hash slots. Redis Cluster fixes the number of partitions at 16,384 slots and assigns slots, not keys, to nodes. A key's slot is CRC16(key) mod 16384, computed on the part inside {braces} if the key contains a hash tag. Consequences:

  • Clients route directly. Cluster-aware clients fetch the slot map (CLUSTER SHARDS) and cache it, compute each key's slot locally and send the command straight to the owning node. There is no extra hop.
  • Wrong node, explicit redirect. If the map is stale, the node replies MOVED slot host:port, meaning the slot has moved permanently, and the client updates its map. During a migration, a key that has already moved gets ASK, a one-time redirect: the client sends ASKING and then the command to the target node, without updating its map, because the migration is not finished.
  • No query router. Redis does not split a multi-key command across nodes and merge the results. Commands touching keys in different slots fail with a CROSSSLOT error. Key design, including hash tags, is how you scale Redis. Over-using one hash tag recreates a hot slot.
  • Resharding moves keys one at a time. MIGRATE is atomic per key, so big keys make migration slow and block both nodes while they move.

Proxies in practice. A proxy centralises routing so clients stay simple. mcrouter, Meta's open-source memcached proxy, routes by key prefix to different pools, replicates writes to several pools, fails over to backup pools such as the gutter pool, and can shadow a share of traffic to a test pool before a migration. Twemproxy (from Twitter) shards Redis and Memcached with consistent hashing and pipelines requests. Envoy has a Redis proxy filter that does hashing, connection pooling and request splitting for multi-key commands. A proxy adds about 0.1 to 0.5 ms per request and needs its own fleet, but it cuts the number of connections each cache node sees from "every application process" to "every proxy", which matters at tens of thousands of application processes.

Redis vs Memcached#

RedisMemcached
Data modelStrings, hashes, lists, sets, sorted sets, streams, bitmaps, HyperLogLog, geoStrings (opaque byte values)
ThreadingCommands run on one main thread (I/O threads optional)Multi-threaded
Throughput per node~100k-200k simple ops/s per core-bound instance; run several per hostScales with cores; very high on one large host
PersistenceOptional RDB snapshots and AOF logNone (pure cache)
Replication and failoverBuilt-in replicas, Sentinel, ClusterNone built in; clients or proxies handle it
Max value size512 MB (keep far smaller)1 MB by default (configurable)
EvictionLRU/LFU/random/TTL policiesSegmented LRU
ExtrasLua scripts, transactions, pub/sub, atomic counters, TTL per keyMinimal, predictable
FitsMost new systems; caches plus leaderboards, rate limiters, sessions, queuesLarge simple object caches where multi-threaded throughput and simplicity matter

Default to Redis (or a compatible engine such as Valkey, the Linux Foundation fork created in 2024) unless you have a specific reason for Memcached. See Redis in Practice.

Redis vs Memcached, in depth#

Threading model. Memcached is multithreaded from the start. Worker threads share one hash table protected by fine-grained locks, so one big machine with many cores serves well over a million simple gets per second. Redis runs commands on a single main thread. Since Redis 6, optional I/O threads take over socket reads and writes, but command execution is still serial. That serial execution is a feature: every command, every MULTI/EXEC block and every Lua script is atomic without locks. The cost is that one slow command, such as KEYS *, HGETALL on a hash with a million fields or DEL on a huge set, stalls every other client on that node. To use many cores, Redis users run several instances per machine or a cluster.

Memory management. Memcached uses a slab allocator. Memory is cut into 1 MB pages, and each page is assigned to a slab class of fixed chunk size (for example 96 bytes, 120 bytes, 152 bytes, growing by a factor of about 1.25). An item goes into the smallest chunk that fits, so there is no external fragmentation, but a 100-byte item in a 120-byte chunk wastes 20 bytes. When the size mix of items changes over time, pages can end up stuck in the wrong classes, a problem called slab calcification. Modern Memcached has a slab rebalancer that moves pages between classes automatically. Each slab class has its own segmented LRU with hot, warm and cold sections, so eviction is per class, not global. Redis uses a general allocator (jemalloc by default). It suffers some fragmentation, visible as mem_fragmentation_ratio in INFO memory. Active defragmentation can compact memory online.

Data model. Memcached stores opaque byte strings up to 1 MB by default, with get, set, add, replace, increment, append and check-and-set (CAS) using a version token. Redis stores strings up to 512 MB plus hashes, lists, sets, sorted sets, streams, bitmaps, HyperLogLogs and geospatial indexes, with server-side operations on each. This is why Redis covers leaderboards, queues, rate limiters and locks, while Memcached is purely a cache.

Persistence and durability. Memcached has none: a restart empties it. Its extstore feature (added in the 1.5 series) moves item values to flash while keeping keys and metadata in RAM, so one node can hold far more data at the cost of slightly slower reads. That suits large, cold caches. Redis offers RDB snapshots (a forked child writes a point-in-time file) and an AOF append-only log with fsync every write, every second or left to the OS. With appendfsync everysec, a crash loses about one second of writes. Persistence makes a restart warm instead of cold, but it does not make an async-replicated Redis a system of record.

The licensing split and the forks. In March 2024 Redis moved from the BSD licence to source-available licences. The Linux Foundation then launched Valkey, a fork of Redis 7.2 supported by several cloud providers, and managed services began offering it. Redis 8 later added the AGPL as an open-source licence option. For design purposes, Valkey and Redis expose the same commands and cluster protocol. Dragonfly reimplements the Redis protocol with a multithreaded, shared-nothing design that splits the keyspace across threads inside one process. KeyDB is a multithreaded fork of Redis. Both aim to use many cores in a single node, trading Redis's long track record and ecosystem for vertical throughput.

A practical decision rule.

  • Pick Memcached for a pure, very large look-aside cache of blobs, where multithreaded throughput per node and simple operation matter most, and where you will never need structures or persistence. Meta, for example, runs memcached at very large scale behind mcrouter.
  • Pick Redis or Valkey when you need structures, atomic server-side operations, pub/sub, TTL per key with fine control, replication with automatic failover, or the cache doubles as a store for sessions, counters and locks. This is the default in most designs and interviews.
  • Consider a managed durable variant (for example Amazon MemoryDB, which commits writes to a multi-AZ transaction log before acknowledging them) when you want the Redis API but cannot lose acknowledged writes.

Replication and failover#

A cache node failure means its keys miss until rebuilt, which shifts load to the database (see Cache Failure Modes). Options:

  • No replication (classic Memcached): a lost node's keys are rebuilt from the database. Acceptable if the database can absorb 1/N of the reads.
  • Primary-replica per shard (Redis): each shard has replicas that receive changes asynchronously. Redis Sentinel or Redis Cluster promotes a replica if the primary fails, typically within seconds to tens of seconds. Writes acknowledged just before a failure can be lost (asynchronous replication), which is fine for a cache.
  • Zone-spread replicas: place replicas in different availability zones; managed services (ElastiCache, Memorystore, Azure Cache for Redis) automate Multi-AZ failover.
  • Replicated reads: send reads to replicas to spread hot-key load, accepting slightly stale values.
  • Client-side replication: write each key to two independent clusters (Netflix EVCache writes to clusters in multiple zones and reads from the local one).

Replication and failover, in depth#

How Redis replication works. A replica connects to its primary and asks to sync. A full sync forks the primary, writes an RDB snapshot, ships it and then streams every write command after it. The primary keeps a circular replication backlog (1 MB by default, usually raised to hundreds of MB), so a replica that briefly disconnects can resume with PSYNC from its last offset instead of downloading a full snapshot. If the backlog wrapped around during the outage, a full sync is needed. On a 50 GB node that full sync takes minutes and uses a lot of network bandwidth, and the fork can briefly double memory for pages written during the snapshot (copy-on-write). This is a major reason to keep nodes moderately sized.

Asynchronous means acknowledged writes can vanish. The primary replies "OK" to the client before the replica has the write. If the primary dies a few milliseconds later, the promoted replica never had it. The WAIT numreplicas timeout command blocks until a number of replicas acknowledge, which narrows the window. It does not make Redis strongly consistent, because a replica that acknowledged may still not be the one promoted, and failover does not wait for every write. min-replicas-to-write makes a primary refuse writes when too few replicas are connected, which limits how much a partitioned old primary can accept before it is demoted.

Who decides on failover. With Redis Sentinel (for non-cluster setups), several Sentinel processes watch the primary. When a configured quorum of them consider it down, one Sentinel is elected leader by a majority and promotes the best replica (most recent offset, priority setting). Clients ask Sentinel for the current primary's address. Run at least three Sentinels in separate failure domains, so that one lost zone cannot block or fake a decision. In Redis Cluster, nodes exchange heartbeats over the cluster bus. If a primary is unreachable for longer than cluster-node-timeout (commonly 5 to 15 seconds), the other primaries mark it failed, and its replicas run an election that needs votes from a majority of primaries. Typical failover takes several seconds to tens of seconds, during which writes to that shard fail. Clients must retry with backoff and refresh their slot map.

Reading from replicas. By default a cluster client sends everything to primaries. To read from replicas, the client issues READONLY on its replica connections and routes reads there, accepting reads that lag the primary by milliseconds, or longer under load. That is fine for cached data, which is already a stale copy, and dangerous for locks or counters that must see the latest write. Replicas help read-hot keys, but not write-hot keys, because every write still lands on the one primary.

Locks on a cache: efficiency, not correctness. The standard Redis lock is SET key token NX PX 30000: set only if absent, expire after 30 seconds, store a unique random token. Release with a Lua script that deletes the key only if it still holds your token, so a slow client cannot delete someone else's lock:

-- KEYS[1] = lock key, ARGV[1] = my token
if redis.call("GET", KEYS[1]) == ARGV[1] then
  return redis.call("DEL", KEYS[1])
end
return 0

The diagram above shows the flaw: failover can grant the lock twice. Redlock, proposed by the Redis author, acquires the lock on a majority of independent primaries. Martin Kleppmann's 2016 essay "How to do distributed locking" argued that Redlock still relies on timing assumptions (bounded pauses, clock drift and network delay), so a long GC pause can leave two holders. The robust fix is a fencing token: a number that increases with every grant, which the protected resource checks and rejects if it is older than one it has seen. Rule of thumb: a Redis lock is fine to stop duplicate work (two workers recomputing the same report). When duplicate work would corrupt data (double-charging, overselling a seat), use a consensus system (ZooKeeper, etcd) with fencing, or a database row lock or conditional write. A related choice is pessimistic versus optimistic concurrency. Taking a lock first is pessimistic. WATCH key, read, then MULTI ... EXEC, which aborts if the key changed, is optimistic and needs no lock.

Consistency at scale: Meta-style invalidation#

Meta's paper "Scaling Memcache at Facebook" (NSDI 2013) describes caching for a read-heavy social graph across regions. Key ideas, all still relevant:

  • Look-aside (cache-aside) with delete on write, never update: web servers delete keys after writing to MySQL.
  • Leases: on a miss, the cache hands out a lease token; only that holder may fill the key, and a delete invalidates the lease. This prevents stale sets and limits stampedes (other clients wait briefly).
  • Commit-log-driven invalidation: a daemon (mcsqueal) tails the MySQL commit log and broadcasts deletes to all cache clusters, so every cluster and region is invalidated after each commit, even for writes from other paths.
  • Regional replication: in non-primary regions, writes go to the primary region's database; a remote marker in the local cache tells readers to fetch from the primary region until replication catches up, avoiding stale reads after a user's own write.
  • Gutter pool: when a cache server fails, clients send its keys to a small spare pool with short TTLs instead of rehashing to other servers or hitting the database.

The lesson: at scale, invalidation is a pipeline driven by the database log, not a best-effort side effect in application code. See Change Data Capture.

Consistency at scale, in depth#

The topology behind the ideas. In the design described in the Meta paper, a region contains several front-end clusters. Each cluster has web servers and its own memcached servers, plus one shared storage cluster of MySQL databases. Within a cluster, keys are spread over the memcached servers with consistent hashing, so a page that needs hundreds of items talks to many cache servers at once. Rarely read or very large items that do not need copying into every cluster sit in a regional pool shared by all front-end clusters, which saves memory. Replicating every item into every cluster would waste it. One region holds the primary databases, and other regions hold read replicas fed by MySQL replication.

Why invalidate from the commit log, not from the web server. If the web server that wrote the row sent deletes to every cluster in every region, two things would go wrong. First, the fan-out would be enormous, and a crashed web server would lose its deletes. Second, in a replica region the delete could arrive before replication delivers the new row, and the next miss would refill the cache from the old replica row. Tailing each region's own database commit log solves both. The delete is generated only after the change is durable in that region's database, so a refill after the delete reads the new value. Deletes are batched into packets and sent through mcrouter to the right servers, which cuts packet rates sharply. The writing web server still deletes the key in its own cluster right away, so the user who wrote sees their change.

Leases, with the numbers. A lease is a 64-bit token issued on a miss and bound to the key. A set with an invalidated token is rejected, which prevents the stale-set race. To tame stampedes, the server hands out a token for a given key only once every 10 seconds, and other clients that miss in that window are told to wait briefly and retry, by which time the value is usually there. The paper reports that leases cut the peak database query rate for a hot workload from about 17,000 to about 1,300 queries per second. A refinement lets a waiting client accept a slightly stale value, marked as stale, when the application can tolerate it, instead of waiting.

Cold cluster warm-up. A brand-new or emptied front-end cluster would send almost every read to the database. Instead, during warm-up its clients read misses from a warm cluster's memcached rather than the database, and then fill their own cache. This creates a race: a delete in the cold cluster could be followed by a fill from the warm cluster that has not seen the delete yet. The fix is a hold-off: after a delete in the cold cluster, adds for that key are refused for about two seconds. A warm-up that would take days of database load completes in hours.

Network effects. Reads used UDP to the memcached servers to cut connection overhead, and a dropped packet was treated as a miss. Writes and deletes used TCP through mcrouter for reliability. A page that requests hundreds of keys at once can cause incast: all the responses arrive together and overflow switch buffers. Clients used a sliding window, like TCP congestion control, to cap outstanding requests.

Read-your-writes across regions. A user in a replica region writes to the primary region. Before writing, the web server sets a remote marker for the key in its regional cache. Any read that finds the marker goes to the primary region's database instead of the stale local replica. When replication delivers the change, mcsqueal's delete clears the marker. Reads of that key pay cross-region latency for a short time, and only that user's change pays it.

TAO, the next step. Meta later built TAO (Bronson et al., USENIX ATC 2013), a cache that understands the social graph (objects and associations) instead of opaque keys. TAO caches are write-through: a follower cache tier forwards writes to a leader tier, which writes the database and updates its own cache, then sends invalidations to followers. Because a write updates the cache tier it passes through, the writer reads its own write within that tier. Graph-aware caching also allows queries such as "the 50 newest comments on this post" to be answered from cache, which a plain key-value cache cannot do.

Multi-tier caching (local + distributed)#

read(key):
  v = local_cache.get(key)           # L1: in-process, ~100 ns, TTL 5-30 s, small
  if v: return v
  v = redis.get(key)                 # L2: shared, ~0.5-1 ms, TTL minutes-hours
  if v: local_cache.put(key, v); return v
  v = db.load(key)                   # source of truth, 5-50 ms
  redis.set(key, v, ttl_with_jitter()); local_cache.put(key, v)
  return v
  • L1 (in-process) absorbs the hottest keys with no network hop and protects L2 from hot-key overload. Keep its TTL short, because invalidating every server's L1 is hard (use pub/sub broadcasts or accept seconds of staleness).
  • L2 (distributed) holds the shared hot set.
  • Above both sit the CDN and browser caches for HTTP-cacheable content.

Redis 6+ client-side caching (server-assisted tracking) notifies clients when keys they cached locally change, which makes L1 invalidation easier.

Multi-tier caching, in depth#

Where a cache can live, from far to near. Every tier closer to the user removes a network hop but gives the backend less control over it.

Client and device caches. Browsers cache by HTTP headers, and mobile apps keep their own stores. A fitness app such as Strava records a run on the phone while the user has no signal and uploads it later, so the device is a cache and a write buffer in one. Device caches are the fastest of all and cost the backend nothing, but the backend cannot reliably invalidate them, because a phone may be offline for days. Design for that with version numbers, short max-age, or server responses that tell the client its copy is out of date. A different kind of client-side cache sits inside your own services: a Redis Cluster client caches the slot map, and a database driver caches prepared statements. These are usually invisible but matter during failovers.

CDN and edge. A request from India to an origin in Virginia costs roughly 250 to 300 ms of round-trip time before any work is done, while an edge location in the same country answers in 20 to 40 ms. For a URL shortener, an edge function (Cloudflare Workers, Lambda@Edge) can look up the short code in an edge key-value store and return the redirect without reaching the origin. The trade-offs: invalidating a changed or deleted link must propagate to hundreds of locations, edge runtimes limit CPU time, memory and libraries, cost is per request, and debugging a bug that only shows at some locations is hard.

In-process L1, used well. An in-process cache (Caffeine for Java, an LRU map in Go or Node) answers in about 100 ns with no serialisation. It suits:

  • configuration and feature flags, refreshed every few seconds;
  • small reference data such as country codes, currency rates and category trees;
  • the hottest few thousand keys, to protect L2 from hot-key overload;
  • precomputed values used on every request, such as a compiled permission set;
  • local token buckets for approximate per-instance rate limits.

It is not shared: each of 200 servers has its own copy, so the effective memory is 200 times smaller than it looks, the hit ratio is lower than a shared cache, and 200 copies can disagree. In an interview, propose the external cache first and add an L1 only for a named reason, such as a hot key or a config read on every request.

Server-assisted client-side caching in Redis. Redis 6 added CLIENT TRACKING. In the default mode, the server remembers which keys each client has read and sends an invalidation message when one of them changes. With RESP3 the message arrives on the same connection, and with RESP2 it is redirected to a pub/sub channel. In broadcast mode (BCAST PREFIX user:), the server keeps no per-client key list and notifies every subscribed client about every change under the prefix. That uses less server memory but sends more messages. OPTIN tracks only keys the client marks, and NOLOOP skips notifications for the client's own writes. Tracking turns L1 staleness from "TTL seconds" into "about one network delay", but if the connection drops, the client must flush its L1, because it may have missed invalidations.

Hot keys at cluster scale. Picture 100 cache nodes and a product page that suddenly gets 500,000 reads per second. Every one of those reads hashes to the same node, so 99 nodes idle while one melts. Fixes, in order of preference:

  1. L1 in the application, with a TTL of one to five seconds. 500,000 reads become one L2 read per server every few seconds.
  2. Key copies: write the value under product:123:1 to product:123:10, which hash to different nodes, and have readers pick a random suffix. Writers must update all copies, and clients must know which keys are hot, usually from a shared hot-key list that a detector publishes.
  3. Read replicas for the hot shard, if the client is configured to read from them. This adds read capacity only. A key that is hot for writes, such as a global counter, needs a different design: shard the counter into sub-counters and sum them on read.

Sizing and cost#

Size for both memory and throughput, then add headroom:

Memory:
  hot set = 50 M items x 2 KB = 100 GB
  overhead (keys, pointers, fragmentation) ~1.3-1.5x = 140 GB
  replicas x2 (primary + one replica) = 280 GB
  headroom 30% = ~365 GB total, e.g. 12 nodes of 32 GB usable
Throughput:
  peak 600k ops/s / ~100k ops/s per node = 6 primaries minimum (12 nodes covers it)

Cost: RAM is the expensive part; a cache node with 50-100 GB costs hundreds of dollars a month on public clouds. Weigh it against what it saves: if the cache lets you run 2 database replicas instead of 10, it pays for itself. Reduce cost by caching only hot data (eviction does this), compressing values, using compact encodings (hashes for small objects, MessagePack or Protobuf instead of verbose JSON), and setting sensible TTLs. Extend RAM with flash tiers (Redis on Flash, Memcached's extstore) for large, less-hot data.

Sizing and cost, in depth#

Hit ratio drives database load. If the database sees (1 - h) x QPS reads, then at 200,000 reads per second a 90% hit ratio sends 20,000 reads per second to the database and 99% sends 2,000. The last few points of hit ratio are worth far more than the first. Plot hit ratio against cache size (a miss-ratio curve, from a shadow cache or a trace) and buy memory up to the knee.

Per-key overhead is real. A Redis key is not just its bytes. Each entry carries a hash-table slot, an object header, string headers and allocator rounding, roughly 50 to 100 bytes, plus TTL bookkeeping. For 100-byte values, overhead is as large as the data. Instagram described in 2011 how storing about 300 million photo-to-user mappings as plain string keys needed about 21 GB, while grouping them into hashes of about 1,000 fields each, which Redis stores in a compact encoding when they are small, cut it to about 5 GB. The lesson is general: small objects benefit from compact encodings and bucketing.

A worked example: URL shortener redirects.

Data:    1 B short links, 20% get 95% of clicks -> 200 M hot links
Item:    key 8 B + URL ~100 B + overhead ~80 B   -> ~190 B
Memory:  200 M x 190 B = 38 GB, x1.25 fragmentation -> ~48 GB
Replica: x2 -> ~96 GB; keep maxmemory at 70-80% of RAM
Traffic: 100 k redirects/s average, 1 M/s peak
Nodes:   1 M/s / ~100 k ops/s per node -> 10 primaries at peak
Result:  10 primaries x 8 GB data each, plus 10 replicas

In this example, throughput, not memory, sets the node count. Each primary holds only about 5 GB, which keeps failover resync fast. If the edge layer absorbed most peak traffic, the origin cache could shrink to three or four primaries.

Bandwidth and connections. At 200,000 operations per second with 2 KB values, a node pushes about 400 MB/s, over 3 Gbps, which can saturate an instance's network before its CPU. Large values call for compression (LZ4 or Zstandard on the client) or a different design. Connections cost memory and CPU too: 5,000 application processes with a pool of 10 connections each means 50,000 connections per node, above Redis's default maxclients of 10,000. Pools, multiplexing clients or a proxy fix this.

Memory headroom for the fork. Snapshotting and full resyncs fork the Redis process. Pages written while the child runs are copied, so a write-heavy node can need up to twice its data size during a snapshot. Set maxmemory well below physical RAM, often 60 to 75% for write-heavy nodes with persistence, and alert on swap, which turns sub-millisecond reads into tens of milliseconds.

Cost levers, ranked by usual effect.

  1. Cache less: shorter TTLs on long-tail keys, and no caching of items read only once.
  2. Encode smaller: compact binary formats, compression for values over a few hundred bytes, short key names at billions of keys.
  3. Tier to flash: Memcached extstore, or flash-backed managed tiers, for large and lukewarm data.
  4. Right-size replicas: a pure cache with a well-protected database may run with one replica, or none for disposable data that can be rebuilt.
  5. Absorb at the edge: every request a CDN answers never reaches the cache fleet.

Then compare the total with the database capacity the cache replaces. A cache that lets you avoid sharding a database usually pays for itself many times over.

Operating a distributed cache#

What to watch, per node and not only in aggregate. A cluster average hides the one node that is in trouble.

SignalHealthy rangeWhat a bad value means
Hit ratioStable, often 90-99%A drop means a deploy changed keys, TTLs shortened, or memory is too small
Evictions per secondLow and steadyA rise means the hot set outgrew memory
Used memory vs maxmemoryBelow about 80%Near the limit, evictions or rejected writes start
p99 latencyUnder 1-2 msA slow command, swap, a fork, or a hot node
CPU of the main threadBelow about 70%The node is near its throughput ceiling, often from a hot key
Replication lag and link statusSeconds or less, link upReplicas are falling behind, or resyncs are looping
Connected clientsWell below maxclientsA connection leak or a reconnect storm

Find hot and big keys before they find you. redis-cli --bigkeys and --memkeys sample the keyspace for the largest keys, and --hotkeys reports the most accessed keys when an LFU eviction policy is set. Client-side sampling, such as logging one request in 10,000 with its key, catches hot keys without touching the server. Disable or rename KEYS, FLUSHALL and FLUSHDB in production, iterate with SCAN, and delete big keys with UNLINK, which frees memory in a background thread.

Eviction and memory policy are part of the design. A TTL guarantees a key is never returned after it expires, so it bounds staleness. It does not stop the node filling up. With maxmemory-policy noeviction, the default on self-run Redis, a full node rejects writes with an out-of-memory error, which is right for a store of sessions or locks and wrong for a cache. A pure cache should use allkeys-lru or allkeys-lfu. volatile-* policies evict only keys that have a TTL, which suits a node mixing cache data with keys that must stay.

Changes are where outages happen. Scale out before peak, not during it, because slot migration adds load to the busiest nodes. Upgrade one shard at a time: fail over to an upgraded replica, then upgrade the old primary. Rehearse a primary failure and a full zone loss regularly, and measure what the database sees, because the cache's job is to protect it.

Worked example: caching ticketing search at scale#

The problem. An event-ticketing site serves 50,000 searches per second at peak, with filters for city, date range, category and free-text keyword. Search runs on Elasticsearch, at 30 to 80 ms per query and a cluster that cannot take the peak alone. Event details change rarely, but a venue change or cancellation must show within about a minute.

Cache keys from every parameter. The result of a search depends on every parameter, so the key must include all of them, in a normalised form: lower-case the keyword, sort the categories, round the date range to days and include the page number. For example: search:v3:city=nyc:cat=music,sports:from=2026-12-05:to=2026-12-07:q=jazz:p=1. Without normalisation, Jazz and jazz occupy two keys and halve the hit ratio. The v3 prefix lets a change in the result format invalidate everything at once by bumping the version.

Expect a skewed hit ratio. A handful of popular queries ("concerts this weekend in NYC") get most of the traffic, while long free-text queries are almost all unique. Cache filter-only searches with a TTL of 60 seconds, which meets the freshness goal on its own. Skip the cache, or use a very short TTL, for long keyword queries that are unlikely to repeat. If filter-only queries are 70% of traffic and 95% of them hit, the search cluster sees about 50,000 x (0.3 + 0.7 x 0.05) = 16,750 queries per second instead of 50,000.

Invalidation for venue changes. TTL alone gives up to 60 seconds of staleness. For a cancelled event, keep a Redis set per event, such as tag:event:991, holding the search keys whose results include it, written when the result is cached. On a cancellation, a CDC consumer reads the event change, deletes every key in the tag set and then the tag set itself. The tag sets cost memory and writes, so use them only where TTL staleness is not acceptable.

Structures beyond search results. "Popular events in this city" is a sorted set per city, scored by recent ticket sales and updated with ZINCRBY as orders complete. The homepage reads the top 20 with one command. Seat holds during checkout are keys with a 10-minute TTL, such as hold:event:991:seat:A12 set with NX, so two buyers cannot hold the same seat and abandoned holds release themselves. The final booking must still be confirmed by a conditional write in the database, because the hold is an efficiency tool and the database is the authority.

When Redis is the wrong tool#

  • As the system of record. Asynchronous replication can lose acknowledged writes during failover, and persistence settings trade durability for speed. Keep authoritative data in a database, or use a durable Redis-compatible service built on a replicated log.
  • When the working set does not fit in RAM economically. If the hot set is tens of terabytes with a flat access pattern, a disk-based store with a good page cache (Cassandra, ScyllaDB, DynamoDB) often costs far less than RAM.
  • When you need query flexibility. Redis answers the questions you designed keys for. Ad hoc filters, joins and secondary indexes belong in a database or a search engine.
  • When operations must span many keys atomically across shards. Cross-slot transactions are not supported in Redis Cluster. If the data cannot share a hash tag without creating a hot slot, the cache is the wrong place for that invariant.
  • For durable, replayable event streams. Redis Streams work for small, short-lived queues, but retention is bounded by memory, and replay after days or consumer groups at high scale fit Kafka better.
  • For large binary objects. Images, videos and multi-megabyte documents waste RAM and block the single command thread while they are copied. Store them in object storage behind a CDN and cache only their metadata and URLs in Redis.

When to Use It#

  • Many app servers need a shared cache, or the hot set exceeds one machine's memory.
  • Read throughput beyond what one cache node can serve.
  • Sessions, rate-limit counters, leaderboards and other shared ephemeral state.
  • Multi-region systems that need a fast local copy of data per region.

When NOT to Use It#

  • One app server, or tiny datasets: an in-process cache is simpler and faster.
  • When a CDN can cache the response at the edge.
  • As the only copy of important data without persistence and replication.

How to Implement It#

  1. Estimate the hot set and peak ops/s; pick node size and count with headroom.
  2. Choose Redis (Cluster mode for sharding) unless Memcached's simplicity suits better.
  3. Choose routing: cluster-aware clients, or a proxy for many languages and large fleets.
  4. Enable replicas across zones with automatic failover; test failover.
  5. Add an L1 in-process cache for the hottest keys with short TTLs.
  6. Invalidate from the database log once many writers exist; use leases or versioned sets for hot keys.
  7. Monitor hit ratio, memory, evictions, latency per node, hot and big keys, and replication lag.
TechnologyFits when
Redis Cluster / ValkeySharded cache with data structures and HA
Amazon ElastiCache, Google Memorystore, Azure Cache for RedisManaged Redis/Memcached
Memcached + mcrouterVery large simple caches with proxy routing
Netflix EVCacheMemcached-based, replicated across zones (open source)
Caffeine, GuavaL1 in-process cache

Trade-offs#

ChoiceGainCostPick when
Client-side shardingNo extra hopConfig sync across clientsFew client languages, stable membership
ProxySimple clients, central controlExtra hop, proxy fleetLarge, multi-language fleets
Redis ClusterBuilt-in sharding and failoverCluster-aware clients; multi-key limitsMost Redis deployments
ReplicationSurvives node loss2x memoryDB cannot absorb a node's misses
L1 + L2 tiersLowest latency, hot-key protectionL1 staleness, harder invalidationRead-heavy, hot-key workloads
MemcachedMultithreaded throughput, simple ops, extstoreStrings only, no replication or persistenceHuge look-aside blob caches
Key copies for hot keysSpreads one key's reads across nodesWrite fan-out, clients must know hot keysKnown, read-hot keys
Server-assisted client cachingL1 invalidated within a network delayServer memory for tracking, flush on reconnectLarge L1 hit ratios with low staleness
Commit-log invalidationCovers every writer, ordered after durabilityCDC pipeline to run and monitorMany writers or multiple regions

Common Pitfalls#

  • Using mod N client sharding and losing most of the cache when adding a node.
  • Multi-key operations across slots in Redis Cluster without hash tags.
  • No replicas, so one node failure sends a big share of traffic to the database.
  • Long L1 TTLs with no invalidation, so servers disagree for minutes.
  • Sizing only for memory and running out of throughput on hot nodes.
  • Using a Redis lock as the only guard for money or inventory, without fencing or a database check.
  • Leaving noeviction on a pure cache, so a full node starts rejecting writes.
  • Huge nodes that take many minutes to resync after a failover and double memory during forks.
  • Reading from replicas for data that must reflect the latest write, such as lock state.
  • Cache keys built from unnormalised request parameters, splitting one result across many keys.

Real-World Examples#

Meta's memcache paper describes a cache tier handling billions of requests per second, with mcrouter routing, leases, commit-log-driven invalidation and regional replication; mcrouter is open source.

Netflix's EVCache, built on memcached, replicates cached data across availability zones and regions and is open source.

Instagram's 2011 engineering post on storing hundreds of millions of key-value pairs in Redis showed that bucketing small keys into hashes cut memory roughly fourfold. Meta's TAO paper describes moving from a plain look-aside memcache to a graph-aware, write-through cache tier with leader and follower caches.

In the Interview#

Interview playbook for distributed caches#

Order of the conversation. First state what is cached and why: the key format, the value, the read-to-write ratio and the staleness each item tolerates. Then size it with three numbers: hot-set memory, peak operations per second and the node count those imply. Then cover routing (Redis Cluster slots, or a proxy for large polyglot fleets), availability (one replica per shard in another zone, automatic failover, a database that survives a node's misses) and consistency (TTL plus delete after commit, and CDC invalidation once there are many writers). Finish with hot keys and failure behaviour.

Strong answers to common probes.

  • "Why not just add database replicas?" Replicas scale reads too, but each one costs a full copy of the data and replication lag, and a read still costs milliseconds. A cache holding the hot 5% of the data serves sub-millisecond reads at a fraction of the cost.
  • "What happens when you add a node?" With slots, about 1/N of the slots migrate, keys move one by one, clients follow ASK and MOVED redirects, and the hit ratio dips only for the moved keys.
  • "Can you use Redis for the lock that prevents double booking?" Use it to reduce contention, but make the booking itself a conditional write in the database, so a lost lock cannot oversell a seat.
  • "One celebrity's profile is read a million times a second." Add an L1 with a short TTL, key copies across nodes, or replica reads, and say which one you choose and why.
  • "How do you keep two regions consistent?" Each region invalidates from its own database's replication stream, so deletes never arrive before the data, and recent writers read from the primary region for a few seconds.
Deep Dive: Why Redis is fast on one thread, and connection scalingShow

Single-threaded speed. Redis keeps all data in memory, uses efficient data structures, and processes commands on one thread with an event loop (epoll), so there are no locks or context switches. A simple command takes microseconds; the bottleneck is usually network I/O, which Redis 6+ can spread across I/O threads. To use many cores, run several Redis instances per host or use Cluster.

Connections. Thousands of app instances each opening connections to every cache node creates connection storms. Proxies (mcrouter, Envoy, Twemproxy) multiplex connections, and pipelining batches many commands into one round trip, raising throughput several-fold.

Latency tail. A single slow command (a KEYS *, a large HGETALL, a big-key DEL) blocks everything behind it on that node. Disable dangerous commands in production, use SCAN-style iteration, and alert on slow-log entries.

Deep Dive: Load balance on a hash ring, bounded loads, and how Redis Cluster agrees on failureShow

How uneven is a plain ring? Place N servers at random points on a ring, one point each. The arcs between points behave like the gaps between N random points, and the largest gap is about ln N / N of the ring, against an average of 1 / N. With 100 servers, ln 100 is about 4.6, so the unluckiest server owns about 4.6 times the average share of keys. Virtual nodes fix this by averaging. A server with k points owns the sum of k independent arcs, and the relative spread of that sum shrinks like 1 / sqrt(k). With 100 points per server the typical deviation is about 10%, and with 1,000 points about 3%. The cost is a larger lookup table, which is cheap: 100 servers x 160 points is 16,000 entries, searched by binary search in about 14 comparisons.

Bounded loads. Even perfect key balance does not mean balanced load, because keys differ in popularity. Mirrokni, Thorup and Zadimoghaddam ("Consistent Hashing with Bounded Loads", SODA 2018) cap each server at (1 + epsilon) times the average load. A request whose home server is full walks clockwise to the next server with spare capacity. They show that the number of keys moved when servers join or leave stays small, about 1 / epsilon^2 times the minimum for small epsilon. Vimeo described adopting this approach in HAProxy for its video-serving caches, where it smoothed out hot spots. The trade-off is that overflow requests go to a server that is not their home, so the overflow server's cache may miss for them.

Why Redis Cluster uses 16,384 slots. Every heartbeat carries a bitmap of the slots the sender owns. With 16,384 slots the bitmap is 2 KB, while 65,536 slots would need 8 KB in every heartbeat, multiplied by every pair of nodes gossiping. Since a cluster is not expected to exceed about 1,000 primaries, 16,384 slots still gives each primary at least 16 slots to move around.

From suspicion to failure. When a node gets no reply from a peer for longer than cluster-node-timeout, it marks the peer PFAIL, a local suspicion. Suspicions spread through gossip. When a node collects PFAIL reports about the same primary from a majority of primaries within a time window, it marks the primary FAIL and broadcasts that. A replica of the failed primary then waits a short delay ranked by how up to date its copy is, so the freshest replica usually goes first. It asks the primaries for votes in a new epoch, and wins with a majority. Each primary votes once per epoch, so two replicas cannot both win. If two configurations ever disagree about a slot, the one with the higher configuration epoch wins.

What the design does not guarantee. A minority partition holding an old primary keeps accepting writes until cluster-node-timeout passes, and those writes are lost when it rejoins as a replica. Shortening the timeout shrinks that window but causes failovers on brief network blips. This is why Redis Cluster offers availability and speed, not linearizable consistency, and why correctness-critical state belongs in a consensus-based store.

Key Takeaways#

  • A distributed cache shares one logical cache across nodes for capacity, throughput and a consistent view.
  • Shard with client libraries, proxies or Redis Cluster hash slots; use consistent hashing or slots, never mod N.
  • Redis offers data structures, replication and persistence; Memcached is a simple, multi-threaded cache.
  • Replicate shards across zones; at scale, invalidate from the database commit log and use leases, as Meta does.
  • Combine an in-process L1 with a distributed L2, and size for both the hot set and peak throughput.
  • Shard with slots or consistent hashing, keep nodes moderate in size, and let throughput as well as memory set the node count.
  • Redis replication is asynchronous: failover can lose acknowledged writes, so use the cache for efficiency and the database for correctness.
  • Invalidate from each region's commit log so deletes follow durable data, and use leases against stale sets and stampedes.
  • Treat hot keys explicitly with L1, key copies or replica reads, and size for bandwidth and connections, not only RAM.