OCR H446, section 2.1.2 (c)
Caching means keeping a copy of data or a result that is likely to be needed again, somewhere it can be reached more quickly, so that it doesn't have to be fetched or calculated again. It is a thinking ahead technique: you predict what will be needed, and prepare it.
The idea
- A cache hit is when the data is in the cache.
- A cache miss is when it isn't, and the slow route must be taken.
Examples
| Where | What is cached | Benefit |
|---|---|---|
| Processor (CPU) cache | Recently used instructions and data, copied from RAM into small, fast memory | The processor waits less for RAM |
| Web browser | Images, scripts and pages already downloaded | Pages load faster and use less bandwidth |
| DNS | The IP address for a recently used website name | Avoids repeating a lookup |
| Web server or CDN | Ready-made pages or popular content stored near users | Less load on the main server, faster delivery |
| Database | The results of frequent queries | Fewer slow disk reads |
| Video streaming | The next few seconds of video, buffered ahead | Smooth playback |
| A program's variables | The result of a calculation stored in a variable | Not recalculated every time |
Caching in a program: memoisation
Memoisation stores the results of function calls in a dictionary, so that the same call isn't worked out twice.
cache = {}
def fib(n):
if n in cache:
return cache[n]
if n < 2:
result = n
else:
result = fib(n - 1) + fib(n - 2)
cache[n] = result
return result
Without the cache, the recursive Fibonacci function repeats the same work again and again. Calling fib(30) makes 2,692,537 calls. With the cache, it makes only 59. The result, 832040, is the same.
Benefits
- Speed: much quicker access to data or results.
- Less work: fewer calculations, downloads or database queries.
- Less network traffic and server load.
- Better user experience: pages and apps feel responsive.
Drawbacks and trade-offs
- Uses memory. A cache takes up space, and is usually small, so something must be removed when it is full (for example the least recently used item).
- Stale data. The cached copy may be out of date if the original has changed. A browser might show an old version of a page. A strategy for invalidation is needed, such as an expiry time or checking for changes.
- Extra complexity in the program.
- Cache misses cost a little extra time, because the cache was checked first.
- Only helps if data is reused. Caching something that is only used once is a waste.
Deciding what to cache
Good candidates are things that are:
- Expensive to get or calculate (slow disk, network or heavy calculation).
- Used often.
- Unlikely to change (or where slightly old data is acceptable).
Worked example
Task: a website shows the same list of the 10 most popular products to every visitor. The list is found by a slow database query, and changes once an hour. Explain how caching helps and what problem must be managed.
- Without caching: every visit runs the slow query, so the database is overloaded and pages are slow.
- With caching: the first request runs the query and stores the result in memory with the time it was made. Later requests use the stored copy, which is fast.
- Problem to manage: the list changes each hour, so the cached copy would become stale. Fix this by giving the entry an expiry time of one hour. After that, the next request runs the query again and refreshes the cache.
import time
cached = None
cached_at = 0
def popular_products():
global cached, cached_at
if cached is None or time.time() - cached_at > 3600:
cached = run_slow_query()
cached_at = time.time()
return cached
Exam tip: say what is stored, where, and why it is quicker. Always include one drawback, usually stale (out of date) data or the extra memory used. Link caching to thinking ahead: you anticipate what will be needed again.
Check yourself
What is caching?
Storing a copy of data or a result that is likely to be needed again, in a place where it can be reached faster, so it needn't be fetched or calculated again.
Give two examples of caching
Any two of: CPU cache; a browser storing images and pages; a DNS cache; a CDN; a database caching query results; memoising a function.
What is a cache hit and a cache miss?
A hit is when the required data is found in the cache. A miss is when it isn't, so it must be fetched or calculated the slow way.
Give one problem with caching
The stored copy may become out of date (stale) if the original changes, or the cache uses extra memory.