← Math
Math

Cache hit rate and break-even cost

Does a 95% hit rate save CPU when every bid purges seven pages?

Compare saved origin work with lookup and invalidation costs in one CPU budget.

Outcome

Write the cached cost as lookups, misses and purges, find the break-even hit rate, and decide how many keys a write may purge before the cache costs CPU.

Terminology (6)Terms used in this lesson

Term on the front, definition on the back. Paste with tabs between fields and a new line between cards, or import the download in Anki as Basic.

Hit rate
Hits divided by eligible reads: the reads that could have been served from the cache.
CPU-µs
Microseconds of CPU time spent on one operation; per second, it is the CPU load the work adds.
Lookup cost
What checking the cache costs, paid on every read whether it hits or misses.
Invalidation
Removing cached entries after a write so readers do not see stale data; each purged key costs work.
Fan-out
The number of cached keys one write has to purge.
Break-even hit rate
The hit rate at which the cache saves exactly as much as it costs; above it the cache pays.

Why this matters

Hit rate is the number every cache dashboard shows, and it is easy to read as the saving. The saving also depends on what a lookup costs, what a miss costs and how much work each write spends invalidating entries. Writing those down in one unit turns "is this cache worth it" into a comparison you can check.

This lesson assumes rates per second and solving a linear equation.

What makes a cache pay

The hit rate is the fraction of eligible reads answered from the cache. Every read still pays for a lookup, a miss also pays for origin work, and writes may spend CPU invalidating cached entries.

Break-even is the point where that combined cached cost equals the uncached cost. This lesson counts cache and origin CPU on comparable hardware in the same time window. It holds the measured hit count fixed when varying purge cost; a changed invalidation policy needs a fresh measurement before the calculation can justify it.

01A hit rate is not a load reduction

A hit rate is not a load reduction

An online auction caches its item pages for the closing minutes. A staging replay shows 1,900 of 2,000 reads a second hitting the cache, and a teammate reads that as a 95% cut in load. Each of 250 bids a second purges 7 cached keys. Work out whether the cache pays in the busiest minutes.

The budget here sums CPU consumed by cache and origin work, measured on comparable hardware; it does not predict latency or one server’s saturation. Put every cost in CPU-µs: 100 for a cache lookup and 1,000 for an origin call. Without the cache, 2,000 reads a second cost 2,000,000 µs each second. With it, every read pays the lookup and the 100 misses also call the origin: 200,000 + 100,000 = 300,000. That is an 85% reduction at a 95% hit rate.

In Node.js, process.cpuUsage() reports user and system CPU time in microseconds; measure an isolated batch and subtract a baseline, since concurrent process work also counts. It does not include a remote origin’s CPU.

02Invalidation is part of the cost

Invalidation is part of the cost

Predict the two lines this program prints.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
const [reads, hits] = [2000, 1900]; // item-page reads per second in the closing minutes
const [lookup, miss, purge] = [100, 1000, 1000]; // CPU-µs per operation
const [bids, keysPerBid] = [250, 7];

const uncached = reads * miss;
const cached = reads * lookup + (reads - hits) * miss + bids * keysPerBid * purge;

console.log(uncached, cached); // CPU-µs per second
console.log(uncached - cached); // the saving
CPU-µs per second in the closing minutes
PartFormulaCPU-µs/s
Lookups2,000 × 100200,000
Misses100 × 1,000100,000
Purges250 × 7 × 1,0001,750,000
Cached total2,050,000
Uncached2,000 × 1,0002,000,000
What does the cache save in the closing minutes?

03The break-even hit rate

The break-even hit rate

Lookups and purges cost the same whatever the hit rate. Each hit saves one origin call. With R,W,k and per-operation costs held fixed, cachedcost=Rℓ+(R−H)m+Wkp and uncachedcost=Rm. Subtracting gives saving=Hm−Rℓ−Wkp. SetH=hR and saving=0 to derive the break-even rate: h* = (R·ℓ + W·k·p) / (R·m) = (200,000 + 1,750,000) / 2,000,000 = 97.5%. The replay’s 95% is below it.

