Section 14.20

Memoization and caching

Definition

Memoization is storing each function call’s result, keyed by the call’s arguments, so that a later call with the same arguments returns the stored result instead of recomputing it. Caching is the general practice of keeping a computed or fetched result where it is quicker to reach; memoization is caching of function results. The difference that matters is the key: memoization keys by arguments alone, which is correct only for a function that reads nothing else; a general cache needs a key covering everything its result depends on.

The idea

The Fibonacci numbers show the gain. Each is the sum of the two before it: fib(0)=0\mathrm{fib}(0) = 0, fib(1)=1\mathrm{fib}(1) = 1 and fib(n)=fib(n−1)+fib(n−2)\mathrm{fib}(n) = \mathrm{fib}(n-1) + \mathrm{fib}(n-2). Computed straight from this definition, fib(30)\mathrm{fib}(30) takes 2,692,537 calls, because smaller values are recomputed again and again: fib(28)\mathrm{fib}(28) twice, fib(27)\mathrm{fib}(27) three times, fib(26)\mathrm{fib}(26) five times. With memoization each of the 31 values fib(0)\mathrm{fib}(0) to fib(30)\mathrm{fib}(30) is computed once, in 59 calls. Systems gain in the same way when a file is parsed once, a name looked up once, or a program checked once and the verdict reused.

A stored result is a conclusion drawn from premises, the facts the computation read. Reusing it is valid while every premise still holds. The key records the premises that vary between calls; every premise not in the key must be kept unchanged by other means. A pure function, one whose result depends only on its arguments and which changes nothing else, has its arguments as its only premises, so its stored results never go stale, meaning out of date. A parse, a lookup or a verification usually also reads the parser’s version, a table’s contents or the checker’s rules. Each such premise must be in the key, or a change to it must remove the results that relied on it.

How it works

A memoized or cached computation has these parts.

A lookup goes as follows.

  1. Build the key from the arguments and from every other premise the result depends on, such as a version number.

  2. Look the key up in the table. If an entry is found, compare its stored key with the new key in full; on a match, return the stored result. This is a hit.

  3. Otherwise, on a miss, compute the result, store it under the key, evicting an entry first if the table is full, and return the result.

A premise that can change is handled in one of two ways. The first puts a version number of the premise into the key: a change increases the number, old entries never match again, and eviction removes them later. The second keeps the premise out of the key and, on each change, deletes every entry that relied on that premise; the cache invalidation §14.21 entry treats this. Discarding entries after a fixed time, a third practice, bounds how long a stale result can be served but does not prevent it.

Worked example

Memoized fib(5)\mathrm{fib}(5). Every computed value, fib(0)\mathrm{fib}(0) and fib(1)\mathrm{fib}(1) included, is stored. fib(5)\mathrm{fib}(5) calls fib(4)\mathrm{fib}(4), which calls fib(3)\mathrm{fib}(3), which calls fib(2)\mathrm{fib}(2), which calls fib(1)=1\mathrm{fib}(1) = 1 and fib(0)=0\mathrm{fib}(0) = 0; then fib(2)=1+0=1\mathrm{fib}(2) = 1 + 0 = 1 is stored. Back in fib(3)\mathrm{fib}(3), the second call, fib(1)\mathrm{fib}(1), is a hit, so fib(3)=1+1=2\mathrm{fib}(3) = 1 + 1 = 2. In fib(4)\mathrm{fib}(4), the second call, fib(2)\mathrm{fib}(2), is a hit: fib(4)=2+1=3\mathrm{fib}(4) = 2 + 1 = 3. In fib(5)\mathrm{fib}(5), the second call, fib(3)\mathrm{fib}(3), is a hit: fib(5)=3+2=5\mathrm{fib}(5) = 3 + 2 = 5. That is 9 calls: 6 computations and 3 hits. Without memoization, let C(n)C(n) be the number of calls needed for fib(n)\mathrm{fib}(n). Then C(0)=C(1)=1C(0) = C(1) = 1 and C(n)=1+C(n−1)+C(n−2)C(n) = 1 + C(n-1) + C(n-2), so C(2)=3C(2) = 3, C(3)=5C(3) = 5, C(4)=9C(4) = 9 and C(5)=15C(5) = 15.

A key that misses a premise. A checker examines programs before they run. One program calls a library routine fill and passes it a 16-byte buffer. Version 1 of the library documents that fill writes at most 8 bytes, so the checker accepts the call, since 8≤168 \le 16, and stores the verdict accept under a key computed from the program’s bytes alone. Version 2 of the library changes fill to write up to 32 bytes. The program’s bytes are unchanged, so its key is unchanged, and the next check is a hit that returns accept. The correct verdict is now reject: the call can write 32−16=1632 - 16 = 16 bytes past the end of the buffer.

