缓存驱逐策略
探索缓存如何在内存已满时决定保留和丢弃哪些内容,涵盖 LRU、LFU、FIFO、TTL 及其权衡。
缓存驱逐策略 是 CoddyKit 上的免费 System Design Basics for Backend Developers 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 System Design Basics for Backend Developers 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 System Design Basics for Backend Developers 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
Why Eviction Is Necessary
A cache is fast because it lives in limited memory. When it fills up, it must evict something to make room for new data. The eviction policy decides what to drop.
A good policy keeps the data most likely to be reused.
Hit Rate Is the Goal
The metric that matters is the hit rate: the fraction of requests served from cache. A better eviction policy raises the hit rate, which means fewer slow trips to the database or origin.
hits = 850
misses = 150
hit_rate = hits / (hits + misses)
print('hit rate:', hit_rate)FIFO
FIFO (First In, First Out) evicts the oldest inserted item regardless of usage. It is simple but ignores access patterns, so a frequently used old item can be wrongly evicted.
LRU: Least Recently Used
LRU evicts the item that has not been accessed for the longest time. It assumes recently used data will be used again soon — true for most workloads, which is why LRU is the default in many caches.
Implementing LRU
A classic LRU uses an ordered map. On access, move the key to the most-recent end; when full, evict from the least-recent end.
from collections import OrderedDict
class LRU:
def __init__(self, cap):
self.cap = cap
self.d = OrderedDict()
def get(self, k):
if k in self.d:
self.d.move_to_end(k)
return self.d[k]
def put(self, k, v):
self.d[k] = v
self.d.move_to_end(k)
if len(self.d) > self.cap:
self.d.popitem(last=False)
c = LRU(2)
c.put('a', 1); c.put('b', 2); c.get('a'); c.put('c', 3)
print(list(c.d.keys()))LFU: Least Frequently Used
LFU evicts the item accessed the fewest times. It favors long-term popular items over recent bursts. The downside: a once-popular item can linger long after it stops being useful.
TTL-Based Expiration
A TTL (time to live) expires items after a fixed duration regardless of memory pressure. It bounds staleness and is often combined with LRU: TTL controls freshness, LRU controls memory.
SET session:42 "..." EX 3600
# expires in 3600 secondsRandom and Allkeys Variants
Some caches offer random eviction (cheap, surprisingly decent) and scope variants: evict only keys with a TTL set, or evict from all keys. Redis exposes policies like allkeys-lru and volatile-ttl.
Thundering Herd on Eviction
When a hot key is evicted or expires, many clients may simultaneously rebuild it — a thundering herd that hammers the origin. Mitigate with request coalescing (single-flight) or slightly randomized TTLs to spread out expirations.
Choosing a Policy
Match the policy to the workload:
- Recency-driven traffic: LRU
- Stable popularity: LFU
- Freshness-critical data: TTL
- Uniform access: random is fine and cheap
Eviction in a CDN
CDNs apply the same ideas at the edge. Each edge node has finite storage and evicts (often LRU) plus honors Cache-Control: max-age as a TTL. Understanding eviction explains why a cold edge node has a low initial hit rate.
Quick Check
Test your understanding of eviction policies.
Recap
You learned how caches manage limited memory:
- Eviction policies aim to maximize hit rate
- FIFO, LRU, LFU, TTL, and random each suit different patterns
- Thundering herds need coalescing or jittered TTLs
- CDNs apply the same eviction logic at the edge
常见问题解答
「缓存驱逐策略」课时是免费的吗?
是的 — 「缓存驱逐策略」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 System Design Basics for Backend Developers 课程的其余内容,请升级到 CoddyKit PRO。 System Design Basics for Backend Developers 课程共包含 4 节课。
「缓存驱逐策略」这节课中我会学到什么?
探索缓存如何在内存已满时决定保留和丢弃哪些内容,涵盖 LRU、LFU、FIFO、TTL 及其权衡。 你通过在浏览器中直接运行的动手代码来练习 System Design Basics for Backend Developers,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 System Design Basics for Backend Developers 需要有经验吗?
无需任何先前经验。CoddyKit 上的 System Design Basics for Backend Developers 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 4 节课,共 4 节。
「缓存驱逐策略」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 System Design Basics for Backend Developers 课中编写并运行代码吗?
能。每节 System Design Basics for Backend Developers 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。