Sub topic 10
Sizing a cache and working set in memory
This chapter assumes you can convert daily active users into queries per second, estimate storage from record size and retention, and recall the rough latency gap between memory and disk. Here you will use those numbers to decide how much memory a cache needs.
Why size a cache at all
A cache keeps copies of frequently read data in fast memory so that most reads skip the slower database. Memory costs more per gigabyte than disk or SSD, so you want the smallest cache that still gives most of the benefit. Too small, and the database takes most of the traffic anyway. Too large, and you pay for memory that holds data nobody reads.
Sizing a cache means answering two questions:
- How much data is read often enough to deserve a place in memory?
- How much memory does that data take, including the overhead of the cache itself?
The first answer is the working set. The second is the cache size.
The working set
The working set is the part of your data that is actually read during a given time window. Most systems read a small fraction of what they store. Last year's records exist, but few users open them today.
This skew is why caching works. A common planning rule is the 80/20 rule: about 20% of the data receives about 80% of the reads. It is a rough heuristic, not a law. Measure it on real traffic when you can. For an estimate, state it as an assumption.
The estimate has three steps:
- Compute the daily read volume in objects or bytes.
- Choose the fraction of data you want in cache, often 20% as a starting assumption.
- Multiply by object size, then add overhead.
Two ways to count
There are two common ways to get the working set, and they can give different answers.
- From stored data. Take total storage and multiply by the hot fraction. This is simple, but it can be far too large for a dataset that has grown over many years.
- From daily reads. Take the number of distinct objects read per day and multiply by object size. This tracks what users actually touch.
Prefer daily reads when you have traffic numbers. Use the stored-data method only as an upper bound.
A worked sizing example
Suppose a service has 10 million daily active users, and each user makes 10 read requests per day. Each response is a 5 KB object (assume decimal units for simplicity, so 5 KB is 5,000 bytes).
Daily reads:
- 10,000,000 users × 10 reads = 100,000,000 reads per day.
If the cache holds the hottest 20% of those reads, the cache serves the most popular requests. A direct way to size it is to cache 20% of the daily read volume:
- 100,000,000 × 0.2 = 20,000,000 objects.
- 20,000,000 × 5,000 bytes = 100,000,000,000 bytes, which is 100 GB.
The script below performs the same calculation and adds overhead.
daily_reads = 10_000_000 * 10
hot_fraction = 0.2
object_bytes = 5_000
overhead_factor = 1.5
hot_objects = daily_reads * hot_fraction
raw_bytes = hot_objects * object_bytes
total_bytes = raw_bytes * overhead_factor
print(round(hot_objects)) # 20000000
print(raw_bytes / 1e9) # 100.0 (GB)
print(total_bytes / 1e9) # 150.0 (GB)The overhead_factor of 1.5 is an assumption. Real caches store keys, pointers, expiry metadata, and allocator padding next to each value. Small values suffer most, because overhead is a larger share of a small object. For values of a few hundred bytes, overhead can approach or exceed the value size. For multi-kilobyte values it is usually a modest fraction. State the factor you picked so a reviewer can change it.
Distinct objects versus total reads
The example above treated every read as a different object. That overstates the cache size when many reads hit the same object. If 100 million reads touch only 30 million distinct objects, the working set is based on the 30 million, not the 100 million.
In practice, ask: how many distinct objects are read per day? For some systems you can derive it. A URL shortener, for example, has far fewer popular links than total clicks. For others you must assume a ratio and say so.
| Quantity | Meaning | Effect on cache size |
|---|---|---|
| Total reads per day | Every request, repeats included | Upper bound on objects needed |
| Distinct objects read per day | Unique keys touched | Closer to the real working set |
| Hot fraction | Share of distinct objects you cache | Scales the size directly |
| Overhead factor | Metadata and allocator waste | Multiplies the raw size |
Hit ratio and what it buys you
The hit ratio is the fraction of reads served from the cache. A higher hit ratio means fewer database reads. The database load is:
- database QPS = total read QPS × (1 − hit ratio).
With an average of 1,157 read QPS and a peak of about 2,315 QPS (the figures from the earlier traffic chapter), a 90% hit ratio leaves about 232 QPS reaching the database at peak. A 99% hit ratio leaves about 23. Going from 90% to 99% cuts database load by a factor of ten, so each extra point of hit ratio is worth more as it nears 100%. It also tends to cost more memory, because the last few percent of reads are spread across many rarely used objects.
The hit ratio also changes average latency. If a memory hit takes about 1 ms including the network hop and a database read takes about 10 ms, then a 90% hit ratio gives an average of 0.9 × 1 + 0.1 × 10 = 1.9 ms. A 50% hit ratio gives 5.5 ms. These latency figures are illustrative assumptions. Replace them with measurements from your own system.
def avg_latency_ms(hit_ratio, cache_ms=1.0, db_ms=10.0):
return hit_ratio * cache_ms + (1 - hit_ratio) * db_ms
def db_qps(read_qps, hit_ratio):
return read_qps * (1 - hit_ratio)
for hit in (0.5, 0.9, 0.99):
print(hit, round(avg_latency_ms(hit), 2), round(db_qps(2315, hit)))
# 0.5 5.5 1158
# 0.9 1.9 232
# 0.99 1.09 23Fitting the cache onto machines
Once you have a total, check whether it fits on one machine. A single cache server might have 64 GB of memory, but you cannot use all of it for data. The operating system and the cache process need room, and you want slack so that evictions are not constant. Assume you can use about 70 to 75% of the memory for data.
At 64 GB with 70% usable, one node holds about 45 GB of data. The 150 GB estimate then needs 150 / 45, which is 3.3, so round up to 4 nodes. In a real deployment you would often add a replica of each node for failover, which doubles the memory bill. Say whether your number includes replicas.
A single node also has a throughput limit. Many in-memory stores handle tens of thousands of simple reads per second per node. Check that your peak read QPS divided by the node count stays below that figure. In this example the peak is a few thousand QPS, so memory capacity decides the node count, not throughput. For a system with very high QPS and a small working set, the opposite can be true.
placeholderThe diagram below shows the order of the calculation.
Edge cases and common mistakes
- Using stored data instead of daily reads. Five years of records at 91 TB do not belong in memory. The hot slice is a small fraction of that, and it comes from recent reads.
- Forgetting overhead. A cache of 20 million 100-byte values is not 2 GB. Keys and metadata can easily double or triple it.
- Ignoring cache warm-up. A new or restarted cache is empty, so the hit ratio starts near zero and the database takes the full load. Plan the database for that moment, or warm the cache before sending traffic.
- Assuming a uniform read pattern. If reads are spread evenly across all objects, a small cache gives a low hit ratio. The 80/20 skew is what makes a small cache effective. Check that your data has it.
- Mixing units. Keep decimal (KB, GB) or binary (KiB, GiB) units consistent. The difference is about 7% at the gigabyte scale, which rarely changes a design but can confuse a review.
- Caching writes-heavy data. Objects that change often are invalidated often, which lowers the hit ratio and adds work. Cache data with a high read-to-write ratio.
Summary of the method
- Start from daily reads and estimate distinct objects.
- Pick a hot fraction and state it.
- Multiply by object size and an overhead factor.
- Check the implied hit ratio and database load.
- Divide by usable memory per node and round up.
- Add replicas if the design needs them.
Exercise
A service has 50 million reads per day across 20 million distinct objects. Each object is 2 KB. You cache the hottest 10% of distinct objects, and the overhead factor is 1.5. Each cache node has 32 GB of memory with 75% usable for data. How many nodes do you need, without replicas?
Show answer
Hot objects = 20,000,000 × 0.1 = 2,000,000. Raw size = 2,000,000 × 2,000 bytes = 4 GB. With overhead, 4 × 1.5 = 6 GB. Usable memory per node = 32 × 0.75 = 24 GB. 6 / 24 = 0.25, so one node holds the data. In practice you would still run at least two nodes for failover, but memory alone needs only one.
Exercise
Peak read traffic is 4,000 QPS. Compare the database load at a 95% hit ratio and a 99% hit ratio. By what factor does it drop?
Show answer
At 95%, database QPS = 4,000 × 0.05 = 200. At 99%, it is 4,000 × 0.01 = 40. The load drops by a factor of 5.