TExcelTAD
Home › Online Algorithms & Competitive Analysis › Belady's Optimal Offline Rule

Belady's Optimal Offline Rule

Every competitive ratio in paging compares an online rule with OPT, so we need to know OPT exactly. In 1966 László Belady, studying virtual memory at IBM, proposed the rule now named after him: on a miss, evict the page whose next request lies furthest in the future (a page never requested again counts as infinitely far). This lesson states the paging model carefully, proves that Belady's rule minimizes the number of misses with an exchange argument, implements it in O(nlog⁡k)O(n \log k) time, and notes where the rule stops being optimal.

The paging model

A cache holds at most kk pages of a larger universe. Requests σ1,…,σn\sigma_1, \ldots, \sigma_n name pages. A request for a page in the cache is a hit and costs 0; otherwise it is a miss (a page fault), the page is loaded at cost 1, and if the cache is full some page must be evicted. Both the online algorithm and OPT start with the same cache, usually empty.

Two simplifications cost nothing:

  • Demand paging. An algorithm that loads pages before they are requested, or evicts pages without need, can be converted into a lazy one that loads a page only on its miss and evicts only when the cache is full, without increasing the number of loads: postpone each early load until the page is requested (if it ever is), and each early eviction until space is needed. So OPT may be assumed lazy.
  • Only the eviction choice matters. A lazy algorithm is fully described by which page it evicts on each miss with a full cache.

The rule and its trace

The animation runs Belady's rule (policy: opt) on 18 requests with three slots, and the program below prints the same decisions. Ties (several pages never requested again) go to the first such slot, as in the animation.

python · try it yourself
def belady_trace(reqs, k):
    slots, misses, log = [None] * k, 0, []
    for t, p in enumerate(reqs):
        if p in slots:
            log.append(f"{t + 1:2} {p}: hit")
            continue
        misses += 1
        if None in slots:
            i = slots.index(None)
            log.append(f"{t + 1:2} {p}: miss, free slot")
        else:
            def next_use(q):
                return reqs.index(q, t + 1) if q in reqs[t + 1:] else float("inf")
            i = max(range(k), key=lambda s: (next_use(slots[s]), -s))   # furthest; ties -> first slot
            nu = next_use(slots[i])
            when = "never again" if nu == float("inf") else f"next at {nu + 1}"
            log.append(f"{t + 1:2} {p}: miss, evict {slots[i]} ({when})")
        slots[i] = p
    return misses, log

reqs = "A B C D A B E A B C D E B A C D B E".split()
misses, log = belady_trace(reqs, 3)
print("\n".join(log))
print(f"{misses} misses in {len(reqs)} requests")
 1 A: miss, free slot
 2 B: miss, free slot
 3 C: miss, free slot
 4 D: miss, evict C (next at 10)
 5 A: hit
 6 B: hit
 7 E: miss, evict D (next at 11)
 8 A: hit
 9 B: hit
10 C: miss, evict A (next at 14)
11 D: miss, evict C (next at 15)
12 E: hit
13 B: hit
14 A: miss, evict E (next at 18)
15 C: miss, evict A (never again)
16 D: hit
17 B: hit
18 E: miss, evict D (never again)
10 misses in 18 requests

Why Belady's rule is optimal

Theorem (Belady, 1966). For every request sequence and every cache size kk, Belady's rule (longest forward distance, LFD) incurs the minimum possible number of misses.

The proof transforms an optimal algorithm step by step into LFD without increasing its cost. It goes back to Belady's paper and was made rigorous by Mattson, Gecsei, Slutz and Traiger (1970); the version here follows the standard exchange argument.

Proof sketch (exchange argument)

Lemma. Let AA be a lazy algorithm and ii a request index. There is an algorithm A′A' that makes the same decisions as AA on requests 1,…,i−11, \ldots, i - 1, makes LFD's decision on request ii, and satisfies A′(σ)≤A(σ)A'(\sigma) \le A(\sigma).

Proof. If AA already agrees with LFD at request ii, take A′=AA' = A. Otherwise, on a miss at request ii, AA evicts vv while LFD evicts uu, whose next request comes after vv's. Let A′A' evict uu. Now the caches differ in one page: AA holds S∪{u}S \cup \{u\} and A′A' holds S∪{v}S \cup \{v\}. A′A' copies AA until the difference disappears:

  • A request to a page of SS or outside both caches: both algorithms behave identically; if AA evicts a page of SS, so does A′A'; if AA evicts uu, A′A' evicts vv, and the caches become equal.
  • The first request to uu or vv is a request to vv, since vv is needed before uu. AA misses, A′A' hits. If AA now evicts uu, the caches are equal. If AA evicts some y∈Sy \in S, A′A' evicts yy as well and loads uu in its place; this load is free in the comparison because A′A' saved one miss at this request, and afterwards the caches are equal. (Making A′A' lazy again only lowers its cost.)

