LRU Page Replacement: Recency as a Proxy
Evict the page that has gone unused the longest. Betting that the recent past predicts the near future gets LRU close to optimal, but tracking every access exactly is too costly for hardware, so real systems approximate it.
How LRU Chooses a Victim
The LRU page replacement algorithm, short for least recently used page replacement, runs when a page fault needs a frame and memory is full. It evicts the resident page that has gone the longest without being referenced.
The reasoning is temporal locality: a page used a moment ago will probably be used again soon, while one untouched for a long time likely belongs to work the program has finished. Loops, call stacks and working sets all behave this way, which is why LRU lands close to the best possible on most real programs.
LRU is the mirror image of optimal page replacement. OPT evicts the page whose next use is furthest in the future, which no real system can know. LRU evicts the page whose last use is furthest in the past, using history as a guess about the future.
Unlike FIFO, every hit changes the order. Using a resident page makes it the most recent and puts it at the back of the eviction line. That bookkeeping on hits is both LRU's advantage and its cost.
- Rule: evict the page with the oldest last-use time
- Every reference, hit or fault, updates the order
- A stack algorithm: immune to Belady's anomaly
Worked Example: 9 Faults in 3 Frames
This standard exam string runs through three frames. On each fault with full frames, compare the last-use times of the three resident pages and evict the oldest. The new page takes the evicted page's frame.
The step that separates LRU from FIFO is t = 6. FIFO evicts 0, the earliest arrival, even though 0 was used at t = 5; LRU evicts 1 instead. At t = 7 page 0 is needed again: a hit for LRU, a fault for FIFO.
Total: 9 faults and 4 hits. FIFO takes 10 and OPT takes 7 on the same string. With 4 frames LRU drops to 6 faults; as a stack algorithm it never gets worse when frames are added, unlike FIFO.
| Ref | Frames after | Result | Why this victim |
|---|---|---|---|
| 7 | 7 – – | fault | free frame |
| 0 | 7 0 – | fault | free frame |
| 1 | 7 0 1 | fault | free frame |
| 2 | 2 0 1 | evict 7 | 7 last used at t = 1, the oldest |
| 0 | 2 0 1 | hit | 0 becomes the most recent |
| 3 | 2 0 3 | evict 1 | 1 last used at t = 3; 0 was just used |
| 0 | 2 0 3 | hit | LRU kept 0; FIFO faults here |
| 4 | 4 0 3 | evict 2 | 2 last used at t = 4 |
| 2 | 4 0 2 | evict 3 | 3 last used at t = 6 |
| 3 | 4 3 2 | evict 0 | 0 last used at t = 7 |
| 0 | 0 3 2 | evict 4 | 4 last used at t = 8 |
| 3 | 0 3 2 | hit | |
| 2 | 0 3 2 | hit |
- Count faults: 3 compulsory + 6 replacements = 9
- Ties cannot happen: only one page is referenced per time step
Implementing LRU: Counters and Stacks
Counter method. A logical clock ticks on every memory reference, and each page-table entry stores the clock value of its last use. The victim is the entry with the smallest value, found by scanning every frame.
Stack method. Keep page numbers in a doubly linked list. On every reference, unlink the page and put it on top; the bottom is always the least recently used, so the victim is found at once. Moving an entry costs up to six pointer updates. The code on this page uses this method: Python's OrderedDict, C++'s std::list with a hash map, and Java's LinkedHashMap in access order.
Neither fits in hardware, because the cost lands on every load and store, not just on faults. A memory access takes on the order of 100 nanoseconds, and adding a timestamp write or pointer updates to each one would cost more than the faults it saves.
So operating systems use an LRU approximation. The MMU sets a reference bit in a page's entry whenever the page is used, for free. Clock sweeps the frames and evicts the first page whose bit is 0, clearing bits as it passes. With a page's bit set when it is loaded, it also takes 9 faults on the string above. The aging algorithm keeps a few bits per page, shifted right periodically, to rank pages more finely.
In software, where an extra pointer update is cheap, exact LRU is common: functools.lru_cache in Python and many key-value caches. That data structure is the LRU Cache problem.
| Method | Work on every reference | Work on a fault | Used in practice |
|---|---|---|---|
| Counters | Write a timestamp | Scan all frames for the oldest | No |
| Stack (linked list) | Up to six pointer updates | None: victim is at the bottom | No (in hardware) |
| Clock | None: the MMU sets a bit | Sweep until a 0 bit | Yes |
- Counters: cheap per access in theory, but a scan on every fault
- Stack: O(1) victim, pointer updates on every access
- Hardware gives only a reference bit, so kernels approximate
Terms, operations, and practical uses
The rule
- DecisionEvict the page whose last reference is furthest in the past.
- BetTemporal locality — recently used pages get used again.
- Hits matterEvery reference updates the recency ordering.
- Mirror of OPTOPT reads forward; LRU reads the same axis backward.
Implementing it
- CountersTimestamp per page-table entry; O(frames) scan for the victim.
- StackDoubly linked list; O(1) victim, but heavy pointer traffic.
- The blockerBoth pay on every memory access, not just on faults.
- ApproximationClock gets nearly the same result using one free hardware bit.
Where it breaks
- 9 faultsOn the standard string — one better than FIFO, two off OPT.
- Sequential scanA large one-pass read evicts the real working set.
- Cyclic accessA loop just larger than memory faults on every reference.
- Real fixesLinux active/inactive lists; LRU-K and ARC track more history.
LRU on 7,0,1,2,0,3,0,4,2,3,0,3,2 with 3 frames
from collections import OrderedDict
def lru(refs, frames):
resident = OrderedDict()
faults = hits = 0
for page in refs:
if page in resident:
hits += 1
resident.move_to_end(page) # the bookkeeping FIFO refuses to do
continue
faults += 1
if len(resident) == frames:
resident.popitem(last=False) # least recently used
resident[page] = True
return faults, hits
refs = [7, 0, 1, 2, 0, 3, 0, 4, 2, 3, 0, 3, 2]
faults, hits = lru(refs, 3)
print(f"{faults} faults, {hits} hits")#include <iostream>
#include <list>
#include <unordered_map>
#include <vector>
int lru(const std::vector<int>& refs, int frames, int& hits) {
std::list<int> recency; // front = most recent, back = least recent
std::unordered_map<int, std::list<int>::iterator> where;
int faults = 0;
hits = 0;
for (int page : refs) {
auto found = where.find(page);
if (found != where.end()) {
++hits;
recency.splice(recency.begin(), recency, found->second);
continue;
}
++faults;
if (static_cast<int>(recency.size()) == frames) {
where.erase(recency.back());
recency.pop_back();
}
recency.push_front(page);
where[page] = recency.begin();
}
return faults;
}
int main() {
std::vector<int> refs = {7, 0, 1, 2, 0, 3, 0, 4, 2, 3, 0, 3, 2};
int hits = 0;
std::cout << lru(refs, 3, hits) << " faults, " << hits << " hits\n";
return 0;
}import java.util.LinkedHashMap;
import java.util.Map;
class Main {
static int[] lru(int[] refs, int frames) {
// Access order (the third constructor argument) makes get() move a key
// to the most-recent end, so the eldest key is the LRU victim.
Map<Integer, Boolean> resident = new LinkedHashMap<>(frames, 0.75f, true);
int faults = 0;
int hits = 0;
for (int page : refs) {
if (resident.get(page) != null) { // get(), not containsKey(): it reorders
hits++;
continue;
}
faults++;
if (resident.size() == frames) {
int eldest = resident.keySet().iterator().next();
resident.remove(eldest);
}
resident.put(page, Boolean.TRUE);
}
return new int[] {faults, hits};
}
public static void main(String[] args) {
int[] refs = {7, 0, 1, 2, 0, 3, 0, 4, 2, 3, 0, 3, 2};
int[] result = lru(refs, 3);
System.out.println(result[0] + " faults, " + result[1] + " hits");
}
}Step through it
Running on refs 7,0,1,2,0,3,0,4,2,3,0,3,2 · 3 frames
Where LRU Breaks Down
LRU fails whenever recent use stops predicting the next use. The classic case is a sequential scan bigger than memory: reading a large file touches each block once, every block looks freshly used, and LRU evicts the real working set to keep data that will never be read again. One grep over a large file can flush a database's cache this way.
The other is a loop slightly larger than memory. Cycling through pages 1 to 4 with three frames, the page needed next is always the one LRU just evicted, so every reference faults. FIFO does no better; evicting the most recently used page, or a random one, does much better here.
Real systems patch LRU instead of dropping it. Linux keeps active and inactive lists: a new page enters the inactive list and is promoted only on a second use, so a one-pass scan never displaces the active working set. Database buffer pools use LRU-K or ARC, which look at more than the last use so one touch cannot make a page look hot.
- A large one-pass scan evicts the hot pages
- A loop one page larger than memory faults on every reference
- Fixes: two-list LRU (Linux), LRU-K, ARC