Maps to: CMU 15-440/640 Spring 2026, learning outcomes “origins of temporal and spatial locality” and “cache quality metrics” (under “data caching and one-copy semantics”). Readings (optional, course list):
- J. Fotheringham, Dynamic Storage Allocation in the Atlas Computer, Including an Automatic Use of a Backing Store (CACM 4(10), 1961);
- J. S. Liptay, Structural Aspects of the System/360 Model 85, II: The Cache (IBM Systems Journal 7(1), 1968);
- R. C. Daley and J. B. Dennis, Virtual Memory, Processes, and Sharing in MULTICS (CACM 11(5), 1968).
Problem set: PS2 asks about caching in distributed settings; this lecture gives the vocabulary, not the answers. Project: P2 builds a caching proxy (whole-file caching with LRU replacement). Sources: the readings above. Background:
- P. J. Denning, The Working Set Model for Program Behavior (CACM 11(5), 1968);
- R. L. Mattson, J. Gecsei, D. R. Slutz and I. L. Traiger, Evaluation Techniques for Storage Hierarchies (IBM Systems Journal 9(2), 1970);
- A. J. Smith, Cache Memories (ACM Computing Surveys 14(3), 1982);
- M. D. Hill and A. J. Smith, Evaluating Associativity in CPU Caches (IEEE Trans. Computers 38(12), 1989) — the “three C’s”;
- L. Breslau et al., Web Caching and Zipf-like Distributions (INFOCOM 1999);
- H. Che, Y. Tung and Z. Wang, Hierarchical Web Caching Systems: Modeling, Design and Experimental Results (IEEE JSAC 20(7), 2002).
The slides are not public; this is not a transcript. Numbers from papers are labelled as such. Every other number comes from
code/lecture06/, run on the author’s machine (Apple M4 Pro, macOS, Python 3.13 and 3.9). Code:code/lecture06/. Reading time: ~80 minutes, plus ~20 to run the demos.
0. How to read this lecture
0.1 Learning goals
After this lecture you should be able to:
- Define a cache and its vocabulary: hit, miss, hit ratio, miss ratio, miss penalty, block, capacity, associativity.
- Explain where temporal and spatial locality come from — in programs, in files, in people — and recognize access patterns that defeat a cache.
- Trace the idea from the Atlas one-level store (1961) and the Model 85 cache (1968) to distributed caches, and say what stayed the same.
- Compute average access time through one or several cache levels, and explain why the miss ratio is the number to watch.
- Read and compute a miss-ratio curve (MRC) in one pass with stack distances, and use it to size a cache. Estimate it from popularity alone (Che’s approximation).
- Use Denning’s working set to reason about phases and sizing, and classify misses as compulsory, capacity or conflict.
- Choose a cache’s granularity (block size; whole files vs chunks vs blocks) and its placement (client, proxy, server), and name what a cache costs.
0.2 Prerequisites and scope
- Prerequisites: Lecture 2 (latency, bandwidth). Lecture 5 (AFS and NFS caches; its benchmark trace is reused here). 15-213-level memory hierarchy is helpful but not required.
- Scope: why caches work and how to measure them. Keeping cached copies consistent is Lecture 7. Which item to evict (beyond LRU) is Lecture 8. Fetching before the request is Lecture 9.
0.3 Section → code map
| Section | Idea | Demo in code/lecture06/ |
|---|---|---|
| §2 | where locality comes from (programs, files, people, real hardware) | 01_where_locality_comes_from.py |
| §4 | hit ratio, miss ratio, average access time (with a real RPC cache) | 02_amat.py |
| §5 | miss-ratio curves, stack distances, Che’s approximation | 03_miss_ratio_curves.py |
| §6–7 | working sets; compulsory / capacity / conflict misses; cold starts | 04_working_sets_and_misses.py |
| §8–9 | block size; whole files vs chunks; client vs proxy | 05_granularity_and_placement.py |
| all | streams, caches, stack distances, AMAT | cachelab.py (python3 cachelab.py runs its self-test) |
0.4 Notation
- A reference stream is the sequence of items (or byte addresses) requested: .
- = hit ratio (fraction of references found in the cache); = miss ratio.
- = cost of a hit; = extra cost of a miss (the miss penalty).
- = cache capacity (items, blocks or bytes; always stated). A block (line, page, chunk) is the unit moved into the cache on a miss.
- Zipf(): the -th most popular item is requested with probability proportional to .
1. What a cache is
1.1 The intuition
You work at a desk in a library. The book you need is in the stacks, a five-minute walk away. You fetch it and, instead of returning it, keep it on your desk. If you need it again in an hour, it costs nothing. Your desk is small, so when it is full and you fetch another book, one goes back to the stacks.
That is a cache: a small, fast store that keeps copies of a subset of a large, slow store. It is useful exactly when the next request is likely to be for something already on the desk. The decision to keep a copy is a bet on the future made from the past: having needed this recently, I will need it, or something next to it, again soon.
1.2 The vocabulary
- Hit: the requested item is in the cache. Miss: it is not; it must be fetched from the slower store (and is usually inserted, possibly evicting another item).
- Hit ratio and miss ratio , measured over a stream of references.
- Miss penalty: how much longer a miss takes than a hit.
- Block (CPU: line; virtual memory: page; AFS-3: chunk): the unit of transfer and of bookkeeping.
- Capacity: how much the cache holds. Associativity: where in the cache a given block may be placed (anywhere = fully associative; one place = direct-mapped).
- Replacement policy: which item to evict on a miss when the cache is full. This lecture uses LRU (least recently used); Lecture 8 compares others.
- Write policy: whether a write goes through to the slow store at once (write-through) or later (write-back). It is also part of consistency, so it belongs to Lecture 7.
A cache is supposed to be transparent: programs see the same values with or without it, only faster. Keeping that promise when other parties can change the slow store is the hard part, and it is the next lecture.
2. Where locality comes from
A cache works only if references repeat themselves. Two kinds of repetition are worth naming (Denning’s terms):
- Temporal locality: an item used now is likely to be used again soon.
- Spatial locality: an item near one used now is likely to be used soon.
Neither is a law of nature. Both come from how programs are written, how files are used and how people behave. Demo 01 measures each source.
2.1 In programs
Demo 01 Part A runs the address traces of small programs through a 16 KB cache with 64-byte blocks — the size and block of the 1968 Model 85 — and splits the hit ratio into its two sources. With 8-byte blocks, one word per block, no neighbour comes along, so only temporal locality can hit. A cache of a single 64-byte block can hold no history, so only spatial locality can hit.
| program | 16 KB, 64 B blocks | 16 KB, 8 B blocks (temporal only) | one 64 B block (spatial only) |
|---|---|---|---|
| sum a 2 MB array once | 87.5% | 0.0% | 87.5% |
| sum a 4 KB array 64 times | 99.8% | 98.4% | 87.5% |
| sum a 512×512 matrix row by row | 87.5% | 0.0% | 87.5% |
| sum the same matrix column by column | 0.0% | 0.0% | 0.0% |
| walk a linked list of 50,000 scattered nodes | 0.0% | 0.0% | 0.0% |
| 10,000 binary searches in 2 MB | 47.4% | 53.2% | 9.9% |
| random reads in 1 MB | 1.6% | 1.5% | 0.0% |
| random reads in 8 MB (a big hash table) | 0.2% | 0.2% | 0.0% |
Read the table as a list of where locality comes from:
- Sequential code and arrays give spatial locality. Summing an array once has no reuse at all, yet 87.5% of reads hit: each 64-byte block brings 8 doubles, and 7 of them are hits.
- Loops give temporal locality: re-summing a small array hits 98.4% even with one-word blocks.
- Access order matters as much as data layout. The same matrix, summed column by column, hits 0%. A row of 512 doubles is 4 KB, so every read lands in a new block, and the 512 blocks of a column do not fit in 256. Row-major storage plus column-major traversal throws the locality away.
- Pointer-based structures scatter. A linked list whose nodes were allocated over time has none of either kind.
- Some algorithms have structural reuse. Binary search always probes the middle, then the quarters…, so the top of its implicit tree stays cached. It did better with 8-byte blocks (53.2%): its useful words are far apart, so smaller blocks let 16 KB hold more of them. Block size is a trade-off (§8).
- Random access is the enemy. The hit ratio is about cache size / region size: 16 KB / 1 MB = 1.6%, and 16 KB / 8 MB = 0.2%.
Liptay made the same comparison for the real Model 85 in 1968 (paper numbers). Random addresses would have hit its cache less than 1% of the time. Nineteen traces of real programs, operating system included, averaged a 96.8% hit probability. His conclusion, in substance: what makes the cache work is that real programs do not address memory at random.
2.2 In files
File references inherit locality from the way people work: the edit–compile–run cycle, #include, reading a file you just wrote. Demo 01 Part B uses Lecture 5’s traced benchmark, whose 339 read opens touch 178 distinct files:
| LRU file cache | read hit ratio, caching only what is read | … caching what is written too |
|---|---|---|
| 5 files | 8.6% | 4.1% |
| 20 files | 28.3% | 22.1% |
| 100 files | 47.5% | 66.4% |
| unlimited (179 files) | 47.5% | 79.4% |
#includeis temporal locality: Make’s 123 header opens touched only 14 headers.- Caching only what you read leaves a lot on the table. The benchmark copies each file and then reads the copy, which a read-only cache has never seen. So even an unlimited read cache stops at 47.5%. Keeping the files the client itself writes — as AFS keeps the copy it stores at close — raises it to 79.4%. The only remaining misses are the 70 first reads of the original sources.
- A small cache can be hurt by caching more. With room for 5 files, caching writes lowered the read hit ratio from 8.6% to 4.1%: freshly written files evicted files about to be re-read. A cache is only as good as what it chooses to hold.
2.3 In people
Many distributed caches — web proxies, CDNs, DNS resolvers, a course’s file server — see requests from many people, and people are not uniform: a few things are very popular, most are rarely touched. Popularity is often modelled by a Zipf law. Breslau et al. (1999, paper) found web request popularity to be “Zipf-like” with roughly between 0.64 and 0.83 for the proxy traces they studied. Demo 01 Part C shows what that skew means:
| Zipf | top 10 items | top 0.1% | top 1% | top 10% |
|---|---|---|---|---|
| 0.6 | 1.8% | 5.6% | 15.2% | 39.3% |
| 0.8 | 7.8% | 17.9% | 34.0% | 59.5% |
| 1.0 | 24.2% | 42.9% | 61.9% | 81.0% |
| 1.2 | 48.5% | 70.8% | 85.2% | 94.3% |
(Share of all requests that go to the most popular items, out of 100,000.)
With , caching 1% of the items serves 62% of the requests. Under this independent reference model there is no order in the requests at all. All the locality is in the popularity: temporal locality “on average”.
2.4 It is physics, not just a model
Does any of this matter on today’s hardware, seen from an interpreted language? Demo 01 Part D times the same Python loop reading an array of 8-byte integers, in order or scattered (a large odd stride that visits every slot). This is a real measurement:
| array | per read, in order | per read, scattered | ratio |
|---|---|---|---|
| 32 KB (fits in the CPU’s caches) | 31.4 ns | 32.3 ns | ×1.03 |
| 64 MB (does not) | 33.1 ns | 135.3 ns | ×4.1 |
The interpreter’s overhead (~30 ns per iteration) is identical in all four runs. The extra ~100 ns is DRAM latency that the CPU’s caches hide only when there is locality to exploit. On Python 3.9, which is slower per iteration, the same loop took 46 ns per read for the small array.
The lesson. Locality is a property of the reference stream — produced by code, by file habits, by human taste — not of the data. A cache can only harvest what the stream offers, and some streams (random, pointer-chasing, one-pass scans) offer nothing.
3. One idea at three scales: Atlas, the Model 85, and distributed caches
3.1 The Atlas one-level store (1961–62)
The Manchester/Ferranti Atlas had a small, fast core memory and a large, slow magnetic drum. Programmers of the day moved data between them by hand. Atlas made the machine do it (Fotheringham 1961, paper):
- Core and drum were addressed as one memory of up to about a million 48-bit words.
- Memory was divided into 512-word blocks. Each page of core had a page address register holding the number of the block it currently held, and every address was compared in parallel with all of them (associative lookup).
- If no register matched, an interrupt invoked the Supervisor, which brought the block in from the drum and wrote another one back.
- The block to evict was chosen by a “drum transfer learning program” that watched usage: an early replacement policy.
- A program written for one machine ran unaltered on another with a different split of core and drum. The cache was transparent.
That is virtual memory, and also the first automatic cache: a fast store holding copies of the blocks in use, managed without the program’s help.
3.2 The IBM System/360 Model 85 (1968)
Seven years later IBM put a fast buffer between the processor and main memory and called it a cache (Liptay 1968, paper; the paper’s footnote says cache is a synonym for “high-speed buffer”).
- Sizes: a 16 KB cache (24 or 32 KB optional), in front of 0.5–4 MB of main storage with a 1.04 µs cycle, for a processor with an 80 ns cycle.
- Organization: the cache was divided into 16 sectors of 1 KB, each assigned dynamically to a 1 KB region of main storage. Each sector was split into 16 blocks of 64 bytes loaded on demand, with a validity bit per block. So the unit of allocation (1 KB) differed from the unit of transfer (64 B).
- Replacement: an activity list ordered the sectors by recency of use, and the least recently used one was reassigned. That is LRU. In Liptay’s comparison of replacement schemes it cost little and performed best.
- Writes: always went through to main storage, so the cache never held the only copy and could drop a sector without writing anything back.
- Results: a 96.8% average hit probability over 19 traces, and 81% of the performance of an ideal machine whose whole memory ran at cache speed (range 66–94%). Doubling the cache to 32 KB raised it to about 89%.
Every concept in this lecture is in that paper: hit ratio, block size, LRU, write-through, trace-driven evaluation.
3.3 Multics (1968): sharing one copy
Daley and Dennis describe the Multics virtual memory (paper):
- every process sees memory as a collection of named segments, each paged on demand;
- the same segment — a procedure, a data file — can be shared: one copy in memory, mapped into many processes’ address spaces;
- symbolic references (names) are translated into segment numbers at run time, the first time they are used, and the translation is remembered for later uses (dynamic linking).
Two ideas from it recur in distributed systems. Sharing one cached copy among many users is the shared proxy of §9. Caching the result of a name translation is AFS’s cached directories and DNS.
3.4 And then: everywhere
The same structure — fast small copy, slow large original, a bet on locality — now appears at every layer:
| cache | fast store | slow store | miss penalty | |
|---|---|---|---|---|
| CPU L1 | SRAM | DRAM | ~1 ns | ~100 ns |
| OS page cache | DRAM | SSD / disk | ~100 ns | ~0.1–10 ms |
| AFS client | local disk | file server | ~0.1 ms | ~1–100 ms |
| browser / proxy | local disk / RAM | web server | ~1 ms | ~10–200 ms |
| CDN edge | RAM / SSD near users | origin data center | ~10 ms (one RTT) | ~100+ ms |
| DNS resolver | RAM | authoritative servers | ~1 ms | ~10–100 ms |
The mathematics below does not care which row you are in. Only the numbers change, by factors of a million.
4. Measuring a cache: hit ratio, miss ratio, average access time
4.1 Average access time
If every reference first checks the cache (), and the fraction that miss also pay the miss penalty :
Demo 02 Part A tabulates it for a CPU cache ( = 1 ns, = 100 ns) and a file cache on a client ( = 0.1 ms local disk, = 50 ms to a distant server):
| hit ratio | miss ratio | CPU: AMAT | speedup | files: AMAT | speedup |
|---|---|---|---|---|---|
| 0 | 1 | 101 ns | ×1.0 | 50.1 ms | ×1.0 |
| 0.5 | 0.5 | 51 ns | ×2.0 | 25.1 ms | ×2.0 |
| 0.9 | 0.1 | 11 ns | ×9.2 | 5.1 ms | ×9.8 |
| 0.968 | 0.032 | 4.2 ns | ×24 | 1.7 ms | ×29.5 |
| 0.99 | 0.01 | 2 ns | ×50.5 | 0.60 ms | ×83.5 |
| 0.999 | 0.001 | 1 ns | ×92 | 0.15 ms | ×334 |
Going from 90% to 99% hits — a nine-point improvement that sounds small — made the file cache 8.5× faster, and 99% → 99.9% another 4×. Once hits are cheap, the time is the misses. So think in miss ratios: halving the miss ratio roughly halves the time, whatever the hit ratio “looks like”.
The Model 85 reminds us that the formula is a simplification. At its 96.8% hit ratio, a naive 100× miss penalty predicts an average of 4.2 ns against 1 ns ideal. The real machine reached 81% of ideal (paper), because its miss penalty was smaller (main storage was about 13 processor cycles away) and partly overlapped with other work. The direction is right; the constants belong to the machine.
4.2 Does the formula predict reality? (a real check)
Demo 02 Part B builds a real system:
- a key-value server from Lecture 3’s
rpc.py, in a thread, over loopback TCP; - a client stub with an LRU cache of replies;
- a Zipf(0.9) stream of 20,000 requests over 10,000 keys.
It first measures (a request with no cache, 31.9 µs) and (a cache hit, 34 ns) separately. Then it runs the stream at five cache sizes and compares the real time with :
| cache size | hit ratio | misses | real time | predicted | real vs predicted |
|---|---|---|---|---|---|
| 0 | 0.0% | 20,000 | 623 ms | 638 ms | −2% |
| 10 | 6.6% | 18,689 | 566 ms | 596 ms | −5% |
| 100 | 25.9% | 14,810 | 411 ms | 472 ms | −13% |
| 1,000 | 54.5% | 9,100 | 251 ms | 290 ms | −13% |
| 10,000 | 73.7% | 5,254 | 150 ms | 168 ms | −11% |
The formula captures the shape: growing the cache from 100 to 1,000 replies cut the misses by 1.63× and the time by 1.64×. But the error is not stable. Across runs on this machine it ranged from about −13% to +24%. The hit ratios are exact and repeat on every run; the timings do not. The likely cause is that the machine has fast and slow cores and the OS moves threads between them. That is a hypothesis, recorded as such in the code README.
The practical lesson: predict with the formula, then measure, and report the spread, not the best run.
4.3 Several levels
Caches stack: a client cache in front of a regional proxy in front of the origin. If each level has a local hit ratio (hits among the requests that reach it) and probe latency :
Demo 02 Part C uses assumed numbers: client 0.1 ms with 60% local hits, proxy 5 ms with 70%, origin 80 ms.
| configuration | served at each level | AMAT | load on the origin |
|---|---|---|---|
| client only | 60% / 40% | 32.1 ms | 40% |
| client + proxy | 60% / 28% / 12% | 11.7 ms | 12% |
| proxy only (85% of all requests) | 85% / 15% | 17.0 ms | 15% |
Two distinctions matter:
- A level’s local hit ratio (70% for the proxy) is not its global one (28% of all requests). Lower levels see only the misses of upper levels — the hardest requests.
- A cache also reduces load on what is behind it. The origin’s load fell from 40% to 12% of requests. For AFS (Lecture 5) that was the point: misses are server load.
Two more metrics come up in distributed caches:
- Byte hit ratio: the fraction of bytes, not requests, served from the cache. It matters when objects differ in size, as P2’s files do.
- Tail latency: the misses are the tail, so a 99% hit ratio means the p99 request goes all the way to the origin.
5. Miss-ratio curves: every cache size at once
5.1 Why a curve
“How big should the cache be?” has no answer without knowing how the miss ratio falls as the cache grows. A miss-ratio curve (MRC) plots against . It is the single most useful picture of a workload for caching:
- its knees tell you where buying more cache stops paying;
- its cliffs warn you about sizes just too small;
- comparing tenants’ curves tells you how to split memory between them.
5.2 One pass for all sizes: stack distances
Simulating a cache once per size is slow. Mattson et al. (1970) observed that LRU is a stack algorithm: an LRU cache of size always holds a subset of what an LRU cache of size holds (the inclusion property). So imagine all items ever referenced in a single list ordered by recency, the LRU stack:
- the stack distance of a reference is the position of its item in that list: 0 if it was the last item used, if other distinct items were used since;
- the first reference to an item has infinite distance (a cold miss);
- an LRU cache of capacity holds exactly the top items, so the reference hits if and only if its distance — for every at once.
So one pass that computes all distances gives the whole curve:
cachelab.stack_distances counts the distinct items between two uses of with a Fenwick tree. It holds a 1 at the latest position of every item, so the count is a range sum, giving time: about 0.2 s for 100,000 references in Python. Demo 03 checks the curves against direct LRU simulation at 21 (stream, size) pairs; they are identical.
5.3 What curves look like
LRU miss ratios from demo 03 (100,000 references each; Zipf over 10,000 items):
| stream | 10 | 30 | 100 | 300 | 1,000 | 3,000 | 10,000 |
|---|---|---|---|---|---|---|---|
| Zipf 0.6 | 0.995 | 0.985 | 0.956 | 0.894 | 0.756 | 0.513 | 0.100 |
| Zipf 0.8 | 0.972 | 0.929 | 0.844 | 0.735 | 0.566 | 0.351 | 0.097 |
| Zipf 1.0 | 0.869 | 0.748 | 0.608 | 0.474 | 0.326 | 0.184 | 0.085 |
| Zipf 1.2 | 0.656 | 0.490 | 0.344 | 0.237 | 0.144 | 0.079 | 0.060 |
| loop over 1,000 items | 1.000 | 1.000 | 1.000 | 1.000 | 0.010 | 0.010 | 0.010 |
| loop over 1,050 items | 1.000 | 1.000 | 1.000 | 1.000 | 1.000 | 0.011 | 0.011 |
| Zipf 1.0 + a 2,000-item scan every 4,250 | 0.912 | 0.831 | 0.737 | 0.653 | 0.580 | 0.535 | 0.435 |
Three shapes to recognize:
- Skewed popularity gives a smooth, concave curve. For Zipf 1.0, each tenfold growth of the cache removed about the same share of requests: 0.26, 0.28, 0.24. Returns per added item diminish, but returns per tenfold growth hold steady. Skew decides everything: a 300-item cache (3% of items) missed 89% of requests at but 24% at .
- A loop gives a cliff. Over 1,000 items, LRU missed everything with 999 slots or fewer and almost nothing with 1,000. Over 1,050 items, even 1,000 slots missed 100%: LRU always evicts exactly the item the loop needs next. This is LRU’s classic pathology. Lecture 8’s policies and P2’s large files run into it.
- One-time scans pollute. Mixing a scan of 2,000 never-reused items into the Zipf stream raised the miss ratio of a 1,000-item cache from 0.326 to 0.580 and of a 3,000-item cache from 0.184 to 0.535. Each scan flushes the popular items out. Scan resistance is another of Lecture 8’s goals.
A real trace has a fourth feature: a floor. In Lecture 5’s file trace (448 opens, reads and writes), 179 references are first uses (40%). The curve flattens there: 0.498 at 100 files, 0.400 at 300. No cache can do better than its cold misses; only prefetching can attack those (Lecture 9).
5.4 A curve from a formula: Che’s approximation
Without a trace, can we predict the curve from the popularity distribution alone? Che, Tung and Wang (2002) gave a remarkably good approximation for LRU under independent references:
- Every item stays in the cache for about the same characteristic time after its last request, where solves . The left side is the expected number of distinct items requested in steps, which must equal the capacity.
- Item is then in the cache with probability , and
Demo 03 Part C compares it with the simulated (warm) curves for all four Zipf exponents and six sizes. The largest error was 0.004 in miss ratio. For sizing a cache before you have a trace, a popularity estimate plus this formula is often enough. For example, Zipf 1.0 over 100,000 items:
| cache size | Che’s estimated hit ratio |
|---|---|
| 1,000 | 50.6% |
| 2,000 | 57.4% |
| 4,000 | 64.3% |
Each doubling adds about 7 points.
5.5 Using a curve
- Sizing: pick the size at the knee, or the smallest size whose miss ratio brings the backend’s load (miss ratio × request rate) under its capacity.
- Partitioning a shared cache among tenants: give the next unit of memory to whoever’s curve drops most there. That is equal marginal gain, the same logic as any resource allocation.
- Warning signs: a cliff just above your current size means a small growth of the working set will cause a collapse in hit ratio. That is worth knowing before it happens in production.
6. Working sets
Denning (1968) gave a program-centred definition of “what a cache should hold”. The working set is the set of distinct items referenced in the last references before time . The working-set principle: a program runs efficiently if its working set is in fast memory, and thrashes if not.
Demo 04 Part A runs a program with three phases (hot sets of 200, 50 and 500 items, plus 5% random “noise” references over a huge space):
| reference | 5,000 | 15,000 | 25,000 | 35,000 | 45,000 | 55,000 | 65,000 | 75,000 | 85,000 |
|---|---|---|---|---|---|---|---|---|---|
| 261 | 261 | 251 | 102 | 103 | 96 | 469 | 467 | 460 | |
| 465 | 688 | 780 | 720 | 561 | 526 | 1,055 | 1,008 | 954 |
- With a 1,000-reference window, the working set tracks the phases: about hot set + noise.
- With a 10,000-reference window it lags and blends phases. At = 35,000 it still counts phase 1’s items, and the noise alone adds about 500 distinct items.
- The window is the definition: too short and it misses reuse, too long and it mixes phases.
Sizing an LRU cache by the working set works, provided the noise is counted (miss ratios after warm-up; “first 2,000” = the start of the phase):
| phase | 200 slots | 500 slots | 1,000 slots |
|---|---|---|---|
| phase 3 (hot 500), after warm-up | 0.64 | 0.16 | 0.05 (the noise floor) |
| phase 3, its first 2,000 references | 0.67 | 0.31 | 0.29 |
With 500 slots for a 500-item hot set, the one-time noise items keep pushing hot ones out. And every phase change costs a burst of misses even with ample space. The new working set must be loaded: a small cold start inside a running program.
7. Why misses happen: the three C’s (and a fourth)
Hill and Smith classify every miss of a cache into one of three kinds, by asking what would have prevented it:
- Compulsory (cold): the first reference to a block ever. An infinite cache misses too. Only prefetching or bigger blocks (which make one miss cover many later references) help.
- Capacity: not the first reference, but even a fully associative LRU cache of the same size would miss. The cache is too small for the working set; only more capacity helps.
- Conflict: the fully associative cache would have hit. The miss is due to restricted placement: in a direct-mapped or set-associative cache, a block may live only in its set, and two hot blocks can fight over one set. More associativity helps.
Demo 04 Part B uses a 16 KB cache with 64-byte blocks:
| program | cache | hit ratio | compulsory | capacity | conflict |
|---|---|---|---|---|---|
| c[i] = a[i] + b[i], arrays 16 KB apart | direct-mapped | 0.0% | 768 | 0 | 5,376 |
| 2-way | 0.0% | 768 | 0 | 5,376 | |
| 8-way | 87.5% | 768 | 0 | 0 | |
| sum a 256×256 matrix by columns | direct-mapped | 0.0% | 8,192 | 0 | 57,344 |
| 8-way | 0.0% | 8,192 | 0 | 57,344 | |
| fully associative | 87.5% | 8,192 | 0 | 0 | |
| sum a 64 KB array 4 times | any | 87.5% | 1,024 | 3,072 | 0 |
- Three arrays exactly 16 KB apart map every
a[i],b[i],c[i]to the same set. Direct-mapped and 2-way (three streams, two slots) thrash completely; 8 ways fix it. Associativity must cover the number of conflicting streams. - A column walk of a 256×256 matrix strides 2 KB, which maps all 256 rows to only 8 sets. Even 8-way is not enough, and only full associativity reaches the spatial-locality ceiling of 87.5%.
- A 64 KB loop over a 16 KB cache has pure capacity misses at every associativity. Only a bigger cache helps.
Most distributed caches (file caches, web caches) are fully associative: a hash table can put any item anywhere. So they have only compulsory and capacity misses — plus a fourth C that CPU-cache textbooks add for multiprocessors: coherence misses. Those happen when a cached copy was valid but had to be discarded because someone else changed the original. They are Lecture 7’s subject.
7.1 Cold starts
Compulsory misses come in bursts whenever a cache starts empty: a reboot, a new server added to a pool, a cache flush. Demo 04 Part C starts an LRU cache of 1,000 items empty under a Zipf(0.9) stream:
| references | 0–2,000 | 2,000–4,000 | 4,000–6,000 | … | steady state |
|---|---|---|---|---|---|
| hit ratio | 45.1% | 56.0% | 57.4% | … | 55.7% |
It reached 95% of its steady hit ratio after about 4,000 references, and the cold start cost about 640 extra misses. Every one of them was load on the backend at exactly the wrong moment, right after a failure.
Two design consequences:
- Persistent caches survive restarts. AFS kept its cache on the workstation’s local disk precisely because reboots were frequent (Lecture 5). After a reboot it revalidates the entries instead of refetching them.
- In large services, a cache failure is a load spike on the backend. If the backend cannot absorb the cold-start misses, the system can fall into the kind of metastable overload seen in Lecture 4.
8. Granularity: how much to fetch per miss
8.1 Block size
A bigger block exploits more spatial locality: one miss brings more neighbours. But for a fixed capacity it holds fewer distinct blocks (less room for temporal locality), and it fetches bytes nobody reads, which costs transfer time. Demo 05 Part A uses a 16 KB cache and reads of variable-length records (64 bytes on average) scattered over 4 MB with Zipf popularity. A miss costs 50 ns plus the block size at 8 bytes/ns:
| block | blocks in cache | miss ratio | bytes fetched per read | average access time |
|---|---|---|---|---|
| 8 B | 2,048 | 0.521 | 4.2 | 27.6 ns |
| 32 B | 512 | 0.199 | 6.4 | 11.7 ns |
| 64 B | 256 | 0.147 | 9.4 | 9.5 ns |
| 128 B | 128 | 0.124 | 15.9 | 9.2 ns |
| 512 B | 32 | 0.115 | 59.0 | 14.1 ns |
| 4 KB | 4 | 0.117 | 481.0 | 67.0 ns |
The miss ratio alone is misleading here. It falls and then goes flat: once a block holds a whole record, bigger blocks add no hits. But the cost of each miss keeps growing, so the access time is U-shaped: best at 128 bytes, and 7× worse at 4 KB. The right block size is where time bottoms out.
Liptay found the same direction for the Model 85 (paper): with a 16 KB cache, 64-, 128- and 256-byte blocks reached 82.5%, 81.0% and 78.1% of ideal speed. Smith’s 1982 survey made block size a central design parameter of every cache.
8.2 Whole files, chunks or blocks
Lecture 5 contrasted AFS-2 (whole files), AFS-3 (64 KB chunks) and NFS (8 KB blocks). Demo 05 Part B compares them on three workloads:
| workload | unit | fetches | MB moved | bytes before the first byte |
|---|---|---|---|---|
| Lecture 5 benchmark (whole-file reads) | whole file / 64 KB / 8 KB | 178 / 178 / 178 | 0.52 each | 2,000 |
| 300 images of 4 MB, read the first 16 KB, twice | whole file | 600 | 2,400 | 4,000,000 |
| 64 KB chunks | 300 | 19.7 | 65,536 | |
| 8 KB blocks | 600 | 4.9 | 8,192 | |
| a 2 GB log read twice, 1 GB cache | whole file | — | impossible (file > cache) | — |
| 64 KB chunks | 61,036 | 4,000 | 65,536 |
- Every file in the benchmark is under 8 KB, so the three granularities tie exactly. Whole-file transfer costs nothing extra for small files, and Ousterhout et al. (1985, paper) found most UNIX files to be small. That is why AFS’s bet worked.
- Reading the head of large files is whole-file caching’s worst case: 488× the bytes of block caching, and a 4 MB wait for the first byte.
- A file bigger than the cache cannot be used at all with whole files. Chunks fix both problems, which is why AFS-3 adopted them. The 2 GB log also shows §5’s cliff again: its second sequential pass missed every chunk, because a scan larger than an LRU cache gets no hits.
9. Where to put the cache
A distributed system can cache at the client (fastest hits, no sharing), at a proxy shared by many clients (one client’s miss warms the cache for the others), or at the server (which saves the server’s disk but not the network). Demo 05 Part C gives 20 clients a fixed budget of 4,000 cached objects. The latencies are client 0.1 ms, proxy 5 ms and origin 50 ms; the workload is Zipf 0.8 over 20,000 objects:
| clients have | configuration | client hits | proxy hits | to origin | mean ms | objects cached twice or more |
|---|---|---|---|---|---|---|
| same interests | 20 private caches of 200 | 17.2% | — | 82.8% | 41.51 | 543 |
| same interests | one shared proxy of 4,000 | — | 56.6% | 43.4% | 26.71 | 0 |
| same interests | clients 100 each + proxy 2,000 | 12.1% | 32.2% | 55.6% | 32.31 | 231 |
| different interests | 20 private caches of 200 | 17.2% | — | 82.8% | 41.51 | 344 |
| different interests | one shared proxy of 4,000 | — | 33.3% | 66.7% | 38.34 | 0 |
- Pooling a fixed budget wins when interests are shared. The private caches spent part of their memory on duplicates (543 objects cached in two or more places), and none of them could benefit from another client’s fetch. The shared proxy halved the origin’s load and had the lowest mean latency, despite the 5 ms trip for every hit.
- Sharing only pays if clients want the same things. When each client had its own popularity ranking, the proxy’s advantage shrank: 66.7% to the origin vs 82.8%.
- This is a different question from §4.3. There, adding a proxy behind existing client caches helped a lot. Here, splitting a fixed budget between levels was worse than pooling it. Real systems usually have both: browsers cache privately, and CDNs pool across millions of users.
Placement also decides who can see what:
- a client cache serves only that client;
- a shared proxy raises privacy questions (one user’s requests warm a cache others can probe);
- every additional copy is one more copy to keep consistent (Lecture 7).
10. What a cache costs
Caches are not free:
- Space: memory, disk, or edge servers. Its value is the marginal height of the MRC (§5).
- Consistency: a copy can become stale when the original changes. The next lecture is entirely about this cost.
- Cold starts and failure modes: a cache that restarts, or a cache tier that fails, sends its whole miss stream to the backend at once (§7.1). Systems that depend on a cache’s hit ratio for capacity have turned cache failures into outages.
- Complexity and attack surface: eviction bookkeeping, invalidation logic, and caches that can be poisoned (made to store wrong data) or used to infer what others accessed. Security in distributed systems is Lecture 26.
Summary
- A cache keeps copies of a subset of a slow store in a fast one, betting that the past predicts the future. Its whole value comes from locality in the reference stream.
- Temporal locality comes from loops,
#includes, re-reading and popularity; spatial locality from arrays, sequential code and whole-file reads.- Summing an array once hit 87.5%, all of it spatial; a column-order matrix walk hit 0%; random reads in 1 MB hit 1.6% ≈ cache/region.
- Real programs on the Model 85 averaged 96.8% (paper).
- A real 64 MB array read in scattered order took 4.1× longer per read, even from Python.
- One idea at three scales: Atlas (1961, one-level store, automatic replacement), the Model 85 (1968, the first “cache”: 16 KB, 64-byte blocks on demand, LRU, write-through), Multics (shared copies, cached name translation), then AFS, proxies, CDNs and DNS.
- AMAT . Once hits are cheap, time follows misses: 90% → 99% hits gave 8.5× for a file cache. Against a real RPC cache the formula was within a few percent in some runs and up to 24% off in others; the shape (time ∝ misses) held every time.
- A miss-ratio curve for every size comes from one pass of LRU stack distances (exact; checked 21 times). Recognize three shapes:
- Zipf: concave, with about equal gains per tenfold growth;
- loops: a cliff (1,050-item loop, 1,000 slots: 100% misses);
- scans: pollution (32.6% → 58.0% misses).
- Cold misses set a floor (40% in Lecture 5’s trace).
- Che’s approximation predicted Zipf curves to within 0.004 from popularity alone.
- Working sets track program phases; size caches to them, noise included, and expect a burst of misses at each phase change. Misses are compulsory, capacity or conflict (plus coherence, Lecture 7). Cold starts cost about 640 extra misses here, which is why persistent caches matter.
- Granularity: block size trades spatial locality against capacity and transfer cost (miss ratio flat, time U-shaped). Whole files are free for small files, terrible for partial reads of big ones (488× the bytes), and impossible above the cache size. Chunks fix that.
- Placement: with a fixed budget and shared interests, one shared proxy beat 20 private caches (43.4% vs 82.8% of requests to the origin); with different interests the advantage shrank.
Common pitfalls
- Quoting the hit ratio instead of the miss ratio: 99% and 99.9% hits sound alike, but one is 10× more misses.
- Assuming locality: hash tables, pointer chasing, random sampling and one-pass scans have none, and a cache in front of them is pure overhead.
- Sizing a cache from one point instead of a miss-ratio curve: a size just below a cliff looks fine until the working set grows by 5%.
- Optimizing the miss ratio instead of the time: bigger blocks can keep the miss ratio flat while making every miss more expensive.
- Comparing local hit ratios across levels: a proxy’s 70% of the requests it sees may be only 28% of all requests.
- Forgetting cold starts: a restarted cache sends its whole miss stream to the backend at the worst possible moment.
- Duplicating a fixed budget across many small private caches when clients share interests.
Exercises
-
Three levels. A request first checks a client cache (0.2 ms, local hit ratio 80%), then a proxy (10 ms, local hit ratio 50%), then the origin (100 ms). (a) What is the average access time? (b) What fraction of all requests does each level serve? (c) The proxy is upgraded to a 70% local hit ratio. What is the new average, and which level now dominates it?
Answer
(a) 0.2 + 0.2 × (10 + 0.5 × 100) = 0.2 + 2 + 10 = 12.2 ms. (b) Client 80%, proxy 0.2 × 0.5 = 10%, origin 10%. The proxy's *global* hit ratio is only 10%. (c) 0.2 + 0.2 × (10 + 0.3 × 100) = 0.2 + 2 + 6 = 8.2 ms. The origin's 6 ms (6% of requests × 100 ms) is still the largest term, and the proxy's own 2 ms is next. A faster proxy would now help almost as much as a better hit ratio. -
Stack distances by hand. For the reference string
a b c a d b a c d e a: (a) compute the LRU stack distance of each reference; (b) give the LRU miss count for cache sizes 1 through 5 from them; (c) which references are cold misses?Answer
(a) a ∞, b ∞, c ∞, a 2, d ∞, b 3, a 2, c 3, d 3, e ∞, a 3. (b) A reference hits iff its distance is less than C. C = 1 or 2: no distance is below 2, so all 11 references miss. C = 3: the two references at distance 2 hit, 9 misses. C = 4 or 5: every finite distance (2 or 3) hits, leaving 5 misses. (c) The five first references (a, b, c, d, e) are cold: no cache size removes them. (`cachelab` agrees: 11, 11, 9, 5, 5.) -
Loop order. In C,
double A[N][N]is stored row by row. Which of these loops has better locality, and by how much in a cache with 64-byte blocks and much less than N × 64 bytes of capacity?for i: for j: s += A[i][j]vsfor j: for i: s += A[i][j]. How does the answer change forN = 8?Answer
Row order touches consecutive doubles: 1 miss per 8 reads (87.5% hits). Column order jumps N × 8 bytes between reads. If a column's N blocks do not fit, every read misses (0%), as in demo 01. For N = 8 the whole matrix is 512 bytes = 8 blocks, which fits in any reasonable cache: both orders miss only the 8 compulsory misses. Locality problems appear only when the working set exceeds the cache. -
When bigger blocks hurt. Give two distinct reasons why doubling the block size of a fixed-capacity cache can make performance worse, and describe a workload for each.
Answer
(1) Fewer blocks fit, so temporal locality across many scattered items is lost. Example: binary search or a hot set of scattered small records; demo 01's binary search did better with 8-byte blocks. (2) Each miss transfers more bytes, so the miss penalty grows even when the miss ratio does not fall. Example: records smaller than the block, where demo 05's miss ratio was flat from 512 B up while the access time grew 7×. A third, for shared caches: bigger blocks increase *false sharing* — two clients updating different parts of one block — which is a consistency cost (Lecture 7). -
Sizing with a formula. A file server sees Zipf(1.0) popularity over 100,000 files. Che’s approximation gives an LRU hit ratio of about 50.6% with 1,000 cached files, 57.4% with 2,000 and 64.3% with 4,000. The server can handle 40% of the current request rate on cache misses. What is the smallest of these cache sizes that keeps it out of overload, and what does each doubling buy?
Answer
The miss ratio must be at most 40%, so the hit ratio must be at least 60%. 1,000 (49.4% misses) and 2,000 (42.6%) are not enough; 4,000 (35.7%) is. Each doubling adds about 7 points of hit ratio, roughly the steady gain per tenfold growth seen in demo 03 spread over log₂10 ≈ 3.3 doublings. To check against a real trace, compute its MRC with stack distances. -
Working set. For the stream
a b a c b d c d e aand window τ = 3, compute at every step. What does it suggest about a cache size for this stream?Answer
The sizes are 1, 2, 2, 3, 3, 3, 3, 2, 3, 3. For example, at the 5th reference (`b`) the last three were `a c b`, three distinct items. A working set of about 3 suggests a cache of 3 items. But the window is only 3 references: with a longer window the set would include `a`'s reuse at the end, showing that a 3-item cache misses `a` the second time. -
Private or shared? Ten clients each have a 500-object cache with a 30% hit ratio. A shared proxy holding the same 5,000 objects would see all their requests and hit 55% of them. Latencies: client 0.1 ms, proxy 4 ms, origin 60 ms. Which configuration has the lower mean latency and the lower origin load? What property of the workload makes the proxy’s 55% possible?
Answer
Private: 0.1 + 0.7 × 60 = 42.1 ms; origin load 70%. Shared: 4 + 0.45 × 60 = 31 ms; origin load 45%. The proxy wins on both. Its higher hit ratio comes from shared interests (one client's miss warms the cache for others) and from no duplication of popular objects across ten caches. With disjoint interests it would hit roughly what the private caches do, while every hit pays 4 ms instead of 0.1. -
Cold start arithmetic. A cache tier serves 10,000 requests/s with a steady 90% hit ratio, and the backend can handle 3,000 requests/s. After a restart, the hit ratio climbs linearly from 0% to 90% over 60 s. (a) What is the backend’s load at t = 0, 20 and 40 s? (b) For how long is it overloaded? (c) Name two mitigations.
Answer
(a) At hit ratio h(t) = 0.9 t / 60 the backend sees 10,000 × (1 − h). t = 0: 10,000/s. t = 20 s (h = 0.3): 7,000/s. t = 40 s (h = 0.6): 4,000/s. (b) The load exceeds 3,000/s while 1 − h > 0.3, i.e. h < 0.7, i.e. t < 46.7 s — nearly 47 seconds of overload, during which timeouts and retries can make things worse (Lecture 4). (c) A persistent cache that survives restarts (AFS's disk cache); warming the cache from a peer or a snapshot before taking traffic; restarting cache servers one at a time; admission control or load shedding at the backend.
Related project and problem set (concepts only)
- Project 2’s proxy caches whole files under a size limit. The ideas behind its LRU of variable-sized files are §1.2, §5 and §8. How to evict when items differ in size is Lecture 8’s subject. The design is yours.
- Problem Set 2 includes caching scenarios with latencies and hit ratios, and replacement on small reference strings. §4 and §5 give the vocabulary and the method (AMAT, stack distances), not the answers. The exercises above deliberately use different numbers and strings.
Further reading
- J. Fotheringham, “Dynamic Storage Allocation in the Atlas Computer…”, CACM 4(10), 1961 (course reading).
- J. S. Liptay, “Structural Aspects of the System/360 Model 85, II: The Cache”, IBM Systems Journal 7(1), 1968 (course reading) — the original “cache”, with trace-driven sizing studies.
- R. C. Daley and J. B. Dennis, “Virtual Memory, Processes, and Sharing in MULTICS”, CACM 11(5), 1968 (course reading).
- P. J. Denning, “The Working Set Model for Program Behavior”, CACM 11(5), 1968; and “Virtual Memory”, ACM Computing Surveys 2(3), 1970.
- R. L. Mattson et al., “Evaluation Techniques for Storage Hierarchies”, IBM Systems Journal 9(2), 1970 — stack algorithms.
- A. J. Smith, “Cache Memories”, ACM Computing Surveys 14(3), 1982.
- L. Breslau, P. Cao, L. Fan, G. Phillips, S. Shenker, “Web Caching and Zipf-like Distributions: Evidence and Implications”, INFOCOM 1999.
- H. Che, Y. Tung, Z. Wang, “Hierarchical Web Caching Systems: Modeling, Design and Experimental Results”, IEEE JSAC 20(7), 2002.
- C. Waldspurger et al., “Efficient MRC Construction with SHARDS”, USENIX FAST 2015 — computing MRCs for huge production traces by sampling.
Preview of Lecture 7 — Cache consistency and one-copy semantics
Every cache in this lecture held copies that nobody else changed. Lecture 7 drops that assumption. When several clients cache the same file and one of them writes it, what may the others see? The ideal is one-copy semantics: it behaves as if there were a single copy. We then look at what it costs, and at the weaker promises that real systems make instead (session semantics, TTLs). The protocols that keep caches fresh — check-on-use, callbacks and leases — are measured on the simulator under sharing, crashes and partitions, and Gray and Cheriton’s lease-term model is reproduced.
术语表 (Glossary, English → 中文)
| English | 中文 |
|---|---|
| cache / cached copy | 缓存 / 缓存副本 |
| hit / miss | 命中 / 未命中(缺失) |
| hit ratio / miss ratio | 命中率 / 缺失率 |
| miss penalty | 缺失代价 |
| average memory access time (AMAT) | 平均访存时间 |
| local vs global hit ratio | 局部命中率 / 全局命中率 |
| byte hit ratio | 字节命中率 |
| locality (temporal / spatial) | 局部性(时间 / 空间) |
| reference stream / trace | 访问序列 / 访问踪迹 |
| independent reference model (IRM) | 独立引用模型 |
| Zipf distribution / popularity skew | 齐普夫分布 / 流行度偏斜 |
| block / cache line / page / chunk | 块 / 缓存行 / 页 / 分块 |
| sector (Model 85) | 扇区 |
| validity bit | 有效位 |
| capacity | 容量 |
| associativity (direct-mapped / set-associative / fully associative) | 相联度(直接映射 / 组相联 / 全相联) |
| set / way | 组 / 路 |
| replacement policy / eviction | 替换策略 / 逐出 |
| least recently used (LRU) | 最近最少使用 |
| activity list | 活动列表(按最近使用排序) |
| write-through / write-back | 写直达 / 写回 |
| write-allocate | 写分配 |
| one-level store | 单级存储 |
| virtual memory | 虚拟内存 |
| page address register | 页地址寄存器 |
| associative lookup | 相联查找 |
| backing store (drum) | 后备存储(磁鼓) |
| segment / segmentation | 段 / 分段 |
| dynamic linking | 动态链接 |
| miss-ratio curve (MRC) | 缺失率曲线 |
| stack algorithm / inclusion property | 栈算法 / 包含性 |
| stack distance (reuse distance) | 栈距离(重用距离) |
| Fenwick tree (binary indexed tree) | 树状数组 |
| Che’s approximation / characteristic time | Che 近似 / 特征时间 |
| working set | 工作集 |
| thrashing | 抖动(颠簸) |
| phase (of a program) | 程序阶段 |
| compulsory / capacity / conflict / coherence miss | 强制性 / 容量 / 冲突 / 一致性缺失 |
| cold start / warm-up | 冷启动 / 预热 |
| persistent cache | 持久缓存 |
| cache warming | 缓存预热 |
| granularity | 粒度 |
| proxy cache / CDN (content delivery network) | 代理缓存 / 内容分发网络 |
| cache hierarchy | 缓存层次结构 |
| cache partitioning | 缓存划分 |
| cache poisoning | 缓存投毒 |
| trace-driven simulation | 踪迹驱动模拟 |