From the moment the caches agree, A′A' copies AA exactly. In every case A′A' has at most as many misses as AA.

Theorem. Start from an optimal algorithm and apply the lemma for i=1,2,…,ni = 1, 2, \ldots, n in turn. Each step keeps the cost optimal and makes the algorithm agree with LFD on one more request; after nn steps it is LFD.

An O(nlog⁡k)O(n \log k) implementation

Scanning ahead for the next use costs O(n)O(n) per miss. Precompute instead, in one backward pass, the time next[t]\text{next}[t] of the next request to the same page as σt\sigma_t. Then keep the cached pages in a max-heap keyed by their next-use time. On a hit the page's key changes, so push the new entry and leave the old one in the heap as a stale entry, skipped when popped. Stale entries let the heap grow to O(n)O(n) entries, so this version takes O(nlog⁡n)O(n \log n) time; an ordered set that updates keys in place, as in the C++ version below, keeps kk entries and takes O(nlog⁡k)O(n \log k).

text
BELADY(sigma, k)
0  next[t] = index of the next request to sigma[t], or infinity     // backward pass
1  cache = {} ; heap = empty max-heap of (next_use, page)
2  for t = 0 to n - 1
3      p = sigma[t]
4      if p not in cache
5          misses = misses + 1
6          if |cache| == k
7              pop entries until one is current: (nu, q) with cache[q] == nu
8              remove q from cache
9      cache[p] = next[t] ; push (next[t], p)
python · try it yourself
import heapq
import random

def belady_fast(reqs, k):
    n = len(reqs)
    nxt, seen = [0] * n, {}
    for t in range(n - 1, -1, -1):
        nxt[t] = seen.get(reqs[t], n + t)        # never again: beyond n, later pages first
        seen[reqs[t]] = t
    cache, heap, misses = {}, [], 0
    for t, p in enumerate(reqs):
        if p not in cache:
            misses += 1
            if len(cache) == k:
                while True:
                    nu, q = heapq.heappop(heap)
                    if cache.get(q) == -nu:           # skip stale entries
                        del cache[q]
                        break
        cache[p] = nxt[t]
        heapq.heappush(heap, (-nxt[t], p))
    return misses

def belady_naive(reqs, k):
    cache, misses = set(), 0
    for t, p in enumerate(reqs):
        if p not in cache:
            misses += 1
            if len(cache) == k:
                rest = reqs[t + 1:]
                cache.remove(max(cache, key=lambda q: rest.index(q) if q in rest else len(rest)))
            cache.add(p)
    return misses

rng = random.Random(12)
for trial in range(5):
    k, pages = rng.randint(2, 6), rng.randint(5, 15)
    reqs = [rng.randrange(pages) for _ in range(300)]
    print(f"k = {k}, {pages:2} pages: fast {belady_fast(reqs, k):3}, naive {belady_naive(reqs, k):3}")
k = 5,  9 pages: fast  71, naive  71
k = 6,  9 pages: fast  51, naive  51
k = 3,  7 pages: fast 109, naive 109
k = 5, 11 pages: fast 103, naive 103
k = 4, 12 pages: fast 130, naive 130

The miss counts agree even though the two versions break ties between never-requested-again pages differently: by the theorem, every LFD tie-break is optimal.

In C++

The same algorithm with an ordered std::set of (next use, page) pairs, which supports updating a page's key directly instead of leaving stale entries. The program compares OPT with LRU and FIFO on a seeded trace with locality (a working set that drifts slowly over 64 pages).

cpp · try it yourself
#include <cstdio>
#include <deque>
#include <list>
#include <random>
#include <set>
#include <unordered_map>
#include <vector>

