Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 4 of 6 · Worked example · 25 min · revision 3

Hit-ratio math and sizing a cache tier

Model cache hit and miss ratios, calculate backend database load amplification, and size working sets using Pareto distributions and memory budgeting.

Contentsand lesson path

What you will learn

  • Size a cache from working set and target hit ratio, and estimate the resulting load on the backing store.

01. Why miss ratio, not hit ratio, drives database load

Teams like to report a cache's hit ratio, H, as its success metric. What decides whether the database survives peak traffic, though, is the miss ratio, M = 1 − H, because the database only sees the requests that miss.

That makes small drops in hit ratio expensive. Take an API serving a steady 60,000 read requests per second:

  • 98% hit ratio. M = 0.02, so the database receives 60,000 × 0.02 = 1,200 reads per second.
  • 94% hit ratio. A release with badly built cache keys drops H by four percentage points. M triples from 0.02 to 0.06, and the database receives 60,000 × 0.06 = 3,600 reads per second: three times the load, an increase of 200%, the moment the hit ratio drops.
  • 90% hit ratio. M = 0.10, and the database receives 6,000 reads per second, five times the baseline.

A database provisioned for 2,000 queries per second is therefore overloaded by a four-point drop in hit ratio, although client traffic has not changed at all. Size the database for the miss rate you can reach at peak, not for the average hit rate. If database CPU sits at 75% at a 96% hit ratio, a marketing campaign that sends traffic to rarely cached items and drops the hit ratio to 90% multiplies the misses by 2.5, more than the remaining CPU headroom; queries queue, connection pools run dry, and the API starts returning gateway timeouts.

02. Sizing the working set and its memory

A common mistake is sizing the cache to hold the whole dataset. Read traffic is usually skewed: a small share of the items, the hot ones, receives most of the requests, a pattern often modelled with Pareto or Zipf distributions.

The working set. The working set is the collection of keys that users actually read within a given window, such as 24 hours. How skewed it is varies by product, so measure it from your access logs: count reads per key and find the smallest set of keys that covers, say, 90% of reads. In many catalogues that set is a minority of the items. Caching the cold remainder costs memory for little gain in hit ratio.

Sizing formula and Redis memory overhead. Redis needs more memory than the raw bytes of keys and values: every key has a dictionary entry, an object header and string headers, and the allocator rounds each allocation up to a size class. Measure it on your version rather than guessing. On Redis 8.10.3 with jemalloc, MEMORY USAGE reported 1,573 bytes for one key of 18 bytes holding a 1,500-byte value, and loading 100,000 such keys grew used_memory by about 1,591 bytes per key, roughly 75 bytes more than the key and value themselves. A 50-byte value under a 13-byte key took about 103 bytes per key.

The sizing formula is: working-set RAM = hot keys × (key size + value size + per-key overhead) × (1 + headroom).

A worked example for an e-commerce platform with 12,000,000 products:

  • Hot keys. Suppose the access logs show that 20% of the products receive about 88% of the reads: 12,000,000 × 0.20 = 2,400,000 hot keys.
  • Payload. The average product JSON is 1,500 bytes, and a key such as prod:item:12345678 is 18 bytes.
  • Overhead. About 75 bytes per key, as measured above.
  • Raw memory. 2,400,000 × (1,500 + 18 + 75) = 2,400,000 × 1,593 bytes ≈ 3.82 GB, which is 3.56 GiB.
  • Headroom. Add 30% for replication buffers, copy-on-write during persistence (RDB snapshots and AOF rewrites) and fragmentation: 3.56 GiB × 1.3 ≈ 4.63 GiB.

The script below does the same arithmetic.

Python · sizing.py
def calculate_db_load(total_rps: float, hit_ratio: float) -> tuple[float, float]:
    miss_ratio = 1.0 - hit_ratio
    db_rps = total_rps * miss_ratio
    return miss_ratio, db_rps