The repair adds the library’s contract to the key, as the library’s version number or as a cryptographic hash §5.1 (a fixed-length fingerprint that, in practice, differs whenever the data differs) of the contract text. With version 2 the key differs, the lookup misses, and the checker recomputes and rejects. No hash of the program’s bytes, however strong, could have caught the change, because the changed premise was not among the hashed bytes.

Stated precisely

Write the computation as r=f(x,c)r = f(x, c), where xx is the explicit input (the arguments); cc is the context, meaning every other value the computation reads, such as code versions, configuration, stored data, the contracts of routines it calls and the time; and rr is the result. A cache entry holds a key k=key(x,c)k = \mathrm{key}(x, c) and the result rr computed when the entry was stored. A later lookup with input x′x' in context c′c' that produces the same key returns rr. That reuse is correct when f(x′,c′)=f(x,c)f(x', c') = f(x, c).

A cache returns only correct results when the key determines the result: for all inputs and contexts, key(x,c)=key(x′,c′)\mathrm{key}(x, c) = \mathrm{key}(x', c') implies f(x,c)=f(x′,c′)f(x, c) = f(x', c'). Three conditions give this.

  1. Determinism. ff gives the same result whenever xx and cc are the same; it reads no clock, random number or other value that cc does not include.

  2. Coverage. Every part of cc that can affect the result is in the key, or is guaranteed not to change while the entry exists; invalidation provides that guarantee.

  3. Exact comparison. Keys are compared in full, or through a collision-resistant §5.5 cryptographic hash, one for which finding two different inputs with the same hash is infeasible. The short hash a hash table uses is not enough on its own, because two different keys can share it.

For a pure function, cc is empty, the arguments are the whole key, and entries never go stale. Eviction never breaks correctness, because a discarded entry is simply recomputed; keeping an entry whose premises have changed does break it.

Resolving a lookup once

A common systems form of memoization resolves a lookup by name once and keeps the result. Take a program that, for every incoming event, finds five tables by name: it formats a name string such as limits:conn42 and looks the string up in a hash table, which means building the string, hashing it (computing a number from its characters) and comparing it with stored names. The set of tables changes only when a new configuration is loaded. So the program can look up all five names once, at loading time, and store the five resulting pointers (memory addresses) in a small structure, called here a resolved view. Each event then follows a pointer directly.

The resolved view holds memoized lookup results whose hidden premise is the configuration they were resolved against. It costs its own size for each configuration alive at the same time: with 4-byte pointers, five pointers take 5×4=205 \times 4 = 20 bytes, plus any bookkeeping the memory allocator adds. During a switch the old and the new configuration are both alive, so two views exist for a while.

The view must be replaced together with the tables it points into, as one unit. If the tables are replaced and freed while the old view is kept, the view points to freed memory, a use-after-free §4.6. If the view is replaced before the new tables are ready, readers follow pointers to tables that do not exist yet. The standard pattern puts the tables and their view in one structure and publishes a new structure by changing a single pointer with an atomic operation §9.8, one that other threads see either not at all or completely. The old structure is freed only after every reader that might still use it has finished, a wait called a grace period §9.21 in read-copy update §9.20 (RCU).

Limits and common mistakes

Memory grows with every distinct key. A cache keyed by input that an attacker chooses, with no eviction policy and no bound on the number of entries, lets the attacker fill memory.

Hits are faster than misses, so the time a request takes can reveal whether the same request was made recently. That is a side channel §1.29: information leaking through a measurable effect other than the output.

A time limit on an entry bounds how long a stale result is served; it does not make the result correct during that time. A known change must remove the entries that depend on it at once.

Memoizing a function that has side effects, such as writing a log or sending a message, skips those effects on every hit. A table that hands out the stored object itself, instead of a copy, lets one caller’s change to that object reach every later hit.

Two threads that miss on the same key at the same time compute the result twice, which for a deterministic ff only wastes time. A worse race stores a stale result: a thread computes from old data, the data changes and the dependent entries are deleted, and then the thread stores its old result. Recording the data’s version when the computation starts, and storing only if that version is still current, prevents this.

Questions answered

What changes invalidate a cached parse, lookup, or proof?

A cached parse, lookup or proof becomes invalid when anything the result depended on changes and that thing is not part of the cache key, the value used to find the stored result. A key that includes the changed item turns the change into a miss automatically; every other change must be matched by deleting the entries that relied on it. The usual dependencies are these.

A change to something the result does not depend on invalidates nothing. Concluding that a result does not depend on something requires a complete record of what the result read; when that record may be incomplete, discarding all entries is safe, because a discarded entry costs only the time to compute it again.

Related entries: Graph reachability search (§14.18), Cache invalidation (§14.21), Security claim scope (§1.45).