If R·ℓ + W·k·p is larger than R·m, h* is above 100% and no hit rate makes the cache pay. With no eligible reads, or an origin call that costs nothing, h* has no value at all.

04How many keys a write may purge

How many keys a write may purge

Before purges the cache saves 1,900 × 1,000 − 200,000 = 1,700,000 CPU-µs a second. Each key a bid purges takes 250 × 1,000 = 250,000 of that away. The saving stays positive while 250,000·k is less than 1,700,000, so k is at most 6. Purging 6 keys per bid saves 200,000; purging 7 loses 50,000. This holds the replay’s hit count fixed while varying purge cost. A real change in invalidation can change future hit rate, so replay or measure the new policy before using this bound; never skip keys needed for correct data just to lower cost.

If each key cost 170,000 CPU-µs a second instead, how many keys per bid could the cache afford?

05A low hit rate can still pay

A low hit rate can still pay

Two caches against their break-even hit rates
CacheHit rateBreak-evenSaving, CPU-µs/s
Item pages, 7 keys per bid95%97.5%−50,000
Review panel, origin 4,000 µs40%3.75%580,000

The review panel is read 400 times a second with 160 hits. It uses the same100 µs lookup and 1000 µs purge costs. Its origin call costs4,000 µs and 5 writes a second purge 4 keys each. A rule that removes caches under 80% would delete the one that saves 580,000 CPU-µs a second and keep the one that costs CPU. Compare each cache with its own break-even.

06Decide on the closing-window cache

Decide on the closing-window cache

The auction report first needs total CPU, not a hit percentage interpreted as savings. Its second request adds bid invalidation and solves for the hit rate that covers it. The last request holds measured hits fixed and asks for the strict integer key-count boundary; rounding a break-even quotient down can still approve zero saving.

In the frontend A server-side cache that measures its own hit rate in Next.js and SvelteKit Optional

A page’s server code can keep a small cache and count every eligible read and every hit, so the hit rate in your decision is measured rather than assumed. Each purge costs work and can cause a later miss if that key is read. The excerpts keep the purge helper local so the route/load module exports only framework entry points. A separate bid handler must import shared cache state and invalidation from a server-only module; the local helper alone does not wire that handler. These maps and counters are per process; sum counts over the same window rather than averaging process hit rates. A generation check stops an in-flight old fill from repopulating the local cache after a bid purge. The application must deliver invalidations to every serving process; local counters and a local map are not a shared cache or a complete consistency design.

Estimate.tsx
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
// app/api/items/[id]/route.ts: an in-process cache that counts its own hit rate.
const cache = new Map<string, { body: string; expires: number }>();
const stats = { reads: 0, hits: 0 };
const generation = new Map<string, number>();

export async function GET(
  _request: Request,
  { params }: { params: Promise<{ id: string }> }
) {
  const { id } = await params;
  stats.reads += 1; // every eligible read, hit or miss
  const entry = cache.get(id);

  if (entry && entry.expires > Date.now()) {
    stats.hits += 1;

    return new Response(entry.body, { headers: { "x-cache": "hit" } });
  }

  const version = generation.get(id) ?? 0;
  const body = JSON.stringify(await loadItem(id)); // the origin call a hit avoids

  if ((generation.get(id) ?? 0) === version)
    cache.set(id, { body, expires: Date.now() + 5_000 });

  return new Response(body, { headers: { "x-cache": "miss" } });
}

// Local helper for a write handler in this module (not shown).
// A separate bid route must share this cache state and helper from a server-only module.
function purgeItem(id: string) {
  generation.set(id, (generation.get(id) ?? 0) + 1);
  cache.delete(id);
}

declare function loadItem(id: string): Promise<unknown>;

Check this idea later
For this CPU-only model, a cache hits40% of reads. Does that alone justify removing it?
Lookups and purges cost more than every read sent to the origin. What is the break-even hit rate?
Sources

Values above were computed in Node 22 and run in Go 1.27, Rust 1.99 and Apple clang 17. The auction and review panel are a worked model with illustrative costs.

Report a problem in this lesson

For typos, mistakes and things that don’t work. We read every report and fix what’s wrong, but we don’t reply here, so a question won’t get an answer.