Implement an LRU Cache
What an LRU cache is, how it decides what to throw out, and how to build one in Python, explained simply for your AI interview.
In short
An LRU cache holds a fixed number of items and throws out the one used least recently when it is full. I'd pair a dictionary (a store that finds an item by its key straight away) with an order that tracks use, which Python's OrderedDict gives you in one object.
10 min readIntermediateCommon · estimateFacts checked 27 November 2026
Say it out loud
Read it once, then say it without looking. Start with the short one; use the long one when they ask you to go deeper.
An LRU cache keeps a fixed number of items. When it is full and a new item comes in, it throws out the one used least recently. I'd build it with a dictionary for fast lookups and an order that tracks use. Python's OrderedDict, a dictionary that also keeps its keys in order, gives me both. In a claims assistant, it keeps the busiest policy lookups in memory, so the slow database is called less often.
Picture a claims desk that has room for only three policy files. A new file arrives, the desk is full, so the file nobody has opened for the longest time goes back to the archive. That is an LRU cache, short for least recently used. In an AI claims assistant, each policy lookup is a slow database call, and the same few policies come up again and again. An LRU cache keeps those close.
The cache needs two things. A dictionary finds any item by its key straight away. An ordering tracks which item was used last. Every read or write moves the item to the newest end, so the oldest item is always at the other end. When the cache goes over its capacity, that oldest item is removed. Python's OrderedDict gives you both in one object, with move_to_end to refresh an item and popitem(last=False) to drop the oldest.
I'd test the cases an interviewer checks: a hit, a miss, an eviction, and a read that saves an item from eviction. I'd also say what my class does not do. It has no lock, so a server with many threads needs one around each get and put. And a bigger capacity saves more database calls but uses more memory, so I'd choose the size from the hit and miss counts.
What is an LRU cache, in plain words?
A cache is a small, fast store for things you would otherwise fetch again and again. LRU stands for least recently used. The cache has a fixed size, and when it is full, the item that was used longest ago leaves to make room.
Think of a claims desk that holds only a few policy files. A new file comes in and the desk is full, so the file nobody has opened for the longest time goes back to the archive. A busy desk keeps the files it uses most.
In an AI claims assistant, every lookup of a policy's terms costs a slow database call. The same few policies come up for many claims, so keeping them in a cache saves most of those calls.
Key words
- Cache
- A small, fast store for things you would otherwise fetch again.
- Hit
- The item is already in the cache, so no slow call is needed.
- Miss
- The item is not in the cache, so it must be loaded from the slow source.
- Eviction
- Throwing out an item to make room. The least recently used one goes first.
- Capacity
- The fixed number of items the cache can hold.
How does the cache know what to throw out?
Every read or write counts as a use. The item moves to the newest end of the order, so the oldest end is always the next one out. The cache never has to search for it.
A lookup in an LRU cache
Policy asked for
the agent needs the terms
Is it cached?
Hit: already cached
no database call is needed
Miss: not cached
a slow database call is needed
Return it, mark newest
it becomes the newest item
Load from database
store it; drop oldest if full
Answer to the agent
the same answer either way
- 1The lookup finds the item in the cache.
- 2The lookup finds nothing, so it is a miss.
- 3A hit goes straight back, and the item moves to the newest end.
- 4A miss goes to the slow database.
- 5The reply goes back to the agent.
- 6The loaded item is stored, and the oldest one is dropped if the cache is full.
- Hit
Already cached
Return it and move it to the newest end. No database call.
- Miss
Not cached
Load it from the slow source, store it as the newest item, then check the capacity.
- Full
Over capacity
Remove the oldest item. Only the least recently used one goes.
A worked example with a cache of three. Load POL-1041, POL-2210 and POL-3307, in that order. Then read POL-1041. It moves to the newest end, so POL-2210 is now the oldest. Store POL-4418, and the cache is over capacity, so POL-2210 goes. POL-1041, POL-3307 and POL-4418 stay.
Here it is in plain Python, for a made-up claims team. The output tells the same story: the read saved POL-1041, so POL-2210 was the one thrown out.
# A claims team's lookup cache: keep the 3 policies used most recently, so busy claims skip the slow database.
from collections import OrderedDict
class LRUCache:
def __init__(self, capacity):
self.capacity = capacity
self.items = OrderedDict() # oldest at the front, newest at the back
def get(self, key):
if key not in self.items:
return None # a miss: the caller must load it from the database
self.items.move_to_end(key) # this key was just used, so it becomes the newest
return self.items[key]
def put(self, key, value):
self.items[key] = value
self.items.move_to_end(key)
if len(self.items) > self.capacity:
evicted, _ = self.items.popitem(last=False) # drop the least recently used
return evicted
return None
cache = LRUCache(capacity=3)
for policy in ["POL-1041", "POL-2210", "POL-3307"]:
cache.put(policy, "terms for " + policy)
print("hit:", cache.get("POL-1041") is not None)
print("evicted:", cache.put("POL-4418", "terms for POL-4418"))
print("keys, oldest first:", list(cache.items))
print("POL-2210 still cached:", cache.get("POL-2210") is not None)Output
hit: True evicted: POL-2210 keys, oldest first: ['POL-3307', 'POL-1041', 'POL-4418'] POL-2210 still cached: False
- 1
Set a capacity
Decide how many items the cache holds, for example 3 policies or 10,000 rows.
- 2
Store the items in an ordered dictionary
Keys are kept in order, with the oldest at the front and the newest at the back.
- 3
Move an item on every use
A read or a write moves the item to the newest end with move_to_end.
- 4
Drop the oldest when over capacity
When the size goes over the capacity, popitem(last=False) removes the item at the front.
Is there a ready-made version in Python?
Yes. functools.lru_cache is a decorator (a wrapper you put above a function) that caches what a function returns. Python's documentation says it saves the most recent calls, up to a limit, and it reports how often it had a hit or a miss.
“An LRU (least recently used) cache works best when the most recent calls are the best predictors of upcoming calls”
Python documentation, functools
“The OrderedDict algorithm can handle frequent reordering operations better than dict. As shown in the recipes below, this makes it suitable for implementing various kinds of LRU caches.”
Python documentation, collections
Use lru_cache when you only need to remember the results of a function. Build your own, as above, when you must look up, refresh or drop a specific key, or control what is stored. Python's lru_cache is safe to use from several threads (parts of one program running at the same time). A class you write yourself has no lock, so add one if threads share it.
Tip
Asked which to use? Name the ready-made one first, then say you would write the class yourself when you need to control the keys. Interviewers want to see that you know how the order works.
What are the trade-offs and limits?
Capacity is the main choice. A bigger cache means more hits and fewer slow calls, and it uses more memory. Python's docs make the same point about the size limit: it stops the cache growing without bound in long-running servers. Measure the hits and misses before you pick the number.
A cached value can go out of date. If a policy's terms change in the database, the cache may still give the old terms until that item is dropped or refreshed. For terms that must always be current, add a time limit, or clear the item whenever the database changes.
Threads are the other limit. A thread is one path of work that runs at the same time as others inside the same program. A lock is a tool that makes other threads wait until it is released. Put one around each get and put, or the order can break when two threads act at once.
What does the interviewer want to hear?
A strong answer covers
- A plain definition: a fixed number of items, and the least recently used one goes when it is full.
- A dictionary for quick lookup, plus an order that tracks use.
- What a hit, a miss and a full cache each do.
- Why a read counts as a use and moves the item to the newest end.
- The trade-off of capacity: more hits, more memory.
- Thread safety: a lock is needed when many threads share the cache.
Common traps
Trap"Keep a plain dict and delete a random key when it is full."
BetterA random pick can throw out the busiest policy. LRU keeps the items used lately.
Trap"Use a list and search it for the key every time."
BetterA search gets slower as the list grows. A dictionary finds the key without searching the whole list.
Trap"Just wrap the function with lru_cache, that is the whole answer."
BetterThat works for function results, but the interviewer wants the structure: how a read changes the order, and how the oldest item leaves.
Can you spot the wrong line and pick the item that goes?
Spot the wrong eviction
Which line throws out the right item when the cache is over capacity?
Quick check
The claims cache holds 3 policies. Oldest first, the order is POL-1041, POL-2210, POL-3307. The agent reads POL-1041, then a new policy POL-4418 arrives. Which policy is thrown out?
Can you answer these from memory?
Flash cards · tap a card to flip it
What will they ask next?
Last updated on 27 November 2026
Building a cache or a service that many people share?
I design and build AI products and agents, including the systems behind them. Book a short call and tell me what yours needs to handle.