TExcelTAD
Home › Selected Topics: FFT, Strings, Parallelism & NP-Completeness › Online Problems and the Competitive Ratio

Online Problems and the Competitive Ratio

Every algorithm so far received its whole input before it started. Many real decisions are not like that. A cache must decide which page to evict now, without knowing the future requests; a scheduler must place a job when it arrives; a ski renter must decide each morning whether to buy. These are online problems: the input arrives piece by piece, and each decision is final. This lesson defines how to measure an online algorithm, the competitive ratio, and applies it to the most studied online problem, paging.

Online versus offline

An online algorithm receives a request sequence σ=σ1,σ2,…\sigma = \sigma_1, \sigma_2, \ldots one request at a time and must serve σt\sigma_t before seeing σt+1\sigma_{t+1}. The offline optimum OPT(σ)\mathrm{OPT}(\sigma) is the least cost of serving the whole sequence by someone who knows it in advance. No online algorithm can match OPT on every input, because OPT can tailor its choices to the future. The question is how much is lost.

An online algorithm ALG is cc-competitive if there is a constant aa such that for every request sequence σ\sigma

ALG(σ)≤c⋅OPT(σ)+a.\mathrm{ALG}(\sigma) \le c \cdot \mathrm{OPT}(\sigma) + a .

If this holds with a=0a = 0, ALG is strictly cc-competitive. The smallest such cc is the competitive ratio of ALG. It is a worst-case measure over all inputs: think of an adversary who knows the algorithm and picks the sequence that hurts it most. For a deterministic algorithm the adversary can simulate it and always knows its next move; randomized algorithms are measured against an oblivious adversary who knows the algorithm but not its coin flips.

Paging

A cache holds kk pages of a larger set. Each request names a page; if the page is in the cache it is a hit (cost 0), otherwise a miss (cost 1): the page is loaded and, if the cache is full, some page must be evicted. The cost is the number of misses. Three eviction rules:

  • LRU (least recently used): evict the page whose last request is oldest.
  • FIFO (first in, first out): evict the page that was loaded earliest.
  • OPT, Belady's rule: evict the page whose next request is furthest in the future (or never comes). It needs the future, so it is offline, and Belady proved in 1966 that it minimises the number of misses.

The animation runs LRU on twelve requests with three slots; switch to OPT by reading on.

The program serves the same requests with each rule and prints the same decisions as the animation (requests numbered from 1).

python · try it yourself
def serve(requests, k, policy):
    cache, last_use, loaded, log, misses = [None] * k, {}, {}, [], 0
    for t, page in enumerate(requests):
        if page in cache:
            log.append(f"{page}: hit")
        else:
            misses += 1
            if None in cache:
                slot = cache.index(None)
                log.append(f"{page}: miss, free slot")
            else:
                if policy == "lru":
                    key = lambda i: last_use[cache[i]]
                    slot = min(range(k), key=key)
                elif policy == "fifo":
                    slot = min(range(k), key=lambda i: loaded[cache[i]])
                else:                                   # opt: furthest next use
                    def next_use(i):
                        rest = requests[t + 1:]
                        return rest.index(cache[i]) if cache[i] in rest else len(requests)
                    slot = max(range(k), key=next_use)  # first slot among ties
                log.append(f"{page}: miss, evict {cache[slot]}")
            cache[slot] = page
            loaded[page] = t
        last_use[page] = t
    return misses, log

requests = list("ABCADBEACBDE")
for policy in ["lru", "fifo", "opt"]:
    misses, log = serve(requests, 3, policy)
    print(f"{policy.upper():4} {misses:2} misses:", "; ".join(log[3:]))
LRU  11 misses: A: hit; D: miss, evict B; B: miss, evict C; E: miss, evict A; A: miss, evict D; C: miss, evict B; B: miss, evict E; D: miss, evict A; E: miss, evict C
FIFO 10 misses: A: hit; D: miss, evict A; B: hit; E: miss, evict B; A: miss, evict C; C: miss, evict D; B: miss, evict E; D: miss, evict A; E: miss, evict C
OPT   7 misses: A: hit; D: miss, evict C; B: hit; E: miss, evict D; A: hit; C: miss, evict A; B: hit; D: miss, evict C; E: hit

