A team sizes a cache by multiplying 10 million objects by 2 KB each, provisions 20 GB of memory, and watches the hit rate settle at 71% instead of the 95% they expected. The arithmetic was correct. The model was wrong. The real footprint included per-entry overhead, allocator fragmentation, replicas, and failover headroom, and the 10 million objects were not the ones the traffic actually requested.
Cache capacity planning goes wrong in a predictable way: the problem looks like multiplication when it is really a question about access patterns, failure behavior, and how state is spread across nodes. A cache does not hold "the data." It holds a moving subset of the data, chosen by an eviction policy, under a traffic distribution that changes over time, on hardware that will occasionally disappear.
This article covers how to reason about that. It shows how to estimate working set size, predict cache hit rate from access skew, account for the real memory cost of an object, model eviction pressure, and include replication and failure headroom. It then uses those estimates to decide between a local cache and a distributed one.
The Core Problem: A Cache Is a Bet on Locality
Every cache rests on one assumption: recently or frequently accessed data will be accessed again soon, and the set of such data is much smaller than the full dataset. If that holds, a small amount of fast memory absorbs most reads. If it doesn't, the cache is an expensive layer of indirection that adds a network hop and a consistency problem.
Three quantities matter more than total dataset size:
- Working set size: the number of distinct objects accessed within the window over which reuse happens (often the TTL, or the typical gap between repeat accesses).
- Access skew: how unevenly requests fall across that working set.
- Effective bytes per entry: what one cached object costs in memory, not what its payload costs on disk.
The reason this is harder in a distributed system is that the cache sits between components that run at very different speeds. Consider an API service that reads product data from a cache and falls back to a relational database on a miss. In the healthy state, the database serves only the miss traffic. The database is sized for that, not for total traffic, and often nobody writes that dependency down.
Now suppose the cache is slightly too small. The causal chain looks like this:
working set exceeds cache capacity
→ eviction of objects that will be reused
→ hit rate drops from 95% to 90%
→ database read load doubles (5% → 10% of traffic)
→ database latency rises
→ API request latency rises, connection pools fill
→ client timeouts and retries
→ more misses, more database load
The key detail is in the third and fourth lines. The database sees the miss rate, not the hit rate. Going from a 95% hit rate to 90% looks like a 5% regression on a dashboard. For the backing store it is a 2x increase in load. Going from 99% to 98% is also a 2x increase. Capacity decisions that look marginal on the hit-rate axis are multiplicative on the dependency.
The problem compounds as the system grows. When the dataset grows 10x, the working set rarely grows exactly 10x. It might grow less (new data is mostly cold) or more (a new feature adds a scan-like access pattern). Capacity planning that tracks dataset size instead of working-set size will be wrong in both directions.
Distributed Systems Deep Dive: Estimating the Four Numbers That Matter
Working Set Size and Reuse Distance
A useful mental model for LRU-style caches is reuse distance: the number of distinct other objects accessed between two accesses to the same object. Under LRU, an access is a hit if and only if its reuse distance is smaller than the cache's capacity in entries. That turns a vague question ("is the cache big enough?") into a measurable one: what is the distribution of reuse distances in real traffic?
You rarely need the full distribution. A practical approximation is to count distinct keys accessed over a window that matches how reuse actually happens:
working_set_entries ≈ distinct keys accessed in window W
steady_state_entries ≈ unique_insert_rate × average_residency_time
The second form is Little's Law applied to cache entries. If 2,000 new keys per second enter the cache and the average entry lives 30 minutes before eviction or expiry, the cache holds about 3.6 million entries in steady state. If capacity is lower than that, the eviction policy shortens residency time until the equation balances. Shorter residency means objects are evicted before their next access, which is the definition of eviction pressure.
This framing also explains scan pollution. A batch job that reads every record once has an infinite reuse distance for each key. Under plain LRU, those one-time reads push out hot entries. The working set did not grow in any useful sense, but the cache behaves as if it did. Admission policies (such as frequency-based filters like TinyLFU) exist to handle this. They decide whether an object deserves a slot before evicting something else to make room.
Access Skew and the Shape of the Hit-Rate Curve
Many real workloads (product catalogs, social content, URL lookups) are roughly Zipf-distributed: the k-th most popular item is requested with frequency proportional to 1/k^s. With s near 1, a cache holding the top k of N items has a hit rate of approximately:
hit_rate(k) ≈ H(k) / H(N) ≈ ln(k) / ln(N)
where H is the harmonic number. This is an idealization with a static popularity ranking and perfect eviction, but its shape is instructive. For N = 100 million items:
| Cached items (k) | Approx. hit rate (s ≈ 1) | Miss rate |
|---|---|---|
| 10,000 | ~50% | ~50% |
| 1,000,000 | ~75% | ~25% |
| 10,000,000 | ~87% | ~13% |
| 50,000,000 | ~96% | ~4% |
Two consequences matter. First, returns diminish logarithmically: each 10x increase in cache size adds roughly the same fixed increment of hit rate. Second, a very small cache captures a surprisingly large share of traffic. The top 10,000 items may be only tens of megabytes yet absorb half of all reads. That observation is the basis for two-tier caching, discussed below.
The exponent matters a great deal. With s = 0.8 the curve is flatter and the same cache size buys a much lower hit rate. With s = 1.2 the curve is steeper. Assuming the exponent is a mistake. Estimate it from a sample of access logs, or better, replay a sample of real keys through a simulated cache at several sizes and read the hit-rate curve directly:
from collections import OrderedDict
def lru_hit_rate(keys, capacity):
cache, hits = OrderedDict(), 0
for k in keys:
if k in cache:
hits += 1
cache.move_to_end(k)
else:
cache[k] = True
if len(cache) > capacity:
cache.popitem(last=False)
return hits / len(keys)
# Replay a sampled access log at several capacities to find the knee
for cap in (10_000, 100_000, 1_000_000, 5_000_000):
print(cap, round(lru_hit_rate(sampled_keys, cap), 3))
A replay like this costs an afternoon and replaces guessing with a measured curve. When sampling keys, sample by key hash (keep all accesses for a subset of keys), not by request. Request sampling breaks reuse distances and makes the cache look worse than it is.
Effective Bytes per Entry
The memory cost of an entry is never just the payload size. A realistic estimate includes:
- Key bytes. Composite keys like
tenant:4821:product:99812:v3add up across tens of millions of entries. - Per-entry metadata. Hash table slots, pointers, expiry timestamps, and eviction bookkeeping (LRU list pointers or frequency counters). In-memory stores like Redis typically add on the order of tens of bytes per key beyond the key and value, and the exact amount depends on version and encoding. Measure it on your workload.
- Serialization overhead. JSON field names repeated in every object can double the payload compared with a compact binary format.
- Allocator fragmentation. Size-class allocators such as jemalloc round allocations up and fragment over time as objects of different sizes churn. Ratios between 1.1 and 1.5 of used memory to logical data are common, and churn-heavy workloads can go higher.
- Runtime overhead for in-process caches. On managed runtimes, every object carries headers and references, and a large heap increases garbage collector work. A 2 KB payload stored as a deserialized object graph can cost several times that.
The practical rule is to measure bytes per entry empirically. Load a representative sample (say one million real objects) into the actual cache technology and divide the observed memory use by the entry count. That number includes everything, which is what you want.
Replication and Failure Headroom
A distributed cache usually replicates for availability, which multiplies memory by the replication factor. Less obvious is the failure headroom. If a cluster of N shards loses one node and the cluster redistributes that node's keyspace, the remaining nodes must absorb it. To keep the hit rate stable through a single-node loss, each node needs capacity for roughly 1/(N−1) of the working set instead of 1/N. For a four-node cluster, that is 33% more memory per node.
Persistence adds another factor. Snapshotting by forking the process relies on copy-on-write. Under heavy writes during a snapshot, a large share of pages are copied, and peak memory can approach twice the dataset in the worst case. Systems that ignore this get killed by the operating system's out-of-memory handler during a backup, which is a capacity bug that looks like a stability bug.
Enjoying this so far?
Join thousands of engineers receiving practical engineering, Cloud, Distributed Systems, Infrastructure and AI engineering insights.
No spam. Unsubscribe anytime.
Architecture: A Worked Capacity Model
Consider a hypothetical product-detail service for an e-commerce platform. The figures are illustrative.
- 50 million products, average serialized payload 2 KB (about 100 GB total)
- 40,000 reads per second at peak
- Access log replay shows about 5 million distinct products requested per hour, and a 1-hour TTL keeps freshness acceptable
- Replay at 5 million entries gives a 94% hit rate. At 1 million entries, 78%
Client
|
v
Load Balancer
|
v
API Service (20 instances)
| in-process L1: top ~20k products, short TTL
v
Distributed Cache L2 (4 shards, 1 replica each)
| on miss
v
Primary Database (read replicas)
^
| change events (invalidate L2, broadcast L1 eviction)
Catalog Write Path
Sizing L2:
bytes per entry (measured) ≈ 2,300 B (payload + key + metadata)
entries 5,000,000
logical footprint ≈ 11.5 GB
× fragmentation 1.3 ≈ 15 GB
× replication factor 2 ≈ 30 GB
per node, 4 shards, survive 1 loss:
15 GB / 3 shards ≈ 5 GB primary data per node
+ replica data ≈ 10 GB per node
+ fork/snapshot headroom (if persistence enabled)
→ provision roughly 14 to 16 GB per node
The 100 GB dataset never enters the calculation directly. The working set does.
State ownership and consistency boundaries. The database owns truth. L2 is a shared, derived copy with one representation per key, so invalidation is a single delete. L1 is a per-instance copy, which means 20 independent representations of each hot key. Invalidation must reach every instance, usually through a broadcast channel, and some instances will receive it late or not at all. A short L1 TTL (seconds, not minutes) bounds the staleness when broadcasts are lost.
Why L1 exists at all. Under the skew observed in replay, the top 20,000 products might cover close to half of reads, for about 50 MB per instance. That cuts L2 network round trips roughly in half and, more importantly, protects L2 from hot keys. A single viral product requested 10,000 times per second would otherwise land on one L2 shard. At 2 KB per response that is only 20 MB/s, which is fine. At a 500 KB payload it becomes 5 GB/s on one node's network interface, which is not. Capacity is a bandwidth question as well as a storage question.
Recovery behavior. When an L2 node fails, its keyspace is cold on whichever node takes over. The database sees a burst of misses for that slice until it re-warms. The architecture needs request coalescing (one database fetch per missing key, with concurrent requesters waiting on it) so that a cold slice produces one read per key, not one read per request.
Tradeoffs: Local Cache vs Distributed Cache
The choice between a distributed cache and a local cache is a capacity question before it is a technology question. A local cache multiplies memory by the number of instances. A distributed cache adds a network hop and a shared failure domain.
| Approach | When it makes sense | What it makes harder | Behavior at scale |
|---|---|---|---|
| No cache | Database comfortably handles peak read load; data changes constantly | Nothing structurally; latency is the database's | Scales only as far as the database scales |
| Local in-process cache | Working set is small (fits in a fraction of each instance's memory); staleness of seconds is acceptable | Invalidation across N copies; GC pressure; cold caches on every deploy | Memory cost grows linearly with instance count; hit rate is unaffected by fleet size if traffic is balanced |
| Distributed cache | Working set is large; one shared representation simplifies invalidation | Network latency on every hit; hot-key concentration; shard failure is a correlated miss event | Memory grows with working set, not fleet size; scales by adding shards, which triggers rebalancing |
| Two-tier (L1 + L2) | High skew: a tiny hot set carries much of the traffic | Two staleness windows; harder to reason about which tier served stale data | Best memory efficiency under skew; L1 absorbs hot keys before they reach a single L2 shard |
A quick feasibility test for local caching:
local_cache_total = working_set_bytes × instance_count
If a 50 MB hot set runs on 20 instances, the 1 GB total is trivial. If a 15 GB working set runs on 20 instances, the 300 GB total is both wasteful and, on most runtimes, a garbage-collection problem. Note that local hit rates also fall as the fleet grows when items are only moderately popular. Each instance sees 1/N of the traffic, so the per-instance reuse distance for a medium-popularity key grows with N. A key accessed twice a minute across the fleet may be accessed once every ten minutes on any one instance and expire between uses.
The deeper tradeoff is about where staleness and failure are allowed to live. A local cache spreads both across many small independent copies. A distributed cache concentrates them into fewer, larger, shared failure domains.
Failure Modes and What Happens at Scale
At 10 requests per second, most caches are premature. A properly indexed database query at that rate is rarely the bottleneck, and a cache adds an invalidation problem for no measurable benefit.
At 1,000 requests per second, a modest cache is usually justified for expensive reads. A single cache node or a local cache often suffices. The main risk is staleness: invalidation logic that misses an update path serves wrong data indefinitely if TTLs are long.
At 100,000 requests per second, the cache is load-bearing. With a 90% hit rate, the database serves 10,000 reads per second. Lose one of four shards and 25% of the keyspace goes cold:
database load = 10,000 (normal misses) + 0.25 × 90,000 (former hits)
= 32,500 reads/second
That is a 3.25x spike from a single node failure. If the database cannot absorb it, the failure cascades: database latency rises, API timeouts trigger retries, retries add load, and the cache cannot re-warm because the fetches that would warm it are timing out. This is a thundering herd that capacity planning must account for, either by provisioning the database for the post-failure miss rate, by shedding load, or by coalescing misses.
Other scale-dependent failure modes:
- Eviction storms: a traffic shift (a sale, a new feature) expands the working set past capacity, residency time collapses, and the hit rate falls off a cliff rather than degrading gradually.
- Synchronized expiry: objects written at the same moment with the same TTL expire together, producing a periodic miss spike. Adding random jitter to TTLs spreads expirations out.
- Rebalancing churn: adding shards for capacity moves keys, temporarily lowering the hit rate. Consistent hashing limits the moved fraction to roughly 1/N, but that fraction still goes cold.
- Stale reads after reordering: a delete-then-fill race (invalidation arrives, then a slow reader repopulates with the old value) leaves stale data until TTL expiry. Versioned writes or short TTLs bound the damage.
Engineering Principles
-
Size the cache from the working set, not the dataset. Total data volume is an upper bound, rarely the right number. Distinct keys accessed within the reuse window is the input that matters.
-
The dependency sees the miss rate. Express cache changes in miss-rate terms. A drop from 98% to 96% hit rate doubles backing-store load, and the database should be sized for that.
-
Measure bytes per entry; never compute them from payload size. Metadata, serialization, and fragmentation routinely add 30% to 100% or more. One empirical load test replaces a page of assumptions.
-
Capacity must survive the failure you planned for. Replication factor and N−1 headroom belong in the base estimate, not in a later revision.
-
Hit rate grows logarithmically under skew. A small hot tier captures a large share of traffic, and the last few percentage points of hit rate cost far more memory than the first fifty.
-
Local caches multiply memory by fleet size and staleness by copy count. They win when the hot set is small and loose freshness is acceptable.
-
Caching moves the consistency problem; it does not eliminate it. Every cached copy is a second representation of state with its own update path and its own way of going stale.
Final Thoughts
Cache capacity planning is a modeling exercise about locality and failure, not a memory-purchasing exercise. The questions that decide the outcome are: which objects are actually reused, over what window, at what skew, at what true cost per entry, and what happens to the backing store when a slice of that memory disappears.
Engineers who reason this way stop asking "how big should the cache be?" and start asking "what hit rate does the dependency require, what working set produces it, and what does the system do when that assumption breaks?" That shift moves the discussion from configuration to architecture. The cache stops being a performance add-on and becomes a component with an explicit contract: a load reduction that other components depend on, and that therefore must be provisioned, monitored, and designed to degrade predictably.
These are the kinds of problems at the center of modern backend systems, and the focus of the engineering work at PulseSoft: understanding where state lives, how much of it the fast path can hold, and what happens when the assumptions between components stop being true.
Key Takeaways
- Working set size, measured as distinct keys accessed within the reuse window, determines cache capacity; total dataset size is only an upper bound.
- Under Zipf-like access, cache hit rate grows roughly with the logarithm of cache size, so a small hot tier can absorb a large share of reads while the final percentage points require disproportionate memory.
- Backing stores experience the miss rate, so a small hit-rate regression (95% to 90%) can double database load and must be planned for as a load event.
- The real memory cost of an entry includes keys, metadata, serialization, allocator fragmentation, and runtime overhead, and should be measured by loading representative data, not calculated from payload size.
- Replication, N−1 failover headroom, and snapshot copy-on-write peaks can more than double the provisioned memory relative to the logical working set.
- Local caches multiply memory and invalidation cost by instance count; distributed caches share one representation but concentrate hot keys and turn node failures into correlated miss spikes.
- A cache shard failure at high traffic can multiply database load several times over, so miss coalescing, TTL jitter, and post-failure database capacity are part of cache design, not afterthoughts.
Get insights like this in your inbox
Join thousands of engineers receiving practical engineering, Cloud, Distributed Systems, Infrastructure and AI engineering insights.
No spam. Unsubscribe anytime.