def estimate_redis_ram_gib(
    total_entities: int,
    hot_ratio: float,
    val_bytes: int,
    key_bytes: int,
    overhead_bytes: int = 75,  # measured: used_memory growth per key, Redis 8.10
    safety_margin: float = 0.30,
) -> dict:
    hot_keys = int(total_entities * hot_ratio)
    bytes_per_key = key_bytes + val_bytes + overhead_bytes
    raw_ram_bytes = hot_keys * bytes_per_key
    total_ram_gib = (raw_ram_bytes / (1024**3)) * (1.0 + safety_margin)
    return {
        "hot_keys": hot_keys,
        "bytes_per_key": bytes_per_key,
        "raw_gib": round(raw_ram_bytes / (1024**3), 2),
        "recommended_ram_gib": round(total_ram_gib, 2),
    }


# 1. Load amplification when the hit ratio drops 4 points
baseline_miss, baseline_db = calculate_db_load(60_000, 0.98)
degraded_miss, degraded_db = calculate_db_load(60_000, 0.94)
amplification = (degraded_db / baseline_db - 1.0) * 100
msg = f"DB load: {baseline_db:.0f}/s -> {degraded_db:.0f}/s (+{amplification:.0f}%)"
print(msg)

# 2. Sizing a 12M-product catalogue whose hot 20% is cached
sizing = estimate_redis_ram_gib(
    total_entities=12_000_000,
    hot_ratio=0.20,
    val_bytes=1500,
    key_bytes=18,  # len("prod:item:12345678")
)
print(f"{sizing['hot_keys']:,} hot keys x {sizing['bytes_per_key']} bytes"
      f" = {sizing['raw_gib']} GiB raw")
print(f"Recommended cache size: {sizing['recommended_ram_gib']} GiB")
Terminal
python sizing.py
Expected output
DB load: 1200/s -> 3600/s (+200%)
2,400,000 hot keys x 1593 bytes = 3.56 GiB raw
Recommended cache size: 4.63 GiB

03. Check your understanding

Practice check · 3 questions

Hit ratio mathematics and cache sizing check

Three scenario questions on what hit ratio hides, scan pollution, and replacing a cache cluster.

Q1. A cache reports a steady 95% hit ratio by request count, yet the database is still overloaded. The 5% of misses turn out to be large report queries. Which measurement would have shown the problem?
Q2. A nightly export reads every product once through the cache-aside path. Redis runs with `maxmemory-policy allkeys-lru`, and the next morning the hit ratio is poor for an hour. Why?
Q3. You must move traffic from an old cache cluster to a new, empty one without overloading the database. Which plan is safest?
Practice only: not graded, not saved, not evidence.

04. Apply it

Apply the arithmetic to your own cache tier:

  • Monitor miss ratio and database queries per second, not only hit ratio. Alert on spikes in miss ratio and in absolute database reads. On a busy endpoint, a drop from 97% to 94% doubles the misses, and with them the database load, while a hit-ratio dashboard still looks healthy.
  • Size for the working set, not the table. Measure the read distribution, find the working set, and set Redis maxmemory to fit it plus the headroom from the formula. Use an eviction policy such as allkeys-lru or allkeys-lfu, so dormant keys age out by themselves.
  • Measure the per-key overhead. Load a sample of real keys into a test Redis and compare used_memory before and after, or check single keys with MEMORY USAGE, before you commit to a capacity budget.
  • Prepare for cold restarts. Plan how a cache that starts empty at peak time is filled: pre-warming scripts, single-flight coalescing of misses, and moving traffic to a new cluster in steps.

The next lesson defends against cache stampedes and hot keys with single-flight coalescing, locks in Redis and jittered TTLs.

05. Review prompt

Show with numbers why a 4 percentage-point drop in cache hit ratio can triple the read volume arriving at the database. Explain the working set concept and calculate the required cache memory for a catalogue of 4 million items where the hottest 15% receive most of the reads, with a 900-byte payload and a 20-byte key per item and 20% headroom, and say how you would measure the per-key overhead. Describe what happens when a high-throughput cache restarts cold during peak traffic, and outline three engineering strategies to protect the database.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check