LRU misses 11 times and OPT only 7. The animation with "policy": "opt" shows Belady's choices:

LRU is kk-competitive

Theorem (Sleator and Tarjan, 1985). LRU and FIFO are kk-competitive for paging with a cache of kk pages.

Proof sketch for LRU

Cut the request sequence into phases: phase 1 starts at the first request, and each phase is the longest stretch that requests at most kk distinct pages; the next request (a (k+1)(k+1)-st distinct page) starts the next phase.

LRU misses at most kk times per phase. Once a page is requested within a phase, it is among the kk most recently used pages for the rest of that phase (only kk distinct pages are requested in it), so LRU never evicts it before the phase ends. Each of the at most kk distinct pages of the phase can therefore miss at most once.

OPT misses at least once per phase after the first. Take phase i≥1i \ge 1 and let pp be its first request. From the second request of phase ii to the first request of phase i+1i + 1 inclusive, at least kk distinct pages other than pp are requested. Right after serving pp, OPT holds pp and only k−1k - 1 other pages, so it misses at least once in that window. The windows of different phases are disjoint.

So with mm phases, LRU≤km\mathrm{LRU} \le km and OPT≥m−1\mathrm{OPT} \ge m - 1, which gives LRU≤k⋅OPT+k\mathrm{LRU} \le k \cdot \mathrm{OPT} + k.

No deterministic algorithm does better

The matching lower bound is a pure adversary argument. Use only k+1k + 1 distinct pages. After the cache fills, exactly one of them is missing from the cache at any time, and the adversary always requests that page. Every request is a miss for the online algorithm. OPT, facing the same sequence, evicts the page whose next request is furthest away; at least k−1k - 1 other requests come before that page is needed again, so OPT misses at most once every kk requests.

python · try it yourself
def opt_misses(requests, k):
    cache, misses = set(), 0
    for t, page in enumerate(requests):
        if page in cache:
            continue
        misses += 1
        if len(cache) == k:
            rest = requests[t + 1:]
            far = max(cache, key=lambda p: rest.index(p) if p in rest else len(rest))
            cache.remove(far)
        cache.add(page)
    return misses

def adversary(evict, k, length):
    """build the worst sequence for a deterministic eviction rule over k + 1 pages"""
    pages = list(range(k + 1))
    cache, requests = list(range(k)), list(range(k))
    for t in range(length):
        page = next(p for p in pages if p not in cache)   # the one page not cached
        requests.append(page)
        victim = evict(cache, requests)
        cache[cache.index(victim)] = page
    return requests

def lru(cache, requests):                 # least recently used, before the new request
    past = requests[:-1]
    return min(cache, key=lambda p: max(i for i, q in enumerate(past) if q == p))

def mru(cache, requests):                 # most recently used, before the new request
    past = requests[:-1]
    return max(cache, key=lambda p: max(i for i, q in enumerate(past) if q == p))

for k in [2, 4, 8]:
    for name, rule in [("LRU", lru), ("MRU", mru)]:
        seq = adversary(rule, k, 240)
        alg = 240 + k                     # every request misses (k cold misses first)
        opt = opt_misses(seq, k)
        print(f"k = {k}, {name:6}: ALG {alg} misses, OPT {opt:3}, ratio {alg / opt:.2f}")
k = 2, LRU   : ALG 242 misses, OPT 122, ratio 1.98
k = 2, MRU   : ALG 242 misses, OPT   3, ratio 80.67
k = 4, LRU   : ALG 244 misses, OPT  64, ratio 3.81
k = 4, MRU   : ALG 244 misses, OPT   5, ratio 48.80
k = 8, LRU   : ALG 248 misses, OPT  38, ratio 6.53
k = 8, MRU   : ALG 248 misses, OPT   9, ratio 27.56