int belady(const std::vector<int>& r, int k) {
    int n = r.size(), misses = 0;
    std::vector<int> nxt(n);
    std::unordered_map<int, int> seen;
    for (int t = n - 1; t >= 0; --t) {
        auto it = seen.find(r[t]);
        nxt[t] = it == seen.end() ? n + r[t] : it->second;    // never again: beyond n
        seen[r[t]] = t;
    }
    std::set<std::pair<int, int>> byNext;                      // (next use, page)
    std::unordered_map<int, int> key;                          // page -> its next use
    for (int t = 0; t < n; ++t) {
        int p = r[t];
        auto it = key.find(p);
        if (it != key.end()) byNext.erase({it->second, p});
        else {
            ++misses;
            if ((int)key.size() == k) {
                auto far = std::prev(byNext.end());
                key.erase(far->second);
                byNext.erase(far);
            }
        }
        key[p] = nxt[t];
        byNext.insert({nxt[t], p});
    }
    return misses;
}

int lru(const std::vector<int>& r, int k) {
    std::list<int> order;                                       // front = most recent
    std::unordered_map<int, std::list<int>::iterator> where;
    int misses = 0;
    for (int p : r) {
        auto it = where.find(p);
        if (it != where.end()) order.erase(it->second);
        else {
            ++misses;
            if ((int)where.size() == k) { where.erase(order.back()); order.pop_back(); }
        }
        order.push_front(p);
        where[p] = order.begin();
    }
    return misses;
}

int fifo(const std::vector<int>& r, int k) {
    std::deque<int> q;
    std::set<int> in;
    int misses = 0;
    for (int p : r) {
        if (in.count(p)) continue;
        ++misses;
        if ((int)q.size() == k) { in.erase(q.front()); q.pop_front(); }
        q.push_back(p);
        in.insert(p);
    }
    return misses;
}

int main() {
    std::mt19937 rng(99);
    std::vector<int> r;
    int base = 0;
    for (int t = 0; t < 20000; ++t) {
        if (rng() % 50 == 0) base = (base + 1) % 64;           // the working set drifts
        r.push_back((base + rng() % 12) % 64);                  // 12 hot pages around base
    }
    std::printf("   k     OPT     LRU    FIFO   LRU/OPT  FIFO/OPT\n");
    for (int k : {4, 8, 12, 16}) {
        int o = belady(r, k), l = lru(r, k), f = fifo(r, k);
        std::printf("%4d  %6d  %6d  %6d   %7.3f  %8.3f\n", k, o, l, f, double(l) / o, double(f) / o);
    }
}
   k     OPT     LRU    FIFO   LRU/OPT  FIFO/OPT
   4    8563   13454   13472     1.571     1.573
   8    3137    6907    6978     2.202     2.224
  12     434     899    1521     2.071     3.505
  16     402     434     437     1.080     1.087

On a trace with locality LRU and FIFO stay within a small factor of OPT, far from the worst-case factor kk proved in LRU and FIFO Are k-Competitive. Practise all three rules in Count Cache Misses.

Where Belady's rule stops being optimal

  • Weighted caching. If pages have different fetch costs, furthest-in-future can be bad: evicting a page that is needed late but costs 100 to reload may lose to evicting a cheap page needed soon. The offline problem is still polynomial (it is a minimum-cost flow problem; see Chrobak, Karloff, Payne and Vishwanathan, 1991), but no simple rule solves it.
  • Variable page sizes (web caches holding objects of different sizes): the offline problem becomes NP-hard, and Belady's rule is only a heuristic.
  • In practice. Belady's rule needs the future, but it is the standard yardstick in hardware cache research, and some modern replacement policies (for example Hawkeye, Jain and Lin, 2016) learn to imitate its past decisions.

Test yourself

A cache of size 2 holds pages A and B. The remaining requests are C, A, B, A. Which page does Belady's rule evict for C?

  1. A
  2. B
  3. Either, both are optimal
  4. C is not loaded

What does the exchange lemma in the optimality proof show?

  1. LRU is optimal
  2. Any algorithm can be changed to agree with Belady's rule on one more request without increasing its misses
  3. OPT never misses twice in a row
  4. Every lazy algorithm is optimal

Why can OPT be assumed to be a lazy (demand-paging) algorithm?

  1. Because loading early is forbidden
  2. Because any early load or eviction can be postponed without increasing the number of loads
  3. Because lazy algorithms are faster
  4. Because OPT does not know the future

With the precomputed next-use array and an ordered set of (next use, page) pairs updated in place, what is the running time of Belady's rule on nn requests and cache size kk?

  1. O(nk)O(nk)
  2. O(nlog⁡k)O(n \log k)
  3. O(n2)O(n^2)
  4. O(k2)O(k^2)