TExcelTAD
Home › Online Algorithms & Competitive Analysis › LRU and FIFO Are k-Competitive

LRU and FIFO Are k-Competitive

Part I proved that LRU is kk-competitive with a phase argument (Online Problems and the Competitive Ratio). This lesson generalizes the proof to two whole classes of algorithms, marking algorithms and conservative algorithms, which together contain LRU, FIFO, CLOCK and flush-when-full; tightens it to a strict bound when the caches start empty; and shows that some natural rules, LIFO and LFU, are not competitive at all. The result is due to Sleator and Tarjan (1985); the conservative class is from Young (1994).

Phases

Fix kk and a request sequence σ\sigma. Split σ\sigma greedily into phases: phase 1 starts with σ1\sigma_1, and each phase is the longest block of requests containing at most kk distinct pages. So every phase except possibly the last has exactly kk distinct pages, and the first request of phase i+1i + 1 is a page not requested in phase ii. The partition depends only on σ\sigma and kk, not on any algorithm.

Within a phase, call a page marked once it has been requested in that phase. At the start of each phase all marks are erased.

  • A marking algorithm never evicts a marked page.
  • A conservative algorithm misses at most kk times on any consecutive block of requests with at most kk distinct pages.

LRU is a marking algorithm: during a phase, a marked page has been requested more recently than every unmarked one, so while an unmarked page exists in the cache LRU never picks a marked one (and when all kk cached pages are marked, the next request is a new page and therefore starts a new phase). Flush-when-full (FWF), which empties the whole cache when it is full and a miss occurs, is also marking. FIFO is not marking, but it is conservative: on a block with at most kk distinct pages, a page loaded during the block stays for at least kk more loads, so none of the block's pages is loaded twice. LRU is conservative too.

The theorem

Theorem (Sleator and Tarjan, 1985; Young, 1994). Every marking algorithm and every conservative algorithm ALG satisfies ALG(σ)≤k⋅OPT(σ)+k\mathrm{ALG}(\sigma) \le k \cdot \mathrm{OPT}(\sigma) + k for all σ\sigma when ALG and OPT start with the same cache contents. If both start with an empty cache, ALG(σ)≤k⋅OPT(σ)\mathrm{ALG}(\sigma) \le k \cdot \mathrm{OPT}(\sigma) (strictly kk-competitive).

Proof

Let mm be the number of phases.

ALG misses at most kk times per phase. For a conservative algorithm this is the definition, since a phase has at most kk distinct pages. For a marking algorithm: once a page is requested in the phase it is marked and stays in the cache until the phase ends, so each of the phase's at most kk distinct pages misses at most once. Hence ALG≤km\mathrm{ALG} \le k m.

OPT misses at least once per window. For phase i<mi < m, let the window WiW_i run from the second request of phase ii to the first request of phase i+1i + 1. Let pp be the first request of phase ii. WiW_i contains requests to at least kk distinct pages different from pp (the other k−1k - 1 pages of phase ii and the new page that starts phase i+1i + 1). Right after serving pp, OPT holds pp and at most k−1k - 1 other pages, so it misses at least once in WiW_i. The windows are disjoint, so OPT≥m−1\mathrm{OPT} \ge m - 1, which gives ALG≤km≤k OPT+k\mathrm{ALG} \le km \le k\,\mathrm{OPT} + k.

Empty start. If m=1m = 1, ALG misses only on the first request of each distinct page, and so does OPT: ALG=OPT\mathrm{ALG} = \mathrm{OPT}. If m≥2m \ge 2, phase 1 has kk distinct pages, each a compulsory miss for OPT, all at positions before window W2W_2. With windows W2,…,Wm−1W_2, \ldots, W_{m-1} this gives OPT≥k+(m−2)\mathrm{OPT} \ge k + (m - 2), and km≤k(k+m−2)km \le k(k + m - 2) holds for k≥2k \ge 2. (For k=1k = 1 every algorithm misses on every change of page, so ALG=OPT\mathrm{ALG} = \mathrm{OPT}.)

Phases on a concrete sequence