Against LRU the ratio approaches kk as the sequence grows (OPT's kk cold misses still weigh on the short run for k=8k = 8). Evicting the most recently used page is far worse: the adversary just alternates between two pages, which OPT keeps in the cache. Whatever deterministic rule the cache uses, the ratio is at least about kk. Randomization helps: the marking algorithm, which evicts a random page among those not requested recently, is 2Hk2H_k-competitive against an oblivious adversary (Hk=1+12+⋯+1k≈ln⁡kH_k = 1 + \frac{1}{2} + \cdots + \frac{1}{k} \approx \ln k), exponentially better than kk. That and much more is in the Part II course Online Algorithms & Competitive Analysis.

In C++

LRU and OPT in C++ on a longer request sequence with locality (a fixed pseudo-random walk over 12 pages), for several cache sizes. Unlike the adversarial sequences, a trace with locality gives LRU ratios far below kk.

cpp · try it yourself
#include <algorithm>
#include <cstdio>
#include <vector>

int lru(const std::vector<int>& req, int k) {
    std::vector<int> cache;                       // front = least recently used
    int misses = 0;
    for (int p : req) {
        auto it = std::find(cache.begin(), cache.end(), p);
        if (it != cache.end()) cache.erase(it);
        else { misses++; if ((int)cache.size() == k) cache.erase(cache.begin()); }
        cache.push_back(p);
    }
    return misses;
}

int opt(const std::vector<int>& req, int k) {
    std::vector<int> cache;
    int misses = 0;
    for (size_t t = 0; t < req.size(); t++) {
        if (std::find(cache.begin(), cache.end(), req[t]) != cache.end()) continue;
        misses++;
        if ((int)cache.size() == k) {
            size_t best = 0, far = 0;
            for (size_t i = 0; i < cache.size(); i++) {
                size_t next = t + 1;
                while (next < req.size() && req[next] != cache[i]) next++;
                if (next > far) { far = next; best = i; }
            }
            cache.erase(cache.begin() + best);
        }
        cache.push_back(req[t]);
    }
    return misses;
}

int main() {
    std::vector<int> req;
    unsigned x = 12345;
    int page = 0;
    for (int t = 0; t < 2000; t++) {              // a fixed walk: mostly nearby pages
        x = x * 1103515245u + 12345u;
        int step = int((x >> 16) % 5) - 2;
        page = (page + step + 12) % 12;
        req.push_back(page);
    }
    std::printf(" k   LRU   OPT  ratio\n");
    for (int k : {2, 3, 4, 6, 8})
        std::printf("%2d %5d %5d  %.2f\n", k, lru(req, k), opt(req, k), (double)lru(req, k) / opt(req, k));
}
 k   LRU   OPT  ratio
 2  1159   988  1.17
 3   903   726  1.24
 4   755   562  1.34
 6   558   343  1.63
 8   401   191  2.10

The gap between the worst case kk and these ratios is typical of competitive analysis: it guards against every input, so it can be pessimistic for the inputs that actually occur. It still says something real: no deterministic rule is safe against a request pattern that cycles through just one page more than the cache holds, and LRU's behaviour on loops larger than the cache is a well-known performance cliff. The Page Replacement lesson of the Operating Systems course shows how real kernels approximate LRU. Practise with Count Cache Misses.

Test yourself

An online algorithm is cc-competitive if, for every request sequence σ\sigma,

  1. ALG(σ)≤c\mathrm{ALG}(\sigma) \le c
  2. ALG(σ)≤c⋅OPT(σ)+a\mathrm{ALG}(\sigma) \le c \cdot \mathrm{OPT}(\sigma) + a for a constant aa
  3. OPT(σ)≤c⋅ALG(σ)\mathrm{OPT}(\sigma) \le c \cdot \mathrm{ALG}(\sigma)
  4. the average cost over random sequences is at most c⋅OPTc \cdot \mathrm{OPT}

With a cache of kk pages, which request pattern forces every deterministic paging algorithm to miss on every request?

  1. Requests for kk distinct pages in a cycle
  2. Always requesting the one page, out of k+1k + 1, that is not in the cache
  3. Requests in sorted order
  4. Random requests

On the requests A B C A D B E A C B D E with 3 slots, how many misses does OPT have?

  1. 5
  2. 7
  3. 9
  4. 11

What does Belady's rule evict?

  1. The least recently used page
  2. The page loaded first
  3. The page whose next request is furthest in the future
  4. A random page