Imagine running a cozy café with a tiny pastry shelf. You can only keep a few items at a time, and when the shelf is full, something has to go. The real question: which pastry gets kicked off to make room for the new one?
That’s exactly what caches do in software. The shelf is your RAM, pastries are data, and the “kick-off” rules are called cache eviction policies. Let’s see how each works — café style.
FIFO — First In, First Out
Kick out the oldest item first.
Everyday café analogy: The cinnamon bun that’s been sitting on the shelf longest gets tossed to make space for fresh pastries.
Why it works: What if that cinnamon bun is still a customer favorite? FIFO doesn’t care — it’s gone.
Where it’s used: Simple and predictable, FIFO works in queues, streaming buffers, and systems where order matters more than popularity.
LFU — Least Frequently Used
Kick out the least popular item.
Everyday café analogy: The chocolate cake nobody ever orders gets removed, while cheesecake that flies off the shelf stays.
Why it works: A pastry that was trendy last month might still hog space today, even though no one buys it anymore.
Where it’s used: LFU is great for CDNs, recommendation engines, and image caches — places where popularity beats freshness.
👉 Try it here: LeetCode LFU Cache
LRU — Least Recently Used
Kick out the item that hasn’t been touched in the longest time.
Everyday café analogy: That croissant sitting untouched for days gets tossed, while the one someone grabbed just yesterday stays.
Why it works: Sometimes recency isn’t everything — a customer-favorite pastry could still get removed if it hasn’t sold lately.
Where it’s used: LRU is the most common default. It powers browser caches, Redis eviction, OS page replacement, and session storage.
👉 Try it here: LeetCode LRU Cache
MRU — Most Recently Used
Kick out the newest item you just used.
Everyday café analogy: You whip up a fresh green matcha latte, take one sip, and toss it. Strange rule, but sometimes it works.
Why it works: You risk losing the freshest, most relevant data.
Where it’s used: Rarely used, but handy in niches like database cursors or workloads where older data is more valuable.
The Café Lesson
Your café shelf — like a cache — can only hold so much. Different rules give you different trade-offs:
- FIFO → Oldest cinnamon bun goes.
- LFU → Least-loved chocolate cake goes.
- LRU → Stale croissant goes.
- MRU → Fresh green matcha latte goes.