The animation runs LRU with three slots on 20 requests. The program splits the same sequence into phases and counts the misses of LRU, FIFO and FWF in each phase; every count is at most k=3k = 3.

python · try it yourself
def phases(reqs, k):
    out, cur = [], []
    for p in reqs:
        if p not in cur and len(set(cur)) == k:
            out.append(cur)
            cur = []
        cur.append(p)
    return out + [cur]

def run(reqs, k, policy):
    cache, misses_at = [], []
    for t, p in enumerate(reqs):
        if p in cache:
            if policy == "lru":
                cache.remove(p)
                cache.append(p)
        else:
            misses_at.append(t)
            if len(cache) == k:
                if policy == "fwf":
                    cache = []                 # flush everything
                else:
                    cache.pop(0)               # lru: least recent; fifo: oldest load
            cache.append(p)
    return misses_at

reqs = "A B A C D A B D C E C A B E D B A C A E".split()
k = 3
ph = phases(reqs, k)
starts = [sum(len(x) for x in ph[:i]) for i in range(len(ph))]
print("phases:", " | ".join(" ".join(x) for x in ph))
for policy in ["lru", "fifo", "fwf"]:
    m = run(reqs, k, policy)
    per = [sum(s <= t < s + len(x) for t in m) for s, x in zip(starts, ph)]
    print(f"{policy.upper():4} {len(m):2} misses, per phase {per}")
print(f"{len(ph)} phases: OPT >= {len(ph) - 1} after the first, and ALG <= k * phases = {k * len(ph)}")
phases: A B A C | D A B D | C E C A | B E D B | A C A E
LRU  14 misses, per phase [3, 2, 3, 3, 3]
FIFO 14 misses, per phase [3, 3, 3, 2, 3]
FWF  15 misses, per phase [3, 3, 3, 3, 3]
5 phases: OPT >= 4 after the first, and ALG <= k * phases = 15

The phases contain exactly 3 distinct pages each (the last one may have fewer). FWF is the crudest marking algorithm, and here it misses exactly 3 times per phase; LRU and FIFO sometimes keep a page from the previous phase that is requested again.

In C++

LRU in O(1)O(1) per request (a list ordered by recency plus a hash map from pages to list positions), the standard way to implement it; practise the same structure in LRU Cache. The program checks the strict bound LRU≤k⋅OPT\mathrm{LRU} \le k \cdot \mathrm{OPT} and the per-phase bound on a long seeded sequence over 10 pages.

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

struct LRU {
    int k;
    std::list<int> order;                                     // front = most recent
    std::unordered_map<int, std::list<int>::iterator> pos;
    bool access(int p) {                                      // returns true on a miss
        auto it = pos.find(p);
        bool miss = it == pos.end();
        if (!miss) order.erase(it->second);
        else if ((int)pos.size() == k) { pos.erase(order.back()); order.pop_back(); }
        order.push_front(p);
        pos[p] = order.begin();
        return miss;
    }
};

int opt(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) { nxt[t] = seen.count(r[t]) ? seen[r[t]] : n + r[t]; seen[r[t]] = t; }
    std::set<std::pair<int, int>> s;
    std::unordered_map<int, int> key;
    for (int t = 0; t < n; ++t) {
        if (key.count(r[t])) s.erase({key[r[t]], r[t]});
        else {
            ++misses;
            if ((int)key.size() == k) { auto f = std::prev(s.end()); key.erase(f->second); s.erase(f); }
        }
        key[r[t]] = nxt[t];
        s.insert({nxt[t], r[t]});
    }
    return misses;
}

int main() {
    std::mt19937 rng(5);
    std::vector<int> r(5000);
    for (int& p : r) p = rng() % 10;
    for (int k : {2, 4, 6, 8}) {
        LRU cache{k, {}, {}};
        int misses = 0, worst_phase = 0, in_phase = 0;
        std::set<int> distinct;
        for (int p : r) {
            if (!distinct.count(p) && (int)distinct.size() == k) { distinct.clear(); in_phase = 0; }
            distinct.insert(p);
            if (cache.access(p)) { ++misses; ++in_phase; }
            if (in_phase > worst_phase) worst_phase = in_phase;
        }
        int o = opt(r, k);
        std::printf("k = %d: LRU %4d, OPT %4d, ratio %.3f, k * OPT = %5d, most misses in a phase %d\n",
                    k, misses, o, double(misses) / o, k * o, worst_phase);
    }
}
k = 2: LRU 3978, OPT 3179, ratio 1.251, k * OPT =  6358, most misses in a phase 2
k = 4: LRU 2981, OPT 1805, ratio 1.652, k * OPT =  7220, most misses in a phase 4
k = 6: LRU 1997, OPT  971, ratio 2.057, k * OPT =  5826, most misses in a phase 6
k = 8: LRU  996, OPT  394, ratio 2.528, k * OPT =  3152, most misses in a phase 8

Not every rule is competitive

Two rules that sound reasonable have no bounded ratio.

  • LIFO (evict the page loaded most recently): with pages 1,…,k+11, \ldots, k + 1, request 1,2,…,k1, 2, \ldots, k, then alternate k+1,k,k+1,k,…k + 1, k, k + 1, k, \ldots. LIFO evicts kk to load k+1k + 1 and then k+1k + 1 to load kk, missing on every request, while OPT misses once.
  • LFU (evict the least frequently requested page): request each of pages 1,…,k−11, \ldots, k - 1 many times (NN times each), then alternate between two fresh pages aa and bb, NN times each. LFU keeps the k−1k - 1 heavy pages forever and evicts aa for bb and bb for aa, missing on every alternating request, while OPT evicts the dead heavy pages once.
python · try it yourself
def simulate(reqs, k, policy):
    cache, freq, loaded, misses = [], {}, {}, 0
    for t, p in enumerate(reqs):
        freq[p] = freq.get(p, 0) + 1
        if p in cache:
            continue
        misses += 1
        if len(cache) == k:
            if policy == "lifo":
                victim = max(cache, key=lambda q: loaded[q])
            else:                                       # lfu, ties: oldest load
                victim = min(cache, key=lambda q: (freq[q], loaded[q]))
            cache.remove(victim)
        cache.append(p)
        loaded[p] = t
    return misses

def opt(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

k = 4
for N in [10, 50, 200]:
    lifo_seq = list(range(1, k + 1)) + [k + 1, k] * N
    lfu_seq = [p for p in range(1, k) for _ in range(N + 1)] + ["a", "b"] * N
    print(f"N = {N:3}: LIFO {simulate(lifo_seq, k, 'lifo'):4} vs OPT {opt(lifo_seq, k)}   "
          f"LFU {simulate(lfu_seq, k, 'lfu'):4} vs OPT {opt(lfu_seq, k)}")
N =  10: LIFO   24 vs OPT 5   LFU   23 vs OPT 5
N =  50: LIFO  104 vs OPT 5   LFU  103 vs OPT 5
N = 200: LIFO  404 vs OPT 5   LFU  403 vs OPT 5

The online cost grows linearly with NN while OPT stays constant, so no constant cc works. Both rules violate the marking property: they evict a page requested in the current phase while keeping one that is not.

Test yourself

Which of these is a marking algorithm?

  1. FIFO
  2. LRU
  3. LIFO
  4. LFU

In the phase argument, why does OPT miss at least once in each window WiW_i?

  1. Because every phase starts with a miss for every algorithm
  2. Because the window requests at least kk distinct pages other than the phase's first page pp, and OPT holds pp plus only k−1k - 1 others
  3. Because OPT is lazy
  4. Because LRU misses kk times

A request sequence splits into 40 phases for k=5k = 5. What is the best upper bound on the misses of a marking algorithm, and the lower bound on OPT?

  1. 200200 and 3939
  2. 4040 and 4040
  3. 200200 and 200200
  4. 55 and 11

Why is LFU not competitive?

  1. It is randomized
  2. Pages that were popular long ago keep high counts and are never evicted, so an alternation between two new pages misses every time
  3. It uses too much memory
  4. It is a marking algorithm