Skip to content
Why Caches?
step 1/5

Reading — step 1 of 5

Read

~1 min readWhy LRU

Why Caches?

A cache trades memory for speed. Common pattern: keep the most-frequently-used data in fast storage so you don't redo expensive work.

def get_user(user_id):
    if user_id in cache:
        return cache[user_id]   # 0.1ms
    user = db.query(user_id)    # 10ms
    cache[user_id] = user
    return user

The challenge: cache is BOUNDED. When full, you must EVICT something. The eviction policy determines what's good vs bad cache:

PolicyStrategyHit rate
RandomEvict random entryOK
FIFOEvict oldest INSERTOK
LRUEvict least-recently-USEDBest for typical workloads
LFUEvict least-frequently-USEDBest when popularity is stable
ARCAdaptive: blend recency + frequencyExcellent (used in ZFS)
TinyLFUFrequency-aware with bloom filterExcellent (used in Caffeine)

LRU is the workhorse: when used recently means likely-to-be-used-again, LRU is near-optimal. The implementation is also simple — O(1) get/put with the right data structures.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…