Part VII · Selected Topics Chapter 27

Online Algorithms

Deciding without knowing the future, and measuring how much that costs against an opponent who knew it all along.

Every algorithm so far received its whole input before producing an answer. An online algorithm gets the input piece by piece and must commit to a decision on each piece before seeing the rest, with no chance to revise. Cache eviction, elevator dispatch, and ski rental are all like this. Since you cannot expect optimality, the field measures quality differently: by the competitive ratio, the worst-case ratio between what the online algorithm spends and what an omniscient offline algorithm would have spent.

4th edition note. This chapter is new. Offline caching, its natural companion, appears in Chapter 15 as an application of greedy algorithms.

Contents

  1. Online versus offline
  2. The competitive ratio
  3. Ski rental
  4. Online caching
  5. A lower bound for deterministic caching
  6. Randomization helps
  7. Other online problems
  8. Recap

Online versus offline

OfflineOnline
InputAvailable in full before startingArrives one request at a time
DecisionsMade with complete knowledgeCommitted irrevocably, one per request
GoalThe optimumStay within a bounded factor of the optimum
Measured byRunning timeCompetitive ratio
The difficulty is informational, not computational. An online algorithm may have unlimited time and still be unable to match the offline optimum, because the information it needs has not arrived yet. That is a different kind of hardness from anything in Chapter 34.

The competitive ratio

An online algorithm A is c-competitive if there is a constant k such that for every request sequence σ,
costₐ(σ) ≤ c · costOPT(σ) + k

where OPT is the optimal offline algorithm. The additive constant k forgives startup effects; when k = 0 the algorithm is strictly c-competitive.

This is a worst-case, adversarial measure. The bound must hold for every sequence, including one designed by an adversary who knows your algorithm. It is not an average over typical inputs, which is why competitive ratios often look pessimistic compared with observed behaviour. It is the same distinction as worst-case versus average-case from Chapter 2, applied to a different resource.

Ski rental

The smallest interesting example, and the one that teaches the technique.

You are learning to ski. Renting costs £1 per day; buying costs £B once. Each morning you might quit for good, and you do not know when. Rent or buy?

The break-even strategy: rent for B - 1 days, then buy on day B. This is 2-competitive, and no deterministic algorithm does better.

Why 2: if you quit before day B, you paid exactly the optimum. If you reach day B, you have paid B - 1 in rent plus B to buy, total 2B - 1, while the optimum is B. The ratio is (2B-1)/B < 2.

Why no deterministic algorithm beats 2: an adversary watches for the day you buy and ends the season immediately afterwards, making your purchase worthless. Buying earlier makes that waste relatively larger; buying later means more rent paid before it.

The rent-or-buy pattern is everywhere. Cache versus recompute, lease versus purchase, keep a TCP connection alive versus reopen it, spin versus block on a lock. Whenever a recurring small cost can be replaced by a one-off large one and you do not know how long the need will last, this is the analysis, and 2-competitive is the answer.

Online caching

The chapter’s main problem. A cache holds k pages. Requests arrive one at a time. A hit is free; a miss requires fetching the page and, if the cache is full, evicting one. Minimise misses.

Chapter 15 established the offline optimum: Belady’s rule, evict the page whose next request is furthest in the future. Online, that information does not exist.

PolicyEvictsCompetitive ratio
LRU (least recently used)The page unused for longestk
FIFOThe page loaded earliestk
LIFOThe page loaded most recentlyNot competitive at all
LFU (least frequently used)The page requested fewest timesNot competitive
Belady (offline)Furthest next use1, by definition
LRU is k-competitive, where k is the cache size. The proof partitions the request sequence into phases, each containing requests to exactly k distinct pages. LRU incurs at most k misses in a phase; the optimal algorithm must incur at least one, because each new phase introduces a page not in the cache at the phase boundary. Ratio k.
LFU is not competitive, and the reason is instructive. A page requested a million times last year but never since keeps its high count forever and is never evicted. Frequency without decay is a trap. Real systems use aged or windowed variants precisely to avoid this.

A lower bound for deterministic caching

Theorem. No deterministic online caching algorithm is better than k-competitive. So LRU and FIFO are optimal among deterministic policies.

The adversary argument is short and worth knowing. Restrict attention to k + 1 distinct pages, so the cache can never hold them all. The adversary simulates the algorithm and, at each step, requests the one page not currently cached. The online algorithm therefore misses on every single request.

Meanwhile the offline optimum, using Belady, misses at most once every k requests: when it evicts the page whose next use is furthest away, that page is not requested again for at least k steps. Ratio: k.

This is a lower bound on the problem, not on a particular algorithm — the same shape of argument as the Ω(n lg n) sorting bound in Chapter 8. No amount of cleverness gets a deterministic policy below k. The only way out is to stop being deterministic.

Randomization helps

The adversary above depends on predicting exactly which page the algorithm holds. Randomize and it cannot.

The MARKER algorithm: give each cached page a mark bit, all initially clear. On a request, if the page is cached, mark it. On a miss, if every page is marked, clear all marks and start a new phase; then evict a page chosen uniformly at random from the unmarked pages, insert the requested page, and mark it.
MARKER is 2Hₖ-competitive, where Hₖ = 1 + 1/2 + … + 1/k ≈ ln k
Cache size kDeterministic boundRandomized bound ≈ 2 ln k
1010~5.9
100100~10.4
10001000~15
Randomization converts a bound that grows linearly in k into one that grows logarithmically. The mechanism is the same as randomized quicksort in Chapter 7: the adversary must fix the input before seeing your coin flips, so it can no longer target you specifically. The competitive ratio becomes an expected ratio, against an oblivious adversary that knows your algorithm but not its random choices.

Other online problems

ProblemQuestionKnown result
List updateReorder a linked list to speed future searchesMove-to-front is 2-competitive
Load balancingAssign arriving jobs to m machinesGreedy least-loaded is (2 - 1/m)-competitive
Bin packingPack arriving items into fewest binsFirst-fit is 1.7-competitive
k-serverMove k servers to serve requests in a metric spaceGeneralises caching; the k-server conjecture is still open
Secretary problemHire the best candidate, one irrevocable choiceSkip n/e, succeed with probability 1/e (Chapter 5)
Move-to-front deserves a note. On every access, move the accessed element to the front of the list. It is 2-competitive against an optimal offline reordering, adapts automatically to changing access patterns, and needs no counters or timestamps. It is the same instinct as LRU, and it is why self-organising lists appear in real caches and compression algorithms.

Recap

The seven things to carry forward

Where this goes next

Chapter 28 returns to concrete computation with matrix operations: solving systems of linear equations by LU decomposition, inverting matrices, and least-squares approximation — the numerical core that Chapter 29’s linear programming and Chapter 33’s machine learning both stand on.


Ch 26 — Parallel Algorithms Ch 28 — Matrix Operations