SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
  • What is Caching?
  • Caching Strategies
  • Cache Eviction Policies
  • Cache Invalidation
  • HTTP Caching (Cache-Control, ETag)
  • Redis vs Memcached
  • Local Cache vs Distributed Cache
Part 4: Data and Storage
Part 5: Architecture
Part 6: Distributed Systems
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/Caching/Caching Basics

Cache Eviction Policies

The cache is full. Which item do we throw out? LRU, LFU, FIFO and more.

⏱ 14 min readIntermediateMust KnowInterview FavouriteHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

A cache has a limited size. When it is full and a new item arrives, we must remove one item. The rule that picks the item is the eviction policy.

  • LRU removes the item used longest ago. LFU removes the least used. FIFO removes the oldest arrival.
  • The goal: remove the item we are least likely to need. A good policy keeps the hit ratio high.
  • LRU is the usual default. It is simple and works well for most real traffic.

02Concept: What is it?

Memory is limited. A cache that is full must evict (throw out) something to make room. The best choice is the item that will not be asked for again soon. We cannot see the future, so each policy makes a guess from the past.

A full cache and a new item
Cache (3 slots, full)
Aused 5 times
Bused 1 time, long ago
Cused 2 times, just now
→↓new item
πŸ†•D
→↓who leaves?
πŸšͺLRU β†’ Boldest use
Slots A, B and C are full. Item D arrives. The policy picks who leaves.

Eviction is not the same as expiry or invalidation

WordWhy an item leavesWho decides
EvictionThe cache is full and needs spaceThe cache's policy
Expiry (TTL)The item is too oldThe clock
InvalidationThe real data changedYour code or an event

03Real-Life Example

🍡A small desk
You have a desk that fits only 3 books. You are reading a fourth. Which book goes back on the shelf?
Desk
Policy
Put back the book you have not touched for the longest time
LRU (Least Recently Used)
Put back the book you opened the fewest times
LFU (Least Frequently Used)
Put back the book that was put on the desk first
FIFO (First In, First Out)
Close your eyes and pick one
Random
Put back the book you will not need for the longest time (you need a crystal ball)
Optimal (Belady), only a benchmark
πŸ“Think about a phone
Recent apps stay ready in memory. Apps you have not opened for days are closed first. That is LRU.

04Why Do We Need It?

πŸ“Memory is limited
RAM costs money. We cannot keep everything.
🎯Keep what is useful
A smart policy keeps hot items and removes cold ones, so the hit ratio stays high.
πŸ›‘οΈProtect the system
Without eviction a cache would run out of memory and crash, or refuse new data.
⚑Cheap decisions
Eviction must be quick. A slow policy hurts every request.
A good eviction policy keeps the hits you will need tomorrow and throws out the leftovers from yesterday.

05Where Do We Use It?

WherePolicy you will often meet
RedisChoose with maxmemory-policy: allkeys-lru, allkeys-lfu, volatile-ttl, noeviction and more (Redis uses an approximate LRU/LFU, not an exact one)
MemcachedLRU-style eviction per slab class
Browser and CDN cachesLRU-like removal plus expiry by Cache-Control headers
Operating system page cacheA form of LRU (approximated)
DatabasesBuffer pools use LRU variants to decide which pages stay in memory
CPU cachesHardware picks lines to remove, often an approximate LRU

06Types / Parts / How It Works

LRU: Least Recently Used

  • Rule: remove the item that was used longest ago.
  • Good for: most traffic, because recent items are likely to be used again (temporal locality).
  • Weak spot: a one-time big scan (reading a huge file once) pushes out all the hot items. This is called cache pollution.

LFU: Least Frequently Used

  • Rule: remove the item with the fewest uses.
  • Good for: stable popularity: the top items stay for a long time.
  • Weak spot: an item that was popular last week stays even if nobody uses it now. New items start with a count of 1 and can be removed too soon. Real systems fade old counts over time.

FIFO: First In, First Out

  • Rule: remove the item that arrived first.
  • Good for: simplicity: a plain queue.
  • Weak spot: it ignores use, so it can remove your most popular item just because it came early.

Random

  • Rule: pick any item.
  • Good for: almost no bookkeeping. It performs better than people expect.
  • Weak spot: it can remove a hot item by bad luck.

Others you may hear

NameIdea
TTL-basedRemove items that expire first (or are already expired)
MRU (Most Recently Used)Remove the newest. Odd, but fits some scans
LRU-K, 2Q, ARC, TinyLFUSmarter versions that mix recency and frequency and resist scans
Optimal (Belady)Remove the item needed furthest in the future. Needs the future, so it is only a yardstick
πŸ’‘How to build an LRU cache
Use a hash map (key β†’ node) for fast lookup and a doubly linked list to keep the order from newest to oldest. On a get, move the node to the front. On an insert into a full cache, remove the node at the back. Every step is O(1).
VisualizerWhich item gets evicted?Pick a policy and a cache size, then step through the requests. The table at the bottom compares all policies on the same requests.
Policy
LRU (Least Recently Used): throw out the item that was used longest ago. Idea: if you have not used it for a while, you probably will not soon.
Next requests in the plan
ABCADBAEBCABDAEBACBA
The cache (0/3 slots)
empty
empty
empty
Or ask for a key yourself:
Hits
0
Misses
0
Hit ratio
-
Press β€œNext request” to follow the plan, or ask for a key yourself.
Same 20 requests, 3 slots, every policy
LRU
8/20 hits
LFU
10/20 hits
FIFO
6/20 hits
Random
10/20 hits
Optimal (knows the future)
11/20 hits
β€œOptimal” (Belady) always removes the item needed furthest in the future. Real caches cannot know the future, so it is only a ceiling to compare against.

07How to Use It / Steps / Implementation

How to choose

  1. 1
    Start with LRU
    It is the safe default for most apps.
  2. 2
    Popular items are stable over time?
    Try LFU (or TinyLFU) so the top items stay.
  3. 3
    Do you have big one-time scans?
    Use a scan-resistant policy (2Q, ARC, TinyLFU) or keep scans out of the cache.
  4. 4
    Want the cheapest bookkeeping?
    Random or approximate LRU can be good enough at huge scale.
  5. 5
    Measure the hit ratio
    Test a policy with real traffic. The best policy depends on your access pattern.

A tiny LRU cache in pseudo-code

LRU cache (idea)
get(key):
  if key not in map: return MISS
  move node(key) to the front of the list
  return node.value

put(key, value):
  if key in map: update value, move to front
  else:
    if cache is full: remove node at the BACK and its map entry
    add a new node at the FRONT and put it in the map
πŸ“Note
Redis lets you set a memory limit and a policy. When memory is full, it picks keys by that policy. With β€œnoeviction” it refuses new writes instead.

08Key Terms to Know

TermMeaning in easy words
EvictionRemoving an item to make space
LRULeast Recently Used: remove the item unused for the longest time
LFULeast Frequently Used: remove the item used the fewest times
FIFOFirst In, First Out: remove the oldest arrival
Cache pollutionUseless data pushing out useful data
Cache thrashingItems are evicted just before they are needed again, so almost everything misses
Working setThe data a program is using right now. If the cache is smaller than it, hits drop
Hit ratioShare of requests answered from the cache
Belady's optimalThe best possible policy, which needs knowledge of the future
CapacityHow many items or bytes the cache can hold

09Pros, Cons and Trade-offs

βœ… Pros
  • Keeps memory use under control
  • A good policy keeps the hit ratio high
  • LRU is simple and fast (O(1))
  • No manual cleaning needed
⚠️ Cons
  • Every policy can be fooled by some pattern
  • LRU needs extra bookkeeping (a list and a map)
  • LFU can keep old popular items
  • FIFO ignores usage

Trade-offs

PolicyStrengthWeaknessCost
LRUGreat for recent-use patternsHurt by scansMedium (list and map)
LFUKeeps long-term favouritesSlow to forget, hard on new itemsHigher (counters)
FIFOVery simpleIgnores usageLow
RandomAlmost freeUnlucky evictionsLowest
⚠️A cache that is too small
If the cache is smaller than the working set, any policy will thrash. Add memory before you tune the policy.

10Common Problems and Mistakes

Common mistakes

  1. Choosing a policy without measuring. Test with real traffic.
  2. A cache too small for the working set, so it thrashes.
  3. Letting a batch job or a crawler flood an LRU cache and push out hot items.
  4. Using β€œnoeviction” by mistake. The cache fills and then writes fail.
  5. Mixing very large and very small items without thinking about size. One huge item can push out many small ones.

Typical problems

🌊Scan pollution
A one-time scan evicts every hot item under LRU.
πŸŒ€Thrashing
Items leave just before they are needed again.
πŸ§“Stale favourites
LFU keeps items that were popular long ago.
βš–οΈItems of different size
Evicting by count is not the same as evicting by bytes.

11Real-World Examples

🧰Redis
You set a memory limit and a policy such as allkeys-lru or allkeys-lfu. Redis uses sampling to keep it cheap.
🌐Browsers
They keep a limited number of cached files and remove the least recently used first.
πŸ–₯️Operating systems
The page cache keeps recently read file data in free memory and gives it back when programs need it.
πŸ—„οΈDatabases
A buffer pool holds hot pages. Cold pages are evicted by an LRU-like rule.
β˜•Java and other libraries
Many in-process cache libraries offer LRU or TinyLFU-style limits.
πŸ“±Phones
Background apps are closed first when memory is short.
πŸ“Note
These are general ideas. Exact behaviour differs by product and version.

12Related Topics to Read Next

What is Caching?β†’

The basics this topic builds on.

Caching Strategies→

How the cache is filled and written.

Cache Invalidation→

Removing items because the data changed, not because space ran out.

Distributed Cache Architecture→

Eviction across many cache servers.

Consistent Hashing→

How keys are spread over many cache servers.

Cache Stampede→

What happens when many evicted or expired items are needed at once.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • βœ”Why: a cache has limited space, so something must go.
  • βœ”LRU: remove the longest-unused. The usual default.
  • βœ”LFU: remove the least used. Good for stable favourites.
  • βœ”FIFO: remove the oldest arrival. Simple, ignores use.
  • βœ”Random: almost free, surprisingly OK.
  • βœ”LRU build: hash map + doubly linked list = O(1).
  • βœ”Watch for: scans (pollution) and a cache that is too small (thrashing).
  • βœ”One line: β€œEvict the item you are least likely to need, and measure the hit ratio.”
← Previous
Caching Strategies
Next β†’
Cache Invalidation