Skip to content

Case study: cache with eviction policies

Difficulty: Advanced

Key concepts

  • bounded cache
  • eviction policy
  • LRU
  • LFU
  • FIFO
  • strategy at run time
  • strong exception guarantee
  • model-based testing
  • time to live
  • thread-safe wrapper
  • How to separate what a cache stores from what it throws away, so that LRU, LFU, and FIFO are three small classes behind one interface, chosen by name when the program starts.
  • How each policy finds its victim in O(1): a list and a map for LRU and FIFO, and a list of frequency buckets for LFU.
  • Why the victim must be chosen before the new key is added, and the test that catches the version that gets it wrong.
  • How to make every operation leave the cache as it was if anything throws, and how to test that with a policy that fails on purpose.
  • How to check thousands of evictions against a slow, obviously correct model instead of working out each expected victim by hand.
  • How a change (entries that expire, and a cache shared by many threads) lands, and why get needs an exclusive lock even though it looks like a read.

This page follows the order in How to approach a case study. It assumes Cache policies and invalidation, which covers when to cache and how stale a copy may be, Strategy, and Containers and complexity. This page answers the question that the caching page leaves open: once the cache is full, which entry goes, and how to find it fast.

“Building a product page takes us 40 ms. We want to keep built pages in memory, but memory is limited, and we can’t agree on what to throw out when it’s full. Can we try a few rules and keep the best?”

“Try a few rules” is the important part. The team does not want one eviction rule; it wants to swap rules without changing the code that uses the cache, and to compare them on its own traffic.

Each question is here because its answer changes the design.

Question Answer (from the team) What it changes
Which rules do you want to try? Least recently used, least frequently used, and first in first out as a baseline. Three policies behind one interface.
When is the rule chosen? When the service starts, from its configuration. We want to switch without rebuilding. The policy is chosen at run time, by name. A template parameter would not do.
How is “full” measured: entries or bytes? Entries. Pages are roughly the same size; a few thousand fit. Capacity is a count of entries.
How fast must a lookup be? A lookup happens on every request. It must not get slower as the cache grows. Every operation O(1) on average, eviction included. No scanning for the victim.
What does a cache miss do? Our code builds the page and puts it in the cache. The cache stores and evicts. In step 1 it does not load anything itself.
Can a page change? Yes, when an editor saves. The editor’s code then puts the new page in, or erases the old one. put overwrites; erase removes. Neither counts as an eviction.
How will you compare the rules? Hit and miss counts, and how many pages were evicted. The cache keeps those counts.
Does looking at the cache from a health check count as using a page? No. A health check must not change what gets evicted. contains does not tell the policy.
What if the cache runs out of memory in the middle of a put? The request may fail, but the cache must still be usable afterwards. The strong exception guarantee: a failed operation leaves the cache as it was.
One thread or many? One thread per cache for now. We may share one later. Step 1 is single-threaded and says so. Sharing arrives as a change.

Two answers shape most of the design. “Switch without rebuilding” makes the policy an object chosen at run time, which is Strategy. “It must not get slower as the cache grows” rules out the easy way to find a victim, looking at every entry, and asks each policy to keep a structure where its victim is always at one end.

Confirmed:

  • A cache from keys to values with a fixed capacity in entries.
  • get, put (add or overwrite), erase, and contains, which looks without counting as a use.
  • Three eviction policies, LRU, LFU, and FIFO, chosen by name when the cache is made.
  • Hit, miss, and eviction counts.
  • A failed operation leaves the cache unchanged.

Assumed (to confirm with the team; see Assumptions):

  • Keys are cheap to copy and hash (page identifiers, short strings).
  • A value is copied out of the cache on every hit. For pages that are large, the value type can be a std::shared_ptr<const Page>, so the copy is a pointer.

Out of scope: limits in bytes, loading on a miss, entries that expire, sharing between threads (the last three arrive as a change, below), and caches spread over several machines.

Functional requirements.

  • FR-1 Store and read. put(key, value) stores a value; get(key) returns a copy of it, or nothing. put on a key that is there replaces the value.
  • FR-2 Bounded. The cache never holds more than its capacity. A put of a new key into a full cache first evicts one entry, chosen by the policy, and returns the evicted key.
  • FR-3 Policies. LRU evicts the entry unused for longest. LFU evicts the entry used least often, and among those, the one unused for longest. FIFO evicts the entry added longest ago, however much it is used. A get that hits and a put that overwrites both count as a use.
  • FR-4 Chosen at run time. A policy is chosen by name ("lru", "lfu", "fifo") when the cache is made. An unknown name is an error.
  • FR-5 Erase and look. erase(key) removes an entry and is not an eviction. contains(key) reports whether a key is there without counting as a use.
  • FR-6 Counts. The cache counts hits, misses, and evictions.

Non-functional requirements.

  • NFR-1 O(1). get, put, erase, and contains take O(1) time on average, independent of the number of entries, for every policy.
  • NFR-2 Policies are separate. A policy never sees a value, so one policy class works for every value type. Adding a policy changes no line of the cache.
  • NFR-3 Exception safety. Every operation gives the strong guarantee: if it throws, the entries, the policy’s order, and the counts are as they were. See Exception safety.
  • NFR-4 Not thread-safe, on purpose. Step 1 is for one thread at a time, and its documentation says so.

NFR-1 is a statement about how the work grows, not a timing. This page has no benchmarks; the Performance page explains how to measure one honestly.

The tests are named after these criteria. See Use cases, user stories, and acceptance criteria.

UC-1 Store and read a page.

  • AC-1.1 get returns what put stored.
  • AC-1.2 A get for a key that is not there returns nothing and is counted as a miss.
  • AC-1.3 A put on a key that is there replaces the value and never evicts, even when the cache is full.
  • AC-1.4 erase removes the entry and is not counted as an eviction.

UC-2 A full cache under LRU.

  • AC-2.1 LRU evicts the entry unused for longest.
  • AC-2.2 A get makes a key the most recently used, which protects it.
  • AC-2.3 contains does not count as a use.

UC-3 The other policies.

  • AC-3.1 FIFO evicts in the order keys were added, whatever was read or overwritten.
  • AC-3.2 LFU evicts the key used least often.
  • AC-3.3 Among keys used equally often, LFU evicts the one unused for longest.
  • AC-3.4 The key being added is never its own victim.
  • AC-3.5 An overwrite counts as a use, under LRU and under LFU.
  • AC-3.6 A policy is chosen by name; an unknown name is an exception.

UC-4 Edges and setup.

  • AC-4.1 A cache of one keeps only the latest key, under every policy.
  • AC-4.2 A capacity of zero, or no policy, is an exception when the cache is made.

UC-5 Comparing the rules.

  • AC-5.1 The counts are exact: hits, misses, and evictions, and an erase is none of them.
  • AC-5.2 The value get returns is a copy, still good after the entry is evicted.

UC-6 Something fails.

  • AC-6.1 If the policy throws while a new key is added, nothing is evicted and the new key is not there.
  • AC-6.2 If the policy throws on an overwrite or a hit, the old value is still there and nothing is counted.
  • AC-6.3 If copying a value out throws, the get did not count as a use.

Each invariant names the code that keeps it. See Invariants.

  • INV-1 Bounded. The cache holds at most capacity entries. Kept by Cache::put, the only place that adds an entry, which picks a victim whenever the cache is full.
  • INV-2 The policy tracks exactly the cache’s keys. Every key in the cache is tracked by the policy once, and the policy tracks nothing else. Kept by Cache, which calls on_insert, on_access, and on_erase at every change, and undoes its own change when the policy throws.
  • INV-3 The victim is at one end. Each policy keeps its keys in an order where the next victim is at the back of a list: least recently used last (LRU), oldest insert last (FIFO), and the last key of the lowest-count bucket (LFU). Kept by each policy’s on_insert and on_access.
  • INV-4 LFU buckets. The buckets are in strictly increasing order of count, and none is empty. Kept by LfuPolicy::on_insert and on_access, which add a bucket only when the one they need is missing, and by on_access and on_erase, which erase a bucket they empty.

INV-1 and INV-2 are checked after every operation in the model test, through invariants_hold. INV-3 is checked indirectly: the model test compares every victim with one chosen by looking at all entries. Tests explains why the “none is empty” half of INV-4 is not checked by any test.

The nouns from the answers: page, key, value, cache, capacity, rule, use, hit, miss, eviction, count, configuration, health check. Filtered:

  • Cache stores values by key, up to a capacity. Becomes Cache<K, V>.
  • Rule decides what leaves. It has its own data (an order, or counts), and the team wants to swap it. Becomes the interface EvictionPolicy<K> with LruPolicy, LfuPolicy, and FifoPolicy.
  • Use is an event the cache reports to the rule: a key was added, read, overwritten, or removed. Becomes the policy’s on_insert, on_access, and on_erase.
  • Count (hit, miss, eviction) becomes CacheStats, a plain struct.
  • Configuration names a rule. Becomes PolicyKind, policy_kind, which reads a name, and make_policy, which builds the policy.
  • Page, key, value: the caller’s types, K and V.
  • Health check: a caller of contains.
Classes in step 1. Filled diamond: owns. Dashed arrow: makes
Text description of the diagram

EvictionPolicy of K is an interface with on_insert, on_access, on_erase, victim, and size. LruPolicy and FifoPolicy implement it with a list of keys and a map from each key to its node in the list. LfuPolicy implements it with a list of buckets and a map from each key to its bucket and its node. Cache of K and V owns exactly one EvictionPolicy through a unique_ptr, and owns its entries in an unordered_map, its capacity, and its counts. It offers get, put, erase, contains, and stats. The function make_policy takes a PolicyKind and makes one of the three policies.

Diagram source (Mermaid)
classDiagram
class EvictionPolicy~K~ {
  <<interface>>
  +on_insert(const K&) void*
  +on_access(const K&) void*
  +on_erase(const K&) void*
  +victim() const K&*
  +size() size_t*
}
class LruPolicy~K~ {
  -list~K~ order_
  -unordered_map where_
}
class FifoPolicy~K~ {
  -list~K~ order_
  -unordered_map where_
}
class LfuPolicy~K~ {
  -list~Bucket~ buckets_
  -unordered_map where_
}
class Cache~K,V~ {
  -size_t capacity_
  -unique_ptr~EvictionPolicy~ policy_
  -unordered_map~K,V~ entries_
  -CacheStats stats_
  +get(const K&) optional~V~
  +put(const K&, V) optional~K~
  +erase(const K&) bool
  +contains(const K&) bool
  +stats() CacheStats
}
class make_policy {
  <<function>>
  +make_policy(PolicyKind) unique_ptr~EvictionPolicy~
}
EvictionPolicy <|.. LruPolicy
EvictionPolicy <|.. FifoPolicy
EvictionPolicy <|.. LfuPolicy
Cache *-- "1" EvictionPolicy : policy_ (owns)
make_policy ..> EvictionPolicy : makes

Ownership is a short tree: whoever makes the cache owns it; the cache owns its entries and its policy; the policy owns its lists and maps. No object refers to another it does not own, so there is no lifetime rule to state in step 1. (Step 2 adds one: the clock.)

The design below is step 1 of the example, the complete answer to FR-1 … FR-6. Expiry and threads are added in When the requirements change.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

eviction_policy.hpp
// Decides which key leaves a full cache. The cache tells its policy about
// every key it gains, uses, and loses, and asks it for a victim. A policy
// never sees a value, so one policy works for every value type.
//
// The cache keeps this contract, and every policy may rely on it:
// - on_insert(key): key is not tracked yet. Starts tracking it.
// - on_access(key): key is tracked. It was just read or overwritten.
// - on_erase(key): key is tracked. Stops tracking it.
// - victim(): at least one key is tracked. Names the key to evict
// next, without forgetting it. The reference is valid
// until the policy next changes.
// on_insert and on_access may throw (they may allocate); if they do, the
// policy is unchanged. The others do not throw.
//
// K must be copyable and hashable with std::hash, and its hash and
// equality must not throw.
//
// `template <typename K>` makes this a pattern for a family of classes:
// EvictionPolicy<std::string> for string keys, EvictionPolicy<int> for
// int keys, and so on. `K` is filled in where the policy is used.
template <typename K>
class EvictionPolicy {
public:
// A virtual destructor, because the cache deletes a concrete policy
// (LruPolicy, say) through a pointer to this base class. Without it,
// that delete is undefined behaviour (in practice its list and map leak).
virtual ~EvictionPolicy() = default;
// `= 0` makes each of these "pure virtual": this class has no code
// for it, and every concrete policy must supply its own. A call
// through an EvictionPolicy pointer runs the concrete policy's
// version. noexcept is a promise that the function never throws.
virtual void on_insert(const K& key) = 0;
virtual void on_access(const K& key) = 0;
virtual void on_erase(const K& key) noexcept = 0;
// Returns a reference to the policy's own copy of the key, not a new
// copy; see the contract above for how long it may be used.
[[nodiscard]] virtual const K& victim() const noexcept = 0;
// How many keys the policy tracks; the cache checks it equals its own
// size (INV-2).
[[nodiscard]] virtual std::size_t size() const noexcept = 0;
protected:
// Protected: only a derived policy can construct, copy, or assign the
// base part. Outside code cannot copy a policy through an
// EvictionPolicy reference, which would copy only the base part and
// lose the derived data ("slicing").
EvictionPolicy() = default;
EvictionPolicy(const EvictionPolicy&) = default;
EvictionPolicy& operator=(const EvictionPolicy&) = default;
};

The interface is a conversation in two directions. The cache tells the policy what happened (a key was added, used, or removed), and asks it one question: which key goes next? It never asks the policy to remove anything. victim() only names a key; the cache then removes it from its own map and tells the policy with on_erase, the same call an erase makes. Each change has one path through the code.

The comment above the class is the real contract, and both sides lean on it. The cache promises never to insert a key twice, never to use or erase a key the policy does not track, and never to ask for a victim of an empty policy. In return, each policy can skip those checks (it only asserts them), and the cache can rely on on_erase and victim never throwing, which matters below. The tests wrap each policy in a CheckedPolicy that counts every broken promise; see Tests.

victim() returns a reference, and the contract says how long it is good for: until the policy next changes. That is not an academic detail. put is about to call on_insert, which changes the policy, so it copies the key first.

A policy never sees a value (NFR-2). LruPolicy<std::string> serves a cache of pages, a cache of prices, and a cache of images alike. The cost is that the cache and the policy each keep their own copy of every key; see A dedicated LRU.

The copy operations are protected, so a policy cannot be copied through a base-class reference, which would slice it; see Inheritance and interfaces.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

cache.hpp
// A cache that holds at most capacity entries and, when it is full, asks
// its policy which one to evict. It owns its values and its policy.
//
// K: as EvictionPolicy requires, and its move constructor must not
// throw (put returns the evicted key). V must be copyable, and its move
// constructor and move assignment must not throw. get returns a copy:
// the next put may evict the entry, and a reference to it would dangle.
//
// Every member gives the strong guarantee: if it throws, the cache and
// its stats are as they were.
//
// Thread safety: not safe; see SynchronizedCache in step 2.
template <typename K, typename V>
class Cache {
public:
// Throws std::invalid_argument if capacity is 0 or policy is null.
// The policy arrives as a std::unique_ptr, the one owner of a heap
// object. The caller hands it over (a temporary, or std::move), and the
// initialiser policy_(std::move(policy)) moves it on into the member,
// so from here the cache alone owns the policy and deletes it when the
// cache is destroyed. The checks run after the members are set. If
// one throws, the members already built are destroyed, so the policy
// is still deleted: nothing leaks.
Cache(std::size_t capacity, std::unique_ptr<EvictionPolicy<K>> policy)
: capacity_(capacity), policy_(std::move(policy)) {
if (capacity_ == 0) throw std::invalid_argument("capacity must be at least 1");
if (!policy_) throw std::invalid_argument("a cache needs an eviction policy");
}
// A hit counts as a use, so it can change what is evicted next.
// Returns a copy of the value, or std::nullopt ("nothing") on a miss.
[[nodiscard]] std::optional<V> get(const K& key) {
// find returns an iterator: a position in the map. If the key is
// absent, it is the special position entries_.end().
const auto found = entries_.find(key);
if (found == entries_.end()) {
++stats_.misses;
return std::nullopt;
}
// found->first is the key and found->second the value. Copy the
// value first: if the copy throws, no use has been recorded yet.
std::optional<V> copy{found->second}; // may throw: nothing has changed
// Then tell the policy. If this throws, the copy is thrown away and
// the hit is not counted, so the cache is still as it was.
policy_->on_access(key);
++stats_.hits;
return copy;
}
// Adds or overwrites. Returns the key evicted to make room, if any.
std::optional<K> put(const K& key, V value);
// Returns whether the key was there. Not an eviction, so the
// evictions count does not change.
bool erase(const K& key) noexcept {
const auto found = entries_.find(key);
if (found == entries_.end()) return false;
// Tell the policy, then remove the entry through the iterator
// found above, with no second search. Neither step throws.
policy_->on_erase(key);
entries_.erase(found);
return true;
}
// Looks without using: the policy is not told, so a contains never
// changes which key is evicted next.
[[nodiscard]] bool contains(const K& key) const { return entries_.contains(key); }
[[nodiscard]] std::size_t size() const noexcept { return entries_.size(); }
[[nodiscard]] std::size_t capacity() const noexcept { return capacity_; }
[[nodiscard]] CacheStats stats() const noexcept { return stats_; }
// INV-1 and INV-2: never more entries than capacity, and the policy
// tracks exactly as many keys as the cache holds.
[[nodiscard]] bool invariants_hold() const noexcept {
return entries_.size() <= capacity_ && policy_->size() == entries_.size();
}
private:
std::size_t capacity_;
// The policy lives on the heap behind a pointer to the base class, so
// any of LruPolicy, LfuPolicy, or FifoPolicy can sit here. The
// `->` calls go to whichever one it is (a virtual call).
std::unique_ptr<EvictionPolicy<K>> policy_;
// The entries themselves: key to value, found by hashing the key.
std::unordered_map<K, V> entries_;
CacheStats stats_; // every count starts at 0
};
  • get copies first, then tells the policy. Copying a value may throw (a std::string allocates). If it does, nothing has been recorded, so a failed get is not a use (AC-6.3). The order matters the other way too: on_access may throw (LFU may need a new bucket), and then the copy is simply discarded.
  • get returns a copy, not a reference. The next put may evict the entry, and a reference to it would dangle (AC-5.2). For large values, V can be a std::shared_ptr<const Page>; then the copy is a pointer, and a page that is evicted while a request still uses it lives until that request lets go.
  • contains does not tell the policy (AC-2.3). It is const, but that alone would not stop it: const on a member function protects entries_ and stats_, not the policy behind the std::unique_ptr, because a unique_ptr’s const does not reach the object it points to. What keeps the rule is the code, which never calls the policy there, and the test ac_2_3.
  • erase is noexcept. It calls only on_erase, which the contract says does not throw, and unordered_map::erase, which does not throw when hashing and comparing keys do not.
  • No copy or move is written by hand. The members are a std::unique_ptr and standard containers, so the cache is movable and not copyable. That is right for this design: a copy would need a second policy with the same order and counts, and the interface has no way to copy a policy. See The rule of zero and the rule of five.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

cache.hpp
// Adds a key, or overwrites the value of a key that is already there.
// value is taken by value (a copy or a move made by the caller), so put
// can move it into the map without copying it again. Returns the evicted
// key, or std::nullopt if nothing had to go. Overwriting never evicts.
template <typename K, typename V>
std::optional<K> Cache<K, V>::put(const K& key, V value) {
// `if (init; condition)`: found exists only inside this if. The key is
// already in the cache, so this is an overwrite, which counts as a use.
if (const auto found = entries_.find(key); found != entries_.end()) {
policy_->on_access(key); // may throw: nothing has changed
// std::move hands value's contents over instead of copying them.
found->second = std::move(value); // does not throw
return std::nullopt;
}
// Choose the victim before the new key exists, so the new key cannot
// be chosen. Copy it: the reference is only good until the policy
// changes, and on_insert changes it.
// victim starts empty. Only a full cache needs one: emplace copies
// the key the policy names into the optional.
std::optional<K> victim;
if (entries_.size() == capacity_) victim.emplace(policy_->victim());
// try_emplace adds key -> value (the key is known to be absent) and
// returns a pair; .first is an iterator to the new entry, kept so the
// undo below can remove it. For a moment the map may hold
// capacity + 1 entries.
const auto added = entries_.try_emplace(key, std::move(value)).first; // may throw
try {
policy_->on_insert(key);
} catch (...) {
// catch (...) catches any exception. Undo the add, then `throw;`
// sends the same exception on to the caller.
entries_.erase(added); // undo: the cache is as it was
throw;
}
// Nothing below throws, so the eviction cannot be left half done.
// `if (victim)` is true when the optional holds a key; *victim reads
// it. The victim is an old key, never the one just added.
if (victim) {
policy_->on_erase(*victim);
entries_.erase(*victim);
++stats_.evictions;
}
return victim; // the evicted key, or std::nullopt
}

A put of a new key into a full cache does four things, in an order chosen so that a failure at any step leaves the cache as it was:

  1. Copy the victim’s key, while the new key is not yet in the policy. The new key cannot be chosen, because the policy has not heard of it.
  2. Add the entry to the map. This may throw (it allocates); nothing else has changed yet.
  3. Tell the policy with on_insert. If that throws, erase the entry just added: the cache is as it was, and nothing was evicted (AC-6.1).
  4. Evict the victim. on_erase and unordered_map::erase do not throw, so the eviction cannot be left half done.

For a short while, during steps 2 and 3, the map holds one entry more than the capacity. INV-1 is stated for the moments between operations, which is when a caller can look.

Two requirements on the types follow from this order, and the comment on the class states them. V’s move assignment must not throw, because the overwrite path tells the policy first (which may throw) and then move-assigns the value, which must not fail after the use has been recorded. V’s move constructor must not throw, because get returns its copy, a local std::optional<V>, after the use has been recorded, and returning it may move it. K’s move must not throw, because put returns the victim by value after the eviction has happened.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

lru_policy.hpp
// Least recently used: evicts the key that has gone longest without an
// insert or an access. Every operation is O(1) on average.
//
// order_ is a list with the most recently used key at the front, so the
// victim is at the back. where_ finds a key's node in the list, so an
// access can move that node to the front without searching. A list node
// never moves in memory, so the iterators in where_ stay valid while
// other nodes come and go, and splice moves a node without copying it.
//
// `final` means no class may derive from LruPolicy. `override` on each
// member asks the compiler to check that it really replaces a virtual
// function of EvictionPolicy (a typo would otherwise make a new function).
template <typename K>
class LruPolicy final : public EvictionPolicy<K> {
public:
// A new key is the most recently used one: it goes to the front.
void on_insert(const K& key) override {
// assert checks the cache's promise in a debug build, and does
// nothing in a release build (NDEBUG). It is not error handling.
assert(!where_.contains(key));
order_.push_front(key); // may throw: nothing has changed
try {
// order_.begin() is an iterator to the node just pushed: the
// map remembers where that key lives in the list.
where_.emplace(key, order_.begin());
} catch (...) {
order_.pop_front(); // undo, so a throw leaves no trace
throw;
}
}
// A used key becomes the most recently used: move its node to the
// front. found->second is the key's list iterator, saved by on_insert.
void on_access(const K& key) override {
const auto found = where_.find(key);
assert(found != where_.end());
// splice(where to, from which list, which node): unhooks that one
// node and hooks it in before order_.begin(). Same list, so the
// node, its key, and the saved iterator all stay as they are.
order_.splice(order_.begin(), order_, found->second); // does not throw
}
// Removes the key's node from the list, then its map entry. The order
// matters: found->second is read before the map entry holding it goes.
void on_erase(const K& key) noexcept override {
const auto found = where_.find(key);
assert(found != where_.end());
order_.erase(found->second);
where_.erase(found);
}
// The back of the list is the key used longest ago. The reference is
// to the key stored in that list node; the contract promises it only
// until the policy next changes, so the cache copies it first.
[[nodiscard]] const K& victim() const noexcept override {
assert(!order_.empty());
return order_.back();
}
[[nodiscard]] std::size_t size() const noexcept override { return order_.size(); }
private:
std::list<K> order_; // most recently used first
// Key -> the position of that key's node in order_. `typename` tells
// the compiler that std::list<K>::iterator names a type; it is needed
// because the type depends on the template parameter `K`.
std::unordered_map<K, typename std::list<K>::iterator> where_;
};
How this code works: LruPolicy, call by call

The policy holds two structures that must always agree: the list order_, and the map where_ from each key to that key’s node in the list.

  1. on_insert(key) pushes a new node holding the key onto the front of the list, then records order_.begin() (the new node) in the map. If the map insert throws, pop_front removes the node again, so the two structures still agree.
  2. on_access(key) looks the key up in where_, which gives the node directly, and splices that node to the front. Nothing is copied or allocated, and every saved iterator still points at its own node. Splicing the front node to the front changes nothing.
  3. on_erase(key) erases the node through the saved iterator, then the map entry. The map entry goes last, because the iterator is stored inside it.
  4. victim() is the back node, the key that has waited longest since its last insert or use.

A worked example. The LRU cache in the step 1 demo has room for 3. The list is written front first.

Request Calls to the policy order_ after
put home on_insert(home) home
put cart on_insert(cart) cart, home
put deals on_insert(deals) deals, cart, home
get home on_access(home) home, deals, cart
get home on_access(home): already at the front home, deals, cart
get cart on_access(cart) cart, home, deals
put help full: victim() is deals; on_insert(help); on_erase(deals) help, cart, home
get deals none: a miss never reaches the policy help, cart, home
put faq full: victim() is home; on_insert(faq); on_erase(home) faq, help, cart

The evicted keys are deals and then home, and the cache ends holding cart, help, and faq: the first line of the demo’s output, shown in Scenarios.

LRU needs two things fast: the key unused for longest, and a way to move any key to “just used”. A list ordered by use gives the first (the back of the list) but finding a key in it is O(n). A map from key to the key’s list node gives the second. Together, every operation is a hash lookup and a pointer change:

  • on_access finds the node through where_ and splices it to the front. splice moves a node from one place in a list to another without copying the key or allocating, and it does not throw.
  • victim is order_.back().
  • on_erase finds the node, erases it from the list, and erases the map entry.

This only works because a std::list node never moves in memory: the iterators stored in where_ stay valid while other nodes are added, moved, and removed. A std::vector or std::deque would invalidate them. See Containers and complexity.

on_insert is the one place that can throw twice: push_front allocates a node, and emplace allocates a map entry. If the second throws, it pops the node it just pushed, so the policy is unchanged.

LruPolicy after put home, put cart, put deals, get home
Text description of the diagram

The list order_ holds the keys with the most recently used first: home, then deals, then cart. The map where_ has an entry for each of the three keys, and each entry points straight at that key’s node in the list. The get of home moved home’s node from the back to the front, without searching. The victim is the back of the list, cart.

Diagram source (Mermaid)
flowchart LR
subgraph map ["where_ (unordered_map from key to list node)"]
  mh["home"]
  mc["cart"]
  md["deals"]
end
subgraph list ["order_ (list, most recently used first)"]
  direction LR
  nh["home"] --> nd["deals"] --> nc["cart"]
end
mh -.-> nh
md -.-> nd
mc -.-> nc
nc -. "victim: the back" .- V["next to go"]

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

lfu_policy.hpp
// Least frequently used: evicts the key with the fewest uses (its insert
// counts as one, and each access adds one). Among keys with the same
// count, the least recently used goes. Every operation is O(1) on
// average.
//
// Keys with the same count share a bucket, and the buckets are kept in
// increasing order of count, so the victim is at the back of the first
// bucket. An access moves a key to the bucket for count + 1, which is
// the next bucket or a new one inserted right after: no search, and no
// sorting. No bucket is ever empty; an emptied bucket is erased.
template <typename K>
class LfuPolicy final : public EvictionPolicy<K> {
public:
// A new key has one use, so it belongs in the bucket for count 1, at
// the front (most recent). Each step that can throw comes before any
// change that could not be undone.
void on_insert(const K& key) override {
assert(!where_.contains(key));
// A list of one element, holding a copy of key. Making it may
// throw (it allocates), but then nothing has changed yet.
std::list<K> node{key}; // the key's node, made before anything changes
// Counts start at 1 and the buckets are in increasing order, so a
// bucket for count 1, if there is one, is the first. Make one only
// if it is missing.
const bool made_bucket = buckets_.empty() || buckets_.front().uses != 1;
// Bucket{1, {}}: uses is 1 and keys is an empty list. May throw.
if (made_bucket) buckets_.push_front(Bucket{1, {}});
try {
// Record where the key will live: the first bucket, and its node.
where_.emplace(key, Place{buckets_.begin(), node.begin()});
} catch (...) {
// Undo only what this call did; an existing bucket stays.
if (made_bucket) buckets_.pop_front();
throw;
}
// splice does not throw, and node.begin() now points into the bucket
// (splice moves the node itself, so iterators to it stay valid and
// the local list `node` is left empty).
buckets_.front().keys.splice(buckets_.front().keys.begin(), node);
}
// One more use: move the key from its bucket (count n) to the front of
// the bucket for count n + 1, making that bucket if it does not exist.
void on_access(const K& key) override {
const auto found = where_.find(key);
assert(found != where_.end());
// A reference, so the update to place.bucket below changes the
// Place stored in the map, not a copy of it.
Place& place = found->second;
const BucketIt from = place.bucket; // the bucket the key is in now
// std::next(from) is the bucket after it, or buckets_.end() if
// from is the last. The counts strictly increase along the list,
// so if a bucket for count + 1 exists, it is that one.
BucketIt to = std::next(from);
if (to == buckets_.end() || to->uses != from->uses + 1) {
// insert(position, value) puts the new bucket before `to`, which
// is right after `from`, and returns an iterator to it.
to = buckets_.insert(to, Bucket{from->uses + 1, {}}); // may throw: nothing has changed
}
// Move the key's own node from `from` to the front of `to`: no copy,
// no allocation, and place.key still points at it.
to->keys.splice(to->keys.begin(), from->keys, place.key);
place.bucket = to;
// Keep "no bucket is ever empty": if that was the last key in
// `from`, the bucket goes. Other iterators are not affected.
if (from->keys.empty()) buckets_.erase(from);
}
// Removes the key's node, then its bucket if that is now empty, then
// its map entry, which holds the iterators, last.
void on_erase(const K& key) noexcept override {
const auto found = where_.find(key);
assert(found != where_.end());
const BucketIt bucket = found->second.bucket;
bucket->keys.erase(found->second.key);
if (bucket->keys.empty()) buckets_.erase(bucket);
where_.erase(found);
}
// The first bucket has the lowest count; its back is the key among
// those that was used longest ago.
[[nodiscard]] const K& victim() const noexcept override {
assert(!buckets_.empty());
return buckets_.front().keys.back();
}
[[nodiscard]] std::size_t size() const noexcept override { return where_.size(); }
private:
struct Bucket {
std::size_t uses; // how many times each key here was used
std::list<K> keys; // most recently used first; never empty
};
// A short name for "a position in the list of buckets".
using BucketIt = typename std::list<Bucket>::iterator;
// Where one key lives: which bucket, and which node inside that
// bucket's list. Two iterators, so no search is ever needed.
struct Place {
BucketIt bucket;
typename std::list<K>::iterator key;
};
// A list of buckets, not a vector: inserting or erasing a bucket never
// moves the others, so the BucketIt values stored in where_ stay valid.
std::list<Bucket> buckets_; // uses strictly increasing from the front
std::unordered_map<K, Place> where_;
};
How this code works: LfuPolicy, call by call

The policy keeps a list of buckets. Each bucket has a count, uses, and a list of the keys with exactly that count, most recently used first. Along the list of buckets the counts strictly increase, and no bucket is empty. where_ maps each key to a Place: which bucket it is in, and which node of that bucket’s list is its own.

  1. on_insert(key) first builds the key’s node in a small local list, node. If the first bucket is not the one for count 1 (or there are no buckets), it pushes a new bucket for count 1 onto the front. It records the key’s Place in the map, and if that throws, it removes the bucket it made. Last, it splices the node into the front of the first bucket, which cannot throw.
  2. on_access(key) finds the key’s bucket, from, and looks at the bucket after it, to. If to is missing or is not for from->uses + 1, a new bucket for that count is inserted between them. Then the key’s node is spliced to the front of to, the Place is updated, and from is erased if it is now empty.
  3. on_erase(key) erases the key’s node, then its bucket if that is now empty, then the map entry.
  4. victim() is the back of the first bucket: the lowest count, and among keys with that count, the one used longest ago.

A worked example. The LFU cache in the step 1 demo, room for 3. Each bucket is written as count, then its keys front first.

Request What happens in the policy Buckets after
put home no buckets yet: a bucket for 1 is made 1: home
put cart the first bucket is for 1: no new bucket 1: cart, home
put deals the same 1: deals, cart, home
get home after bucket 1 there is none: a bucket for 2 is inserted 1: deals, cart / 2: home
get home after bucket 2 there is none: a bucket for 3 is inserted; bucket 2 is empty and erased 1: deals, cart / 3: home
get cart after bucket 1 comes 3, not 2: a bucket for 2 is inserted between them 1: deals / 2: cart / 3: home
put help full: victim() is deals; help joins bucket 1; deals is erased 1: help / 2: cart / 3: home
get deals a miss: no call to the policy 1: help / 2: cart / 3: home
put faq full: victim() is help; faq joins bucket 1; help is erased 1: faq / 2: cart / 3: home

The state before put help is the one in the diagram below, and the evictions, deals and then help, are the second line of the demo’s output.

LFU is harder, because “used least often” seems to need a search or a heap, and a heap makes each use O(log n). The trick is that a count only ever goes up by one. So keys with the same count share a bucket, the buckets are kept in increasing order of count, and a use moves a key from its bucket to the very next one:

  • If the next bucket has count + 1, the key moves into it.
  • If not (the next bucket has a higher count, or there is none), a new bucket for count + 1 is inserted right after the current one. Nothing is searched and nothing is sorted.
  • A bucket that becomes empty is erased, so the first bucket always holds the keys with the lowest count.

Within a bucket the keys are most recently used first, as in LRU. A key enters a bucket at the moment of its latest use, so the back of the first bucket is the key with the fewest uses and, among those, the oldest last use: exactly the tie rule in FR-3 (AC-3.3).

where_ maps each key to two iterators, its bucket and its node in the bucket, so on_access and on_erase start at the right place. Every key moves with splice, so the iterators stay valid. on_insert builds the key’s node in a one-element list first, before anything changes, then splices it in; on_access inserts the new bucket (the only step that allocates) before it moves anything. If either throws, the policy is as it was.

LfuPolicy in the step 1 demo, just before put help
Text description of the diagram

Three buckets in increasing order of count. The bucket for one use holds deals, which was put once and never read. The bucket for two uses holds cart, put once and read once. The bucket for three uses holds home, put once and read twice. The victim is the last key of the first bucket, deals. A get of deals would move it into the bucket for two uses, in front of cart, and the bucket for one use, now empty, would be erased.

Diagram source (Mermaid)
flowchart LR
subgraph b1 ["bucket: 1 use"]
  k1["deals"]
end
subgraph b2 ["bucket: 2 uses"]
  k2["cart"]
end
subgraph b3 ["bucket: 3 uses"]
  k3["home"]
end
b1 --> b2 --> b3
k1 -. "victim: back of the first bucket" .- V["next to go"]

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

fifo_policy.hpp
// First in, first out: evicts the key that was inserted longest ago,
// however often it is used. The same list and map as LruPolicy, but an
// access changes nothing. where_ is still needed, so that on_erase can
// find a key's node in O(1).
template <typename K>
class FifoPolicy final : public EvictionPolicy<K> {
public:
// As in LruPolicy: the new key goes to the front, and if recording its
// position in where_ throws, the node just pushed is removed again.
void on_insert(const K& key) override {
assert(!where_.contains(key));
order_.push_front(key);
try {
where_.emplace(key, order_.begin());
} catch (...) {
order_.pop_front();
throw;
}
}
// Does nothing in a release build: a use never changes a key's place.
// [[maybe_unused]] stops a warning about an unused parameter when the
// assert, its only user, is compiled out (NDEBUG).
void on_access([[maybe_unused]] const K& key) override {
assert(where_.contains(key)); // tracked, but its age does not change
}
void on_erase(const K& key) noexcept override {
const auto found = where_.find(key);
assert(found != where_.end());
order_.erase(found->second);
where_.erase(found);
}
// The back of the list is the key inserted longest ago.
[[nodiscard]] const K& victim() const noexcept override {
assert(!order_.empty());
return order_.back();
}
[[nodiscard]] std::size_t size() const noexcept override { return order_.size(); }
private:
std::list<K> order_; // newest first
std::unordered_map<K, typename std::list<K>::iterator> where_;
};

FIFO is LRU with on_access doing nothing. It still needs where_, not for uses but for on_erase: an erase can remove a key from the middle of the order, and without the map that would be a search.

The two classes share most of their code. They are kept apart on purpose: merging them would mean a flag that on_access checks, which is the kind of branch the interface exists to remove, and each class is short enough to read in one look. A shared base class for “list plus map” is reasonable once a third policy needs the same structure.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

make_policy.hpp
// The policies a configuration can name. `enum class` keeps the names
// inside the type (PolicyKind::lru) and stops them mixing with ints.
enum class PolicyKind { lru, lfu, fifo };
// The one place that knows every policy, so a cache built from a
// configuration file does not need to. Returns a new policy on the heap,
// owned by the std::unique_ptr; std::make_unique<LruPolicy<K>>() creates
// it, and the pointer converts to a pointer to the EvictionPolicy base.
// The caller hands it to the Cache constructor, which takes ownership.
// Each case returns, so the switch needs no break. Throws
// std::invalid_argument for a value that is not one of the three
// (possible only through a cast), and std::bad_alloc if memory runs out.
template <typename K>
[[nodiscard]] std::unique_ptr<EvictionPolicy<K>> make_policy(PolicyKind kind) {
switch (kind) {
case PolicyKind::lru: return std::make_unique<LruPolicy<K>>();
case PolicyKind::lfu: return std::make_unique<LfuPolicy<K>>();
case PolicyKind::fifo: return std::make_unique<FifoPolicy<K>>();
}
throw std::invalid_argument("unknown eviction policy");
}
// Turns a name from configuration into a PolicyKind. Throws
// std::invalid_argument for a name that is not "lru", "lfu", or "fifo".
// std::string_view looks at the caller's characters without copying them;
// `name == "lru"` compares the characters. inline lets this function be
// defined in a header that several .cpp files include.
[[nodiscard]] inline PolicyKind policy_kind(std::string_view name) {
if (name == "lru") return PolicyKind::lru;
if (name == "lfu") return PolicyKind::lfu;
if (name == "fifo") return PolicyKind::fifo;
throw std::invalid_argument("unknown eviction policy");
}

make_policy is the one function that knows every policy. The service reads its configuration, calls policy_kind("lfu"), and passes the result to make_policy; the cache, and every caller of it, never names a concrete policy. Adding a policy means a class, an enumerator, and a case here. Because the switch has no default, the compiler warns (-Wswitch, part of -Wall) if an enumerator is added without a case. The throw after the switch is reached only by a value outside the enumeration, which a cast could make.

Rule Where it lives
Never more than capacity entries Cache::put, the only place that adds an entry
The new key is never its own victim Cache::put, which asks for the victim first
A hit and an overwrite are uses; contains is not Cache::get, Cache::put, and Cache::contains, which never calls the policy
Which key goes each policy’s victim, kept at one end by on_insert, on_access
A failure leaves the cache as it was the order of steps in get and put, and each policy’s rollback
An unknown policy name is an error policy_kind
Counts Cache::get (hits, misses) and Cache::put (evictions)

Take the step 1 demo’s LFU cache of 3 (shown in Scenarios), just after put home, put cart, put deals, two reads of home, and one of cart. The buckets are as in the diagram above. Now put help:

  1. entries_.find("help") fails: a new key.
  2. The cache is full (3 of 3), so victim() returns the back of the first bucket, deals, and put copies it.
  3. try_emplace adds help; the map holds 4 entries for a moment.
  4. on_insert("help"): the first bucket has count 1, so no new bucket is needed; help is spliced to the front of it. The bucket now holds help, then deals.
  5. on_erase("deals") removes deals from the bucket, which still holds help, so the bucket stays. entries_.erase("deals") brings the map back to 3. Evictions: 1.
  6. put returns "deals".

Then get deals misses, and put faq evicts help: it is alone in the bucket for one use. Under LFU, a key that has just arrived is the easiest to evict, which is the policy’s well-known weakness; see LFU’s memory.

One difference from the textbook Strategy: the cache owns its policy (std::unique_ptr) and the policy has state that must match the cache’s entries exactly (INV-2). So a policy cannot be swapped on a cache that is in use; a new policy would not know the keys. The team’s “try a few rules” means one cache per rule, or a restart with a different configuration. That is a fact worth saying to the team, not a flaw to design around. See Strategy, State, and Template Method compared.

A run-time policy or a template parameter?

Section titled “A run-time policy or a template parameter?”

Many LRU caches are written as one class: a list of key and value pairs, and a map from key to node.

IllustrativeA fragment for explanation; not compiled on its own.

// Capacity must be at least 1.
template <typename K, typename V>
class LruCache {
public:
explicit LruCache(std::size_t capacity) : capacity_(capacity) {}
std::optional<V> get(const K& key) {
const auto found = where_.find(key);
if (found == where_.end()) return std::nullopt;
// Move the entry's node to the front: it is now the most recent.
order_.splice(order_.begin(), order_, found->second); // one lookup, then O(1)
// found->second is the list iterator; ->second is the value in
// the key and value pair it points at. Returned as a copy.
return found->second->second;
}
void put(const K& key, V value) {
// An overwrite: replace the value in place and make it the most
// recent. No eviction, since the number of entries is unchanged.
if (const auto found = where_.find(key); found != where_.end()) {
found->second->second = std::move(value);
order_.splice(order_.begin(), order_, found->second);
return;
}
if (order_.size() == capacity_) { // evict first: the new key cannot be the victim
// Erase the map entry first, using the key in the back node,
// then the node itself. In the other order, back() would
// already be a different node, and the wrong key would go.
where_.erase(order_.back().first);
order_.pop_back();
}
order_.emplace_front(key, std::move(value));
where_.emplace(key, order_.begin()); // if this throws, the cache is left inconsistent
}
private:
using Order = std::list<std::pair<K, V>>; // key and value together, most recent first
std::size_t capacity_;
Order order_;
std::unordered_map<K, typename Order::iterator> where_;
};

It is leaner: one hash lookup per get instead of two (the cache’s map and the policy’s map), and each key is stored twice instead of three times (the cache’s map, the policy’s list, and the policy’s map). For a cache that will only ever be LRU, it is a good answer, and in an interview it is often the expected one.

It is also weaker in ways that are easy to miss. It evicts before it inserts, so if the insert then throws, an entry was lost for nothing (the basic guarantee, not the strong one). If where_.emplace throws, the list has a node the map does not know, and a later put of the same key adds a second node. Fixing both takes the same care as Cache::put. And it answers only one of the team’s three questions. This case study keeps the policies separate because the request was to compare them; the price is one extra lookup and one extra copy of each key, stated here rather than hidden.

LFU never forgets. A page read ten thousand times last month keeps its count after nobody wants it, while today’s popular page starts at one and, as the trace showed, is the first to go. Common remedies, none built here:

  • Age the counts. Every so often (every N operations), halve every count. With buckets, that means rebuilding the bucket list, an O(n) step paid once per N operations.
  • Count only recent uses. Keep counts for a window of recent requests only.
  • Protect new keys. Give a new key a short period in which it cannot be evicted, or admit a new key only if it has been asked for before.

Which one fits depends on the traffic, which is why the team’s plan, to compare the policies on its own request log, is the right one. The caching page makes the same point: there is no best policy.

  • No get_or_load in step 1. The team’s code builds the page on a miss. A loading cache is easy to add, and step 2 adds one, because it is what makes sharing between threads interesting.
  • No limit in bytes. Pages are about the same size. A byte limit would need a size function for V, and a put that can evict several entries.
  • No iteration over entries. No one asked, and an iterator would have to say whether visiting an entry counts as a use.
  • No resize. Changing the capacity of a running cache is a small change (evict until the size fits), but no one asked.

The example has two steps, each a complete program with its own tests:

  • Step 1 is the design above: the cache, the three policies, the factory, and the counts.
  • Step 2 is the change: entries that expire, and a wrapper that lets many threads share a cache. See When the requirements change.

The order inside step 1 is worth copying. The interface and its contract came first, then LruPolicy and the cache, tested together with the LRU tests. Then the model test, before LFU existed, so that LFU was checked against the model from its first run. Then LFU and FIFO, then the failure tests with a policy that throws on purpose.

The demo sends the same nine requests to three caches of 3, one per policy: put home, put cart, put deals, get home, get home, get cart, put help, get deals, put faq.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

main.cpp
// One request: a put (store the page) if is_put is true, otherwise a get.
struct Request {
bool is_put;
std::string page;
};
// The nine requests every cache receives, in order, read across the rows:
// put home, put cart, put deals, get home, get home, get cart, put help,
// get deals, put faq.
const std::vector<Request> requests = {
{true, "home"}, {true, "cart"}, {true, "deals"}, {false, "home"},
{false, "home"}, {false, "cart"}, {true, "help"}, {false, "deals"},
{true, "faq"},
};
// Sends the requests to a new cache of 3 that uses the named policy, then
// prints what was evicted, what is left, and the counts. The name goes
// through policy_kind and make_policy, as a name read from a
// configuration file would.
void run(std::string_view policy_name) {
Cache<std::string, std::string> pages(3, make_policy<std::string>(policy_kind(policy_name)));
std::string evicted; // the evicted keys, each after a space
for (const Request& request : requests) {
if (!request.is_put) {
// get is [[nodiscard]]; the value is not needed here, only the
// effect on the policy and the counts, so it is cast to void.
static_cast<void>(pages.get(request.page));
} else if (const auto gone = pages.put(request.page, "<html>" + request.page + "</html>")) {
// `else if (const auto gone = ...)` declares gone and tests it:
// the branch runs only when put returned an evicted key, and
// *gone reads that key.
evicted += ' ' + *gone;
}
}
// Which of the five pages the cache still holds. contains is used,
// not get, because contains does not count as a use or a hit.
std::string holds;
for (const char* page : {"home", "cart", "deals", "help", "faq"}) {
if (pages.contains(page)) holds += ' ' + std::string(page);
}
std::cout << policy_name << ": evicted" << evicted << "; holds" << holds << "; hits "
<< pages.stats().hits << ", misses " << pages.stats().misses << '\n';
}
Expected output
lru: evicted deals home; holds cart help faq; hits 3, misses 1
lfu: evicted deals help; holds home cart faq; hits 3, misses 1
fifo: evicted home cart; holds deals help faq; hits 4, misses 0

Read each line against the policy:

  • LRU evicts deals for help, because deals was last touched before the three reads, then evicts home for faq. The get deals in between misses.
  • LFU evicts deals (one use) for help, and then help itself (by then alone in the one-use bucket) for faq. home and cart, read earlier, survive.
  • FIFO evicts in arrival order, home and then cart, and ignores the reads. It keeps deals, so get deals hits: four hits and no miss, the best of the three on this sequence.

FIFO winning on nine requests says nothing about real traffic. It is a reminder of the team’s own plan: compare the policies on a recording of real requests, with these counts.

The tests are named after the acceptance criteria and run against the real cache and the real policies, with no mocks. See Testing basics.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_step1.cpp
// LLD_TEST(name) defines one test. LLD_CHECK(condition) records a failure
// if the condition is false; LLD_CHECK_EQ(actual, expected) does the same
// for actual == expected and prints both values when they differ. They
// come from the site's small test header, lld_test.hpp. Each test builds
// its own small cache with make_cache(capacity, policy).
//
// A put then a get of the same key gives back the value, and a put of a
// new key into a cache with room evicts nothing (has_value() is false).
LLD_TEST(ac_1_1_get_returns_what_was_put) {
Pages pages = make_cache(2, PolicyKind::lru);
LLD_CHECK(!pages.put("home", "<h1>home</h1>").has_value());
LLD_CHECK(pages.get("home") == std::optional<std::string>("<h1>home</h1>"));
LLD_CHECK_EQ(pages.size(), std::size_t{1});
}
// A get from an empty cache misses. CacheStats{0, 1, 0} is hits 0,
// misses 1, evictions 0. The extra brackets keep the macro from reading
// the commas inside the braces as separate macro arguments.
LLD_TEST(ac_1_2_a_miss_returns_nothing_and_is_counted) {
Pages pages = make_cache(2, PolicyKind::lru);
LLD_CHECK(!pages.get("home").has_value());
LLD_CHECK(pages.stats() == (CacheStats{0, 1, 0}));
}
// The cache is full (2 of 2) when home is written again. That is an
// overwrite, not a new key, so nothing is evicted and cart stays.
LLD_TEST(ac_1_3_an_overwrite_replaces_the_value_and_never_evicts) {
Pages pages = make_cache(2, PolicyKind::lru);
pages.put("home", "v1");
pages.put("cart", "v1");
LLD_CHECK(!pages.put("home", "v2").has_value()); // full, but not a new key
LLD_CHECK(pages.get("home") == std::optional<std::string>("v2"));
LLD_CHECK(pages.contains("cart"));
LLD_CHECK_EQ(pages.stats().evictions, std::size_t{0});
}
// erase returns true the first time and false the second, and does not
// count as an eviction. Run under LFU, whose on_erase also removes the
// emptied bucket, and the invariants are checked after.
LLD_TEST(ac_1_4_erase_removes_and_is_not_an_eviction) {
Pages pages = make_cache(2, PolicyKind::lfu);
pages.put("home", "v1");
LLD_CHECK(pages.erase("home"));
LLD_CHECK(!pages.erase("home"));
LLD_CHECK(!pages.contains("home"));
LLD_CHECK_EQ(pages.stats().evictions, std::size_t{0});
LLD_CHECK(pages.invariants_hold());
}

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_step1.cpp
// Each test fills a small cache, uses some keys, and checks which key the
// next new put evicts: put returns it.
//
// LRU, no reads: home is the oldest, so it goes when deals arrives.
LLD_TEST(ac_2_1_lru_evicts_the_least_recently_used) {
Pages pages = make_cache(2, PolicyKind::lru);
pages.put("home", "v");
pages.put("cart", "v");
LLD_CHECK(pages.put("deals", "v") == std::optional<std::string>("home"));
LLD_CHECK_EQ(pages.stats().evictions, std::size_t{1});
}
// Reading home makes cart the least recently used, so cart goes.
LLD_TEST(ac_2_2_under_lru_a_get_protects_a_key) {
Pages pages = make_cache(2, PolicyKind::lru);
pages.put("home", "v");
pages.put("cart", "v");
static_cast<void>(pages.get("home"));
LLD_CHECK(pages.put("deals", "v") == std::optional<std::string>("cart"));
}
// The same as ac_2_1 with a contains of home first. home still goes, so
// contains did not count as a use; and the stats show no hit or miss.
LLD_TEST(ac_2_3_contains_does_not_count_as_a_use) {
Pages pages = make_cache(2, PolicyKind::lru);
pages.put("home", "v");
pages.put("cart", "v");
LLD_CHECK(pages.contains("home"));
LLD_CHECK(pages.put("deals", "v") == std::optional<std::string>("home"));
LLD_CHECK(pages.stats() == (CacheStats{0, 0, 1}));
}
// FIFO: a read and an overwrite of home do not save it. It arrived
// first, so it goes first.
LLD_TEST(ac_3_1_fifo_ignores_uses) {
Pages pages = make_cache(2, PolicyKind::fifo);
pages.put("home", "v");
pages.put("cart", "v");
static_cast<void>(pages.get("home"));
pages.put("home", "v2");
LLD_CHECK(pages.put("deals", "v") == std::optional<std::string>("home"));
}
// LFU: home has 3 uses (put and two gets), cart 2 (put and one get). cart
// goes, although it was used more recently: under LFU the count wins.
LLD_TEST(ac_3_2_lfu_evicts_the_key_used_least_often) {
Pages pages = make_cache(2, PolicyKind::lfu);
pages.put("home", "v");
pages.put("cart", "v");
static_cast<void>(pages.get("home"));
static_cast<void>(pages.get("home"));
static_cast<void>(pages.get("cart")); // cart is now the most recent
LLD_CHECK(pages.put("deals", "v") == std::optional<std::string>("cart"));
}
// LFU tie: all three keys reach 2 uses, in the order cart, home, deals.
// The one whose last use is oldest, cart, goes.
LLD_TEST(ac_3_3_lfu_breaks_a_tie_by_least_recent_use) {
Pages pages = make_cache(3, PolicyKind::lfu);
pages.put("home", "v");
pages.put("cart", "v");
pages.put("deals", "v");
static_cast<void>(pages.get("cart"));
static_cast<void>(pages.get("home")); // home and cart: 2 uses each, cart first
static_cast<void>(pages.get("deals")); // deals: 2 uses, most recent
LLD_CHECK(pages.put("help", "v") == std::optional<std::string>("cart"));
}
// The case the flawed "add, then evict" put gets wrong. Both old keys
// have 2 uses, and the new key would have 1, the lowest. The victim must
// still be an old key: home, whose last use is older than cart's.
LLD_TEST(ac_3_4_the_key_being_added_is_never_its_own_victim) {
Pages pages = make_cache(2, PolicyKind::lfu);
pages.put("home", "v");
pages.put("cart", "v");
static_cast<void>(pages.get("home"));
static_cast<void>(pages.get("cart")); // both have 2 uses; a new key has 1
LLD_CHECK(pages.put("deals", "v") == std::optional<std::string>("home"));
LLD_CHECK(pages.contains("deals"));
}
// An overwrite is a use. Under LRU, rewriting home makes cart the oldest.
// Under LFU, the overwrites give home 2 uses and cart 3, so home goes.
LLD_TEST(ac_3_5_an_overwrite_counts_as_a_use) {
Pages lru = make_cache(2, PolicyKind::lru);
lru.put("home", "v");
lru.put("cart", "v");
lru.put("home", "v2");
LLD_CHECK(lru.put("deals", "v") == std::optional<std::string>("cart"));
Pages lfu = make_cache(2, PolicyKind::lfu);
lfu.put("home", "v");
lfu.put("cart", "v");
lfu.put("home", "v2");
lfu.put("cart", "v2");
lfu.put("cart", "v3"); // cart: 3 uses, home: 2
LLD_CHECK(lfu.put("deals", "v") == std::optional<std::string>("home"));
}
// Each name gives a working policy (in a cache of 1, the second key
// evicts the first under every policy), and an unknown name throws.
// LLD_CHECK_THROWS(expression, type) fails unless the expression throws
// that type; policy_kind is [[nodiscard]], so its unused result is cast
// to void.
LLD_TEST(ac_3_6_a_policy_is_chosen_by_name) {
for (const char* name : {"lru", "lfu", "fifo"}) {
Pages pages(1, make_policy<std::string>(policy_kind(name)));
pages.put("home", "v");
LLD_CHECK(pages.put("cart", "v") == std::optional<std::string>("home"));
}
LLD_CHECK_THROWS(static_cast<void>(policy_kind("random")), std::invalid_argument);
}

Each policy test sets up the smallest state that tells the policies apart. ac_3_2 reads cart last, so a policy that evicted by recency instead of count would choose home and fail. ac_3_4 makes every existing key reach two uses, so that a new key with one use would be the lowest, which is exactly the state the flawed insert-then-evict put gets wrong.

Failures on purpose. A FlakyPolicy wraps an LruPolicy and throws std::bad_alloc from on_insert or on_access when told to, and a Fragile value throws when copied. These are test doubles for the one thing a real run rarely shows: memory running out at the worst moment.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_step1.cpp
// FlakyPolicy (defined above, not shown) is an LruPolicy that throws
// std::bad_alloc from on_insert while fail_insert is true, and from
// on_access while fail_access is true. Fragile is a value whose copy
// throws std::runtime_error while Fragile::fail_copy is true.
//
// A put of a new key into a full cache, whose on_insert fails, must leave
// both old keys, add nothing, and count no eviction. Once the policy
// works again, the same put evicts home as usual.
LLD_TEST(ac_6_1_a_failed_insert_evicts_nothing) {
// The cache will own the policy, but the test needs to flip its
// switches. So it keeps a plain reference, taken before the
// unique_ptr is moved into the cache. The object itself stays where
// it is on the heap, and the cache keeps it alive for the whole test,
// so the reference stays valid. owner is empty after the move.
auto owner = std::make_unique<FlakyPolicy>();
FlakyPolicy& policy = *owner;
Pages pages(2, std::move(owner));
pages.put("home", "v");
pages.put("cart", "v");
policy.fail_insert = true;
LLD_CHECK_THROWS(pages.put("deals", "v"), std::bad_alloc);
LLD_CHECK(pages.contains("home"));
LLD_CHECK(pages.contains("cart"));
LLD_CHECK(!pages.contains("deals"));
LLD_CHECK(pages.stats() == (CacheStats{0, 0, 0}));
LLD_CHECK(pages.invariants_hold());
policy.fail_insert = false;
LLD_CHECK(pages.put("deals", "v") == std::optional<std::string>("home"));
}
// on_access fails. The overwrite throws before the new value is stored,
// and the get throws after its copy but before counting the hit, so
// neither leaves a trace: no hit is counted, and home still holds v1.
LLD_TEST(ac_6_2_a_failed_access_leaves_the_old_value) {
auto owner = std::make_unique<FlakyPolicy>();
FlakyPolicy& policy = *owner;
Pages pages(2, std::move(owner));
pages.put("home", "v1");
policy.fail_access = true;
LLD_CHECK_THROWS(pages.put("home", "v2"), std::bad_alloc);
LLD_CHECK_THROWS(static_cast<void>(pages.get("home")), std::bad_alloc);
LLD_CHECK(pages.stats() == (CacheStats{0, 0, 0}));
policy.fail_access = false;
LLD_CHECK(pages.get("home") == std::optional<std::string>("v1"));
}
// The copy of the value inside get fails. get copies before it tells the
// policy, so home was not used: it is still the least recently used, and
// it is the one evicted when deals arrives.
LLD_TEST(ac_6_3_a_failed_copy_is_not_a_use) {
Cache<std::string, Fragile> cache(2, make_policy<std::string>(PolicyKind::lru));
cache.put("home", Fragile(1));
cache.put("cart", Fragile(2));
Fragile::fail_copy = true;
LLD_CHECK_THROWS(static_cast<void>(cache.get("home")), std::runtime_error);
Fragile::fail_copy = false;
LLD_CHECK(cache.stats() == (CacheStats{0, 0, 0}));
// home was not used, so it is still the least recently used
LLD_CHECK(cache.put("deals", Fragile(3)) == std::optional<std::string>("home"));
}

Checking the contract. A policy trusts the cache to keep its contract, and in a release build it does not check. CheckedPolicy wraps a real policy and counts every break: a key inserted twice, a key used or erased that is not tracked, a victim asked of an empty policy.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_step1.cpp
// Wraps a real policy and records every break of the contract the cache
// promised to keep: inserting a key that is tracked, using or erasing
// one that is not, asking for a victim when nothing is tracked. The
// tests read the count of breaks after each run.
//
// It is a policy itself, so the cache cannot tell it from a real one. It
// owns the real policy and passes every call on to it, after checking
// the call against tracked_, its own set of the keys the real policy
// should be tracking. breaks_ is a reference to an int owned by the test,
// so the test can read the count while the cache owns this object. That
// int must outlive the cache.
template <typename K>
class CheckedPolicy final : public EvictionPolicy<K> {
public:
CheckedPolicy(std::unique_ptr<EvictionPolicy<K>> real, int& breaks)
: real_(std::move(real)), breaks_(breaks) {}
// Each member: count a break if the call breaks the contract, then do
// what the real policy does, then keep tracked_ in step with it.
void on_insert(const K& key) override {
if (tracked_.contains(key)) ++breaks_;
real_->on_insert(key);
tracked_.insert(key);
}
void on_access(const K& key) override {
if (!tracked_.contains(key)) ++breaks_;
real_->on_access(key);
}
void on_erase(const K& key) noexcept override {
// std::set::erase returns how many keys it removed: 1 if the key
// was tracked, 0 if not (a break).
if (tracked_.erase(key) != 1) ++breaks_;
real_->on_erase(key);
}
// victim is const, yet it adds to breaks_: const stops this object's
// own members changing, and breaks_ is only a reference to an int that
// lives elsewhere, so the int itself may change.
[[nodiscard]] const K& victim() const noexcept override {
if (tracked_.empty()) ++breaks_;
return real_->victim();
}
[[nodiscard]] std::size_t size() const noexcept override { return real_->size(); }
private:
std::unique_ptr<EvictionPolicy<K>> real_;
std::set<K> tracked_;
int& breaks_;
};

Checking every victim. Working out the expected victim by hand is fine for ten operations and hopeless for ten thousand. The Model is the slowest correct cache anyone could write: each entry remembers when it was inserted, when it was last used, and how many times, and the victim is found by looking at all of them.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_step1.cpp
// The simplest thing that could be right: every entry remembers when it
// was inserted, when it was last used, and how often, and the victim is
// found by looking at all of them. O(n), but easy to check by eye. The
// real policies must choose exactly the same victims.
//
// Time is a counter, tick_, that goes up by one for every insert and use,
// so "earlier" simply means "a smaller tick". Keys and values are ints.
class Model {
public:
Model(std::size_t capacity, PolicyKind kind) : capacity_(capacity), kind_(kind) {}
// Same behaviour as Cache::get: a hit is a use.
std::optional<int> get(int key) {
const auto found = entries_.find(key);
if (found == entries_.end()) return std::nullopt;
use(found->second);
return found->second.value;
}
// Same behaviour as Cache::put: an overwrite is a use and never
// evicts; a new key into a full model evicts first, so the new key can
// never be chosen. A new entry starts with one use, and its last use
// and its insert both at the new tick.
std::optional<int> put(int key, int value) {
if (const auto found = entries_.find(key); found != entries_.end()) {
found->second.value = value;
use(found->second);
return std::nullopt;
}
std::optional<int> victim;
if (entries_.size() == capacity_) {
victim = choose_victim();
entries_.erase(*victim);
}
++tick_;
entries_[key] = Info{value, 1, tick_, tick_}; // value, uses, last_use, inserted
return victim;
}
bool erase(int key) { return entries_.erase(key) == 1; }
[[nodiscard]] std::size_t size() const { return entries_.size(); }
private:
struct Info {
int value;
std::size_t uses;
std::size_t last_use;
std::size_t inserted;
};
// ++tick_ adds one first, then gives the new value, so every use gets
// a tick no other insert or use has.
void use(Info& info) {
++info.uses;
info.last_use = ++tick_;
}
// Looks at every entry and keeps the one that should go first.
// first(a, b) answers "should a go before b?" under this model's
// policy. The lambda captures `this` so it can read kind_.
// LRU: the older last use goes first.
// FIFO: the older insert goes first.
// LFU: fewer uses goes first; for equal uses, the older last use.
// Ticks are never equal, so there is never a tie to break further.
// The final `return false` is never reached; it keeps the compiler
// sure that the lambda returns on every path.
[[nodiscard]] int choose_victim() const {
const auto first = [this](const Info& a, const Info& b) {
switch (kind_) {
case PolicyKind::lru: return a.last_use < b.last_use;
case PolicyKind::fifo: return a.inserted < b.inserted;
case PolicyKind::lfu:
return a.uses != b.uses ? a.uses < b.uses : a.last_use < b.last_use;
}
return false;
};
// Start with any entry as the best so far, and replace it whenever
// another one should go before it. Called only when the model is
// full, so entries_ is not empty and begin() is a real entry.
auto best = entries_.begin();
for (auto it = entries_.begin(); it != entries_.end(); ++it) {
if (first(it->second, best->second)) best = it;
}
return best->first; // the key
}
std::size_t capacity_;
PolicyKind kind_;
std::map<int, Info> entries_;
std::size_t tick_ = 0;
};

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_step1.cpp
// 20,000 random operations per policy on a cache of 5 and 12 keys, with
// a fixed seed so a failure can be repeated. After every operation the
// cache must agree with the model, the invariants must hold, and the
// cache must not have broken the policy contract.
LLD_TEST(inv_every_policy_matches_the_model) {
for (const PolicyKind kind : {PolicyKind::lru, PolicyKind::lfu, PolicyKind::fifo}) {
// Declared before the cache, so it outlives the CheckedPolicy that
// holds a reference to it.
int breaks = 0;
// The real policy for this kind, wrapped in a CheckedPolicy, owned
// by the cache. The model gets the same capacity and kind.
Cache<int, int> cache(5, std::make_unique<CheckedPolicy<int>>(make_policy<int>(kind), breaks));
Model model(5, kind);
std::mt19937 random(2026); // the engine's output is fixed by the standard
int disagreements = 0;
for (int step = 0; step < 20'000; ++step) {
// random() gives the next number; % 12 turns it into a key from
// 0 to 11, and % 10 into a number from 0 to 9 that picks the
// operation: 0-4 get (half), 5-8 put (four in ten), 9 erase.
const int key = static_cast<int>(random() % 12);
const unsigned op = random() % 10;
// The cache and the model get the same call; their results are
// compared (std::optional values compare equal when both are
// empty, or both hold equal values). The put value is the
// step number, so a stale value would show.
if (op < 5) {
if (cache.get(key) != model.get(key)) ++disagreements;
} else if (op < 9) {
if (cache.put(key, step) != model.put(key, step)) ++disagreements;
} else {
if (cache.erase(key) != model.erase(key)) ++disagreements;
}
if (cache.size() != model.size() || !cache.invariants_hold()) ++disagreements;
}
LLD_CHECK_EQ(disagreements, 0);
LLD_CHECK_EQ(breaks, 0);
LLD_CHECK(cache.stats().evictions > 1000); // the run really did evict
}
}
How this code works: The model and the model test

How the model picks a victim. choose_victim walks over every entry and keeps the best so far, best. The lambda first(a, b) answers “should a go before b?” for this model’s policy. Whenever the entry being looked at should go before best, it becomes the new best. Every insert and every use takes the next value of tick_, so two entries never have the same last use or the same insert time.

For example, suppose an LFU model (these entries are made up) holds key 3 with 2 uses, last used at tick 7; key 5 with 1 use, last used at tick 9; and key 8 with 1 use, last used at tick 4. A std::map visits keys in order:

Entry looked at Compared with best Result best after
3 3 (itself) not before itself 3
5 3 1 use is fewer than 2 5
8 5 same uses; tick 4 is older than tick 9 8

So key 8 is the victim. That one line of comparison is all of FR-3; the buckets in LfuPolicy must reach the same answer by a faster route.

How the test uses it. For each policy, the test builds a real cache of 5 (its policy wrapped in a CheckedPolicy) and a model of 5. Then, 20,000 times:

  1. Draw a key from 0 to 11 and an operation: get (half the time), put (four times in ten), or erase (one time in ten).
  2. Do the same operation on both, and compare what they return: the value for a get, the evicted key for a put, and true or false for an erase. Any difference adds one to disagreements.
  3. Compare their sizes, and check the cache’s invariants.

At the end, there must be no disagreement, no broken promise to the policy, and more than 1,000 evictions. With 12 keys and room for 5, the cache is often full, so many puts of a new key evict, and every one of those victims is checked against the model.

The model test runs 20,000 random operations per policy on a cache of 5 with 12 keys, so the cache is nearly always full and evicts often (the test checks that it evicted more than 1,000 times, so a change that stopped evicting would not pass quietly). After every operation, the real cache and the model must return the same value or the same victim, have the same size, and the invariants must hold; and the CheckedPolicy must have seen no broken promise. The seed is fixed, and std::mt19937’s output is fixed by the standard, so a failure repeats exactly. This is a simple form of property-based testing: the property is “behaves like the model”.

The model is only useful because it is obviously right. Its tie rule for LFU, a.uses != b.uses ? a.uses < b.uses : a.last_use < b.last_use, is FR-3 in one line; the buckets are FR-3 in fifty. If the model were as clever as the policies, it could share their bugs.

Did the tests check enough? The step 2 code (which contains all of step 1) was changed in 34 small ways. The changes were written by hand; a script applied them one at a time to a copy of the code and ran the step 2 tests after each. They included: a hit that is not a use, a use recorded before the copy, each count left out, an entry returned after its deadline or removed one tick late, a put that evicts before it removes expired entries, a zero time to live accepted, an overwrite that keeps the old deadline or is not a use, evicting one entry early, a failed insert that leaves the entry or the deadline behind, a removal that forgets the deadline or the policy, contains ignoring expiry, erase counted as an eviction, LRU not moving a key or evicting the newest, LFU breaking ties the wrong way, not counting a use, skipping a count, or making a second bucket for one use, FIFO moving keys on access, put or get without the lock (built with ThreadSanitizer), and a loaded value that is not kept or ignores its time to live.

The last one survived the first run: no test passed a time to live to get_or_load. ac_8_5 was added for it. After that, 33 of the 34 changes made at least one test fail (four by crashing, and the two lock changes by a race report).

One change still passes every test: an LfuPolicy::on_erase that leaves an emptied bucket in the list. The cache cannot see the difference, for two reasons. First, on_access never leaves an empty bucket at the front: a key leaving the bucket before an empty one either moves into it (if its count is one higher) or into a new bucket inserted before it. So an empty first bucket can only come from on_erase, an eviction, or an expiry, and each of those leaves the cache with room. Second, victim() is only asked when the cache is full again, which takes at least one put of a new key, and that put’s on_insert puts a non-empty bucket for one use at the front. A random test that compared this change with the real policy over millions of operations, run during the review of this page, found no difference. The harm is memory: a long-running cache would collect empty buckets. Catching it would need a test that looks inside the policy (a bucket count for tests), and this example does not add one. A change that survives is either a missing test or a rule whose effect cannot be seen from outside; this one is the second, and the comment “never empty” in LfuPolicy is the only thing that holds it.

Run the tests with:

Terminal window
cd examples
cmake --preset gcc-debug
cmake --build --preset gcc-debug
ctest --preset gcc-debug -R cs_cache

Two months later, the team comes back with two requests:

“Some of what we cache now is login sessions. A session must vanish 30 minutes after it was stored, even if the cache has room. And we want one cache per process, shared by all our request threads.”

New requirements.

  • FR-7 Time to live. put may give an entry a time to live. Once it has passed, get and contains treat the entry as absent. An entry without one never expires. An overwrite replaces the old time to live, or removes it.
  • FR-8 Expired before live. When a put needs room, expired entries are removed first; a live entry is evicted only if the cache is still full.
  • FR-9 Shared. A wrapper lets many threads use one cache.
  • FR-10 Loading. get_or_load(key, load) returns the cached value, or calls load(key), caches the result, and returns it. A slow load must not hold up other keys.
  • NFR-5 Testable time. The cache reads the time from a Clock passed in, so the tests move time by hand and nothing sleeps.
File Change
clock.hpp new: Clock, SteadyClock, and ManualClock for tests
cache.hpp a deadline per entry, a map of deadlines, remove_expired, expirations in CacheStats
synchronized_cache.hpp new: SynchronizedCache, one mutex around a Cache, and get_or_load
the three policies, make_policy unchanged
the step 1 tests unchanged, except that every cache now takes a clock

The policies did not change at all. Expiry is a second reason for an entry to leave, and the cache tells the policy with the same on_erase it already used for erase and eviction. That is the interface earning its keep.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

clock.hpp
// Where the cache gets the time. Production code passes SteadyClock;
// the tests and the demo pass ManualClock and move time forward by hand,
// so expiry is checked exactly and nothing sleeps.
//
// An interface with one question, now(). The cache holds a `const Clock&`
// and never knows which clock it has.
class Clock {
public:
// A point in time as std::chrono::steady_clock measures it. Both
// clocks below return this type, so the cache can mix their times
// with durations such as 30min or 100ms.
using time_point = std::chrono::steady_clock::time_point;
virtual ~Clock() = default;
[[nodiscard]] virtual time_point now() const = 0;
// Protected, as in EvictionPolicy: a Clock cannot be copied through a
// base-class reference, which would slice it.
protected:
Clock() = default;
Clock(const Clock&) = default;
Clock& operator=(const Clock&) = default;
};
// A steady clock never goes back, even when someone changes the
// computer's date, so an age measured with it never comes out negative
// or jumps because of a date change.
class SteadyClock final : public Clock {
public:
[[nodiscard]] time_point now() const override { return std::chrono::steady_clock::now(); }
};
// A clock that moves only when advance is called. A test can stop at
// exactly 99 ms, then at exactly 100 ms, which a real clock cannot do.
class ManualClock final : public Clock {
public:
[[nodiscard]] time_point now() const override { return now_; }
// Throws std::invalid_argument for a negative step, and then the time
// is unchanged. Any duration that converts to milliseconds without
// loss can be passed, so advance(29min) works. Not safe to call while
// another thread calls now().
void advance(std::chrono::milliseconds step) {
if (step.count() < 0) {
throw std::invalid_argument("a steady clock never goes back");
}
now_ += step;
}
private:
time_point now_{}; // the epoch; only differences matter
};

This is the same Clock as on the caching page. It is a steady clock, which never goes back, so a change to the computer’s date cannot make an entry expire early or live for ever. The cache holds a const Clock&, which adds the first lifetime rule to this design: the clock must outlive the cache. In main, that is the order of two declarations; in a test, the ManualClock is a local declared before the cache.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

cache.hpp
// Step 1's put, plus a deadline. ttl is an optional time to live: no ttl
// means the entry never expires. Returns the evicted key, if any. Throws
// std::invalid_argument for a ttl of zero or less, before changing
// anything. If a later step throws, the live entries are as they were and
// no new deadline is left behind (only already expired entries may have
// gone).
template <typename K, typename V>
std::optional<K> Cache<K, V>::put(const K& key, V value, std::optional<Ttl> ttl) {
// `ttl &&` first: *ttl is read only when the optional holds a value.
if (ttl && *ttl <= Ttl::zero()) throw std::invalid_argument("a time to live must be positive");
// Read the clock once, so every step below agrees on what "now" is.
const TimePoint now = clock_.now();
// Removes, from the front of deadlines_, every entry whose deadline is
// at or before now, and counts each as an expiration. It does not
// throw. After it, every entry left is live, including `key` if it is
// there, so an overwrite below never revives an expired entry.
remove_expired(now); // an expired entry goes before any live one is evicted
// The new deadline is made first, and dropped again if a later step
// throws, so a failed put leaves no deadline behind.
// With a ttl: add (now + ttl, key) to the multimap and keep the
// iterator to it. Without one: deadlines_.end(), which means "never".
// `?:` picks one; both sides have the same iterator type.
const auto deadline = ttl ? deadlines_.emplace(now + *ttl, key) : deadlines_.end(); // may throw
// The undo for that step, as a small function. [&] lets it use
// `deadline` and this cache by reference. It does nothing when there
// is no new deadline; noexcept, because erasing through an iterator
// cannot fail.
const auto drop_deadline = [&]() noexcept {
if (deadline != deadlines_.end()) deadlines_.erase(deadline);
};
// The key is there (and live): an overwrite, which is a use.
if (const auto found = entries_.find(key); found != entries_.end()) {
try {
policy_->on_access(key);
} catch (...) {
drop_deadline(); // the old value and old deadline are untouched
throw;
}
// Nothing below throws. Replace the value, drop the old deadline
// (if it had one), and point the entry at the new one, which may
// be end(): an overwrite without a ttl stops the entry expiring.
Entry& entry = found->second;
entry.value = std::move(value);
if (entry.deadline != deadlines_.end()) deadlines_.erase(entry.deadline);
entry.deadline = deadline;
return std::nullopt;
}
// A new key. As in step 1, choose the victim first, so the new key
// cannot be chosen; because expired entries are already gone, the
// cache is full only if all its entries are live. added is declared
// here so that the second try below can use it.
std::optional<K> victim;
typename Entries::iterator added;
try {
// Copying the victim's key and adding the entry may each throw;
// either way, the only change so far is the new deadline.
if (entries_.size() == capacity_) victim.emplace(policy_->victim());
added = entries_.try_emplace(key, Entry{std::move(value), deadline}).first;
} catch (...) {
drop_deadline();
throw;
}
try {
policy_->on_insert(key);
} catch (...) {
// Undo both changes, newest first: the entry, then its deadline.
entries_.erase(added);
drop_deadline();
throw;
}
// Nothing below throws. remove forgets the victim everywhere: in the
// policy, in deadlines_ (if it had one), and in entries_.
if (victim) {
remove(entries_.find(*victim));
++stats_.evictions;
}
return victim;
}
How this code works: Cache::put with deadlines

The order of the steps is what gives the guarantee, so here it is with what each step can do if it fails.

Step Can it throw? What is undone if it does
1. Check the ttl yes, for 0 or less nothing has changed yet
2. remove_expired(now) no (expired entries are gone for good)
3. Add the new deadline, if there is a ttl yes, it allocates nothing else has changed yet
4a. Overwrite: on_access yes drop_deadline removes the new deadline
4b. Overwrite: store the value and deadline no (none needed)
5a. New key: copy the victim, add the entry yes drop_deadline
5b. New key: on_insert yes erase the entry, then drop_deadline
5c. New key: evict the victim no (none needed)

Two details make this work. Step 2 comes before everything else, so once it is done, every entry left is live: an overwrite never brings an expired entry back, and a cache that is still full is full of live entries, so only then is a live one evicted (FR-8). And the new deadline is made at step 3, early, because it is the one step that can fail before any entry changes; every later failure removes it with the same small lambda, drop_deadline.

A worked example: the step 2 demo’s put s-102. The cache has room for 2 and holds s-101 (deadline 30 minutes) and config (no deadline). The clock reads exactly 30 minutes.

  1. The ttl, 30 minutes, is positive.
  2. remove_expired: the first deadline is 30 minutes, which is not after now, so s-101 is removed from the policy, the deadlines, and the entries, and counted as an expiration. No deadlines are left, so the loop stops.
  3. The new deadline, 60 minutes for s-102, is added.
  4. s-102 is a new key. The cache holds 1 entry of 2, so no victim is chosen. The entry is added, and on_insert succeeds.
  5. victim is empty, so nothing is evicted, and put returns std::nullopt: the demo prints “evicted nothing”.

Each entry with a time to live has a deadline, now + ttl. The deadlines are kept in a std::multimap from time to key, in time order, so the expired entries are always at its front, and removing them is a loop that stops at the first deadline still in the future. A multimap, because two entries may share a deadline. Each entry keeps an iterator to its own deadline, so removing an entry removes its deadline without a search; an entry with no time to live holds deadlines_.end(), meaning “never”.

This is the structure the caching page asks for when entries have different lifetimes: its cache could use one list in write order only because every entry there had the same time to live.

Entries and their deadlines in the step 2 demo, just before put s-102
Text description of the diagram

The map entries_ holds two entries. s-101 holds token-a and an iterator to its deadline, 30 minutes, which is the only entry in the multimap deadlines_. config holds dark-mode and the multimap’s end iterator, which means it never expires. The multimap is in time order, so an expired deadline is always at its front.

Diagram source (Mermaid)
flowchart LR
subgraph entries ["entries_ (unordered_map from key to Entry)"]
  e1["s-101: token-a"]
  e2["config: dark-mode"]
end
subgraph deadlines ["deadlines_ (multimap from time to key, earliest first)"]
  d1["30 min: s-101"]
end
e1 -. "deadline" .-> d1
e2 -. "deadline is end(): never" .-> N["no deadline"]

How the rules above turned into code:

  • put removes expired entries first (FR-8): remove_expired(now) is its first step after checking the time to live. Each entry is removed once, so the cost of these loops over the life of the cache is at most one removal per entry ever added. This narrows the strong guarantee a little, and the comment on the class says so: a put that throws may already have removed expired entries and counted them as expirations. No caller could have read those entries, but size and the counts can show that they went.
  • The new deadline is made first, and dropped if a later step throws. deadlines_.emplace allocates, so it may throw; doing it before anything else means that a failure leaves nothing to undo, and every later failure undoes it with drop_deadline (AC-7.7).
  • get of an expired entry removes it and counts a miss and an expiration. contains cannot remove anything (it is const), so it only reports false.
  • size counts expired entries not yet removed, and the comment says so. remove_expired() is public, for a caller that wants to sweep, say, once a minute.
  • The cache is neither copyable nor movable. Every entry without a deadline holds deadlines_.end(). Moving a std::multimap keeps its elements (and iterators to them) but not its end(), so a moved cache would hold end() iterators of the wrong map. Rather than fix them up in a hand-written move, step 2 deletes the copy operations, which also removes the moves. A std::optional iterator, with nullopt for “never”, would have let the cache be move-constructed (not move-assigned: the const Clock& member already rules that out), at the cost of a slightly bigger entry.

NFR-1 changes with this: a put with a time to live adds a multimap insert, which is O(log n); removing a deadline through its iterator is amortized O(1). Entries without a time to live cost what they did in step 1.

The invariants gain one:

  • INV-5 Deadlines match. Every deadline names an entry whose own deadline iterator points back at it, and each entry has at most one. Kept by put, remove, and the rollback in put; checked in invariants_hold, which is O(n) in step 2.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

synchronized_cache.hpp
// A Cache that many threads can share. Every call takes one mutex for
// the whole of the Cache call, so each call sees and leaves the cache
// whole, and the stats add up.
//
// A plain mutex, not a reader-writer lock: get is not a read. A hit
// tells the policy, and the policy moves the key (LRU) or changes its
// count (LFU), so two gets at once would race on the policy's lists.
//
// Lifetime: the clock must outlive the cache, and its now() must be safe
// to call from several threads at once (SteadyClock's is).
//
// The wrapper owns the Cache by value and offers the same members. Each
// one but get_or_load (below) is two lines: lock, then call the cache.
template <typename K, typename V>
class SynchronizedCache {
public:
using Ttl = typename Cache<K, V>::Ttl;
// Builds the Cache inside the wrapper, passing on its arguments; the
// policy is moved along, so the Cache ends up owning it. Throws what
// the Cache constructor throws.
SynchronizedCache(std::size_t capacity, std::unique_ptr<EvictionPolicy<K>> policy,
const Clock& clock)
: cache_(capacity, std::move(policy), clock) {}
// std::lock_guard is an RAII lock: making it locks mutex_ (waiting if
// another thread holds it), and it unlocks when `lock` is destroyed at
// the closing brace, even if cache_.get throws. The return value is
// built before that, so the whole Cache call runs under the lock.
[[nodiscard]] std::optional<V> get(const K& key) {
const std::lock_guard lock(mutex_);
return cache_.get(key);
}
std::optional<K> put(const K& key, V value, std::optional<Ttl> ttl = std::nullopt) {
const std::lock_guard lock(mutex_);
return cache_.put(key, std::move(value), ttl);
}
bool erase(const K& key) {
const std::lock_guard lock(mutex_);
return cache_.erase(key);
}
// Even these short reads take the lock: another thread may be in the
// middle of a put, and reading the map then would be a data race.
[[nodiscard]] std::size_t size() const {
const std::lock_guard lock(mutex_);
return cache_.size();
}
[[nodiscard]] CacheStats stats() const {
const std::lock_guard lock(mutex_);
return cache_.stats();
}
[[nodiscard]] bool invariants_hold() const {
const std::lock_guard lock(mutex_);
return cache_.invariants_hold();
}
// Returns the cached value, or loads it with load(key), caches it, and
// returns it. If load throws, nothing is cached and the exception
// reaches the caller.
//
// load runs without the lock, so a slow load does not hold up other
// keys. The price: two threads that miss the same key at the same time
// both load it, and the second put overwrites the first.
//
// Load is any callable (a lambda, a function, ...). The requires line
// is a constraint: calling load with a key must give something that
// converts to V, or the call does not compile.
template <typename Load>
requires std::convertible_to<std::invoke_result_t<Load&, const K&>, V>
V get_or_load(const K& key, Load load, std::optional<Ttl> ttl = std::nullopt) {
// Lock 1, in its own { } block, so it ends at the block's closing
// brace. A hit returns from inside it (std::move takes the value
// out of the optional instead of copying it), and the lock is
// released on the way out.
{
const std::lock_guard lock(mutex_);
if (std::optional<V> hit = cache_.get(key)) return std::move(*hit);
}
// No lock held: other threads use the cache while load runs. If
// load throws, nothing has been cached.
V value = std::invoke(load, key);
// Lock 2, held to the end of the function. Another thread may have
// stored this key meanwhile; then this put is an overwrite. put
// takes a copy of value, so value can still be returned.
const std::lock_guard lock(mutex_);
cache_.put(key, value, ttl);
return value;
}
private:
// mutable: the const members (size, stats, invariants_hold) must lock
// too, and locking changes the mutex.
mutable std::mutex mutex_;
Cache<K, V> cache_;
};
How this code works: get_or_load, lock by lock

Every other member holds the lock for one Cache call. get_or_load takes it twice, and lets it go in between.

  1. Look, under the lock. The first lock_guard lives in its own pair of braces. On a hit, the function returns from inside them, and the lock is released as lock is destroyed. On a miss, the closing brace releases it.
  2. Load, with no lock. std::invoke(load, key) calls the load function. Other threads may use the cache meanwhile, for any key. If the load throws, the exception leaves the function here and nothing is stored.
  3. Store, under the lock again. The second lock_guard is held to the end of the function. put stores a copy of the value; the original is returned to the caller.

Two threads missing the same key, as in the test ac_8_3. This is one possible order:

Time Thread A Thread B The cache
1 locks, misses home, unlocks waits for the lock, or is not yet running misses: 1
2 loading locks, misses home, unlocks misses: 2
3 locks, puts home, unlocks loading home stored
4 returns locks, puts home (an overwrite), unlocks home stored again

Both threads did the work of loading. The answer is still right: both return the loaded value, and the cache holds one entry for home. The two puts can happen in either order; the test’s gate only makes sure that both threads have missed and started loading before either load ends.

SynchronizedCache owns a Cache and a mutex, and every member locks the mutex for the whole call. The single-threaded cache stays as it was, and as simple as it was; the wrapper adds the lock in one place. See Thread safety.

get_or_load is where the lock is easiest to get wrong. The natural version holds the lock from the miss to the put:

The step 2 version, shown above, locks to look, unlocks to load, and locks again to store. The price is stated in its comment and tested: two threads that miss the same key at the same time both load it (AC-8.3), and the second put overwrites the first. For pages, that is wasted work, not a wrong answer. Under LFU, the key starts with two uses instead of one, because the second put is an overwrite. Loading each key only once is the exercise at the end of this page.

load is a template parameter, constrained so that its result converts to V. It is called with no lock held, so it may itself use the cache, for another key, without a deadlock. If it throws, nothing is cached and the exception reaches the caller (AC-8.4).

The step 1 tests run again, unchanged except that every cache now gets still_clock, a ManualClock that is never advanced. Then:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_step2.cpp
// Each test makes its own ManualClock, declared before the cache so that
// it outlives it, and moves time with advance. make_cache(capacity,
// policy, clock) builds the cache; without a clock it uses still_clock, a
// ManualClock that is never moved. CacheStats{hits, misses, evictions,
// expirations}.
//
// The deadline is at 100 ms. At 99 ms the entry is returned; at exactly
// 100 ms it is gone, and that get counts a miss and an expiration and
// removes the entry.
LLD_TEST(ac_7_1_an_entry_expires_when_its_ttl_has_passed) {
ManualClock clock;
Pages pages = make_cache(2, PolicyKind::lru, clock);
pages.put("session", "token", 100ms);
clock.advance(99ms);
LLD_CHECK(pages.get("session") == std::optional<std::string>("token"));
clock.advance(1ms); // exactly 100 ms: expired
LLD_CHECK(!pages.get("session").has_value());
LLD_CHECK(pages.stats() == (CacheStats{1, 1, 0, 1}));
LLD_CHECK_EQ(pages.size(), std::size_t{0}); // the get removed it
LLD_CHECK(pages.invariants_hold());
}
// No ttl: still there a year later. 24h * 365 is a duration of hours;
// advance takes milliseconds, and the conversion is exact.
LLD_TEST(ac_7_2_without_a_ttl_an_entry_never_expires) {
ManualClock clock;
Pages pages = make_cache(2, PolicyKind::lru, clock);
pages.put("home", "v");
clock.advance(24h * 365);
LLD_CHECK(pages.get("home") == std::optional<std::string>("v"));
}
// The first deadline is 100 ms. An overwrite at 60 ms with a ttl of
// 100 ms moves it to 160 ms, so at 120 ms the entry is alive (the old
// deadline would have expired it). An overwrite without a ttl then removes
// the deadline altogether.
LLD_TEST(ac_7_3_an_overwrite_replaces_the_ttl) {
ManualClock clock;
Pages pages = make_cache(2, PolicyKind::lru, clock);
pages.put("session", "t1", 100ms);
clock.advance(60ms);
pages.put("session", "t2", 100ms); // now expires at 160 ms
clock.advance(60ms);
LLD_CHECK(pages.get("session") == std::optional<std::string>("t2"));
pages.put("session", "t3"); // no ttl: no longer expires
clock.advance(1h);
LLD_CHECK(pages.get("session") == std::optional<std::string>("t3"));
LLD_CHECK(pages.invariants_hold());
}
// FR-8. The cache is full with session (expires at 10 ms) and home, and
// the get makes home the LRU victim. At 10 ms, put cart removes the
// expired session first, has room, and evicts nothing: home survives.
LLD_TEST(ac_7_4_expired_entries_go_before_a_live_one_is_evicted) {
ManualClock clock;
Pages pages = make_cache(2, PolicyKind::lru, clock);
pages.put("session", "t", 10ms);
pages.put("home", "v");
static_cast<void>(pages.get("session")); // home is now the LRU victim
clock.advance(10ms);
LLD_CHECK(!pages.put("cart", "v").has_value()); // nothing live evicted
LLD_CHECK(pages.contains("home"));
LLD_CHECK(pages.stats() == (CacheStats{1, 0, 0, 1}));
}
// At 20 ms, a (deadline 10 ms) and b (deadline 20 ms) have expired.
// contains says no for both, but it cannot remove them (it is const), so
// size still counts 3 until remove_expired takes the two out.
LLD_TEST(ac_7_5_an_expired_entry_is_not_contained_until_removed) {
ManualClock clock;
Pages pages = make_cache(3, PolicyKind::lfu, clock);
pages.put("a", "v", 10ms);
pages.put("b", "v", 20ms);
pages.put("c", "v");
clock.advance(20ms);
LLD_CHECK(!pages.contains("a"));
LLD_CHECK(!pages.contains("b"));
LLD_CHECK_EQ(pages.size(), std::size_t{3}); // still held, not yet removed
LLD_CHECK_EQ(pages.remove_expired(), std::size_t{2});
LLD_CHECK_EQ(pages.size(), std::size_t{1});
LLD_CHECK(pages.stats() == (CacheStats{0, 0, 0, 2}));
LLD_CHECK(pages.invariants_hold());
}
// A ttl of 0 or less throws before anything changes: home keeps v1 (its
// 5 ms ttl never runs out, because still_clock never moves), and cart is
// not added.
LLD_TEST(ac_7_6_a_ttl_must_be_positive) {
Pages pages = make_cache(2, PolicyKind::lru);
pages.put("home", "v1", 5ms);
LLD_CHECK_THROWS(pages.put("home", "v2", 0ms), std::invalid_argument);
LLD_CHECK_THROWS(pages.put("cart", "v", -1ms), std::invalid_argument);
LLD_CHECK(pages.get("home") == std::optional<std::string>("v1"));
LLD_CHECK(!pages.contains("cart"));
}
// Two puts fail inside the policy (FlakyPolicy, as in step 1). The first,
// a new key with a ttl, must take its new deadline away again; the second,
// an overwrite without a ttl, must keep home's old deadline. Then
// invariants_hold checks that deadlines_ and the entries agree, and at
// 50 ms home has expired on its original deadline.
LLD_TEST(ac_7_7_a_failed_put_leaves_no_deadline_behind) {
auto owner = std::make_unique<FlakyPolicy>();
FlakyPolicy& policy = *owner;
ManualClock clock;
Pages pages(2, std::move(owner), clock);
pages.put("home", "v1", 50ms);
policy.fail_insert = true;
LLD_CHECK_THROWS(pages.put("cart", "v", 10ms), std::bad_alloc);
policy.fail_insert = false;
policy.fail_access = true;
LLD_CHECK_THROWS(pages.put("home", "v2"), std::bad_alloc); // would have removed the ttl
policy.fail_access = false;
LLD_CHECK(pages.invariants_hold());
clock.advance(50ms);
LLD_CHECK(!pages.contains("home")); // the old ttl still holds
LLD_CHECK(pages.stats() == (CacheStats{0, 0, 0, 0}));
}

No test sleeps. ManualClock::advance moves time, and ac_7_1 checks both sides of the deadline: alive at 99 ms, gone at exactly 100.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_step2.cpp
// The step 1 model test, with time: a put may carry a ttl of 1 to 30 ms,
// and one operation in ten moves both clocks forward 1 to 5 ms.
// The operation is chosen from random() % 20: 0-8 get, 9-12 put without a
// ttl, 13-16 put with a ttl, 17 erase, 18-19 move time. After every
// operation, contains is compared too, since it now depends on time.
LLD_TEST(inv_every_policy_matches_the_model_with_expiry) {
for (const PolicyKind kind : {PolicyKind::lru, PolicyKind::lfu, PolicyKind::fifo}) {
int breaks = 0;
// The cache reads this clock; the model keeps its own time in
// milliseconds, and the two are always moved together.
ManualClock clock;
Cache<int, int> cache(5, std::make_unique<CheckedPolicy<int>>(make_policy<int>(kind), breaks), clock);
Model model(5, kind);
std::mt19937 random(2027);
int disagreements = 0;
for (int step = 0; step < 20'000; ++step) {
const int key = static_cast<int>(random() % 12);
const unsigned op = random() % 20;
if (op < 9) {
if (cache.get(key) != model.get(key)) ++disagreements;
} else if (op < 13) {
if (cache.put(key, step) != model.put(key, step)) ++disagreements;
} else if (op < 17) {
const long ttl = 1 + static_cast<long>(random() % 30);
if (cache.put(key, step, std::chrono::milliseconds(ttl)) != model.put(key, step, ttl)) {
++disagreements;
}
} else if (op < 18) {
if (cache.erase(key) != model.erase(key)) ++disagreements;
} else {
const long ms = 1 + static_cast<long>(random() % 5);
clock.advance(std::chrono::milliseconds(ms));
model.advance(ms);
}
if (cache.contains(key) != model.contains(key)) ++disagreements;
if (cache.size() != model.size() || !cache.invariants_hold()) ++disagreements;
}
LLD_CHECK_EQ(disagreements, 0);
LLD_CHECK_EQ(breaks, 0);
LLD_CHECK(cache.stats().evictions > 2000); // both ways of leaving happened
LLD_CHECK(cache.stats().expirations > 300);
}
}

The model gained a clock of its own and deadlines, and removes expired entries the slow way, by checking every entry. The test checks that both ways of leaving happened often (more than 2,000 evictions and more than 300 expirations per policy), so a change that broke either one could not hide behind the other.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_step2.cpp
// Eight threads, one cache, 5,000 random calls each. The schedule is not
// repeatable, so the checks are the ones that hold for every schedule.
// Each get and each get_or_load does exactly one lookup in the cache, a
// hit or a miss, so hits + misses must equal the number of those calls.
// A lost update to the counts, or a broken list, would show.
LLD_TEST(ac_8_1_many_threads_share_one_cache) {
for (const PolicyKind kind : {PolicyKind::lru, PolicyKind::lfu, PolicyKind::fifo}) {
SynchronizedCache<int, int> cache(8, make_policy<int>(kind), still_clock);
// std::atomic: many threads add to it at once, and ++ on an atomic
// is one indivisible step, so no addition is lost.
std::atomic<std::size_t> lookups{0};
{
std::vector<std::jthread> threads;
for (unsigned seed = 0; seed < 8; ++seed) {
// The thread uses the cache and the counter by reference
// (both outlive it), and gets its own copy of seed, so
// each thread makes a different random sequence.
threads.emplace_back([&cache, &lookups, seed] {
std::mt19937 random(seed);
for (int i = 0; i < 5'000; ++i) {
const int key = static_cast<int>(random() % 20);
switch (random() % 4) {
case 0:
static_cast<void>(cache.get(key));
++lookups;
break;
case 1: cache.put(key, i); break;
case 2:
static_cast<void>(cache.get_or_load(key, [](int k) { return k * 10; }));
++lookups;
break;
default: cache.erase(key); break;
}
}
});
}
} // the jthreads join here
const CacheStats stats = cache.stats();
LLD_CHECK_EQ(stats.hits + stats.misses, lookups.load());
LLD_CHECK(cache.size() <= 8);
LLD_CHECK(cache.invariants_hold());
}
}
// Gate (defined above, not shown): enter_and_wait() records one arrival
// and blocks until open() is called; wait_until_entered(n) blocks until n
// threads have arrived. It uses a mutex and a condition variable, so no
// test needs to sleep and hope.
//
// One thread's load is held inside the gate. While it is held, the main
// thread does a put and a get of another key. If get_or_load kept the
// lock during the load, that put would wait for ever and the test would
// hang; it finishes, so the load does not hold the lock.
LLD_TEST(ac_8_2_a_slow_load_does_not_hold_up_other_keys) {
SynchronizedCache<std::string, std::string> cache(4, make_policy<std::string>(PolicyKind::lru),
still_clock);
Gate gate;
std::jthread loader([&] {
static_cast<void>(cache.get_or_load("report", [&](const std::string&) {
gate.enter_and_wait();
return std::string("slow");
}));
});
gate.wait_until_entered(1); // the load is running now
cache.put("home", "v"); // would wait for ever if the load held the lock
LLD_CHECK(cache.get("home") == std::optional<std::string>("v"));
gate.open();
loader.join(); // wait for the load to finish and store its value
LLD_CHECK(cache.get("report") == std::optional<std::string>("slow"));
}
// The price of loading outside the lock, checked. Both threads miss home
// and enter the load; the gate holds both until both are in, so neither
// has stored a value when the other looked. Two loads, two misses, and
// one entry in the end (the second put overwrote the first).
LLD_TEST(ac_8_3_two_misses_for_one_key_both_load) {
SynchronizedCache<std::string, std::string> cache(4, make_policy<std::string>(PolicyKind::lru),
still_clock);
Gate gate;
std::atomic<int> loads{0};
const auto load = [&](const std::string&) {
++loads;
gate.enter_and_wait();
return std::string("v");
};
{
std::jthread first([&] { static_cast<void>(cache.get_or_load("home", load)); });
std::jthread second([&] { static_cast<void>(cache.get_or_load("home", load)); });
gate.wait_until_entered(2); // both missed and both are loading
gate.open();
} // first and second join here
LLD_CHECK_EQ(loads.load(), 2);
LLD_CHECK_EQ(cache.stats().misses, std::size_t{2});
LLD_CHECK(cache.get("home") == std::optional<std::string>("v"));
LLD_CHECK_EQ(cache.size(), std::size_t{1});
}
// A load that throws: the exception reaches the caller and nothing is
// stored. The next call misses again and loads.
LLD_TEST(ac_8_4_a_failed_load_caches_nothing) {
SynchronizedCache<std::string, std::string> cache(4, make_policy<std::string>(PolicyKind::lru),
still_clock);
// `-> std::string` states the return type. The body only throws, so
// without it the lambda would return void, and get_or_load's
// constraint (the result must convert to `V`) would reject it.
const auto fail = [](const std::string&) -> std::string { throw std::runtime_error("no such page"); };
LLD_CHECK_THROWS(cache.get_or_load("home", fail), std::runtime_error);
LLD_CHECK_EQ(cache.size(), std::size_t{0});
LLD_CHECK(cache.get_or_load("home", [](const std::string&) { return std::string("v"); }) == "v");
LLD_CHECK(cache.stats() == (CacheStats{0, 2, 0, 0})); // each call missed once
}
// The ttl given to get_or_load reaches the put: 10 ms later the loaded
// value has expired. Misses: the first get_or_load, and the expired get.
LLD_TEST(ac_8_5_a_loaded_value_keeps_its_ttl) {
ManualClock clock; // one thread here, so a clock that is moved by hand is safe
SynchronizedCache<std::string, std::string> cache(4, make_policy<std::string>(PolicyKind::lru),
clock);
const auto load = [](const std::string&) { return std::string("token"); };
LLD_CHECK(cache.get_or_load("session", load, 10ms) == "token");
clock.advance(10ms);
LLD_CHECK(!cache.get("session").has_value());
LLD_CHECK(cache.stats() == (CacheStats{0, 2, 0, 1}));
}

The thread tests avoid sleeping too. ac_8_2 uses a Gate: the load enters it and waits, the test waits until it has entered, and only then stores and reads another key, so “the load is running now” is a fact, not a hope. ac_8_3 waits until both loads have entered before opening the gate, which proves both threads missed. ac_8_1 is a stress test: eight threads doing 5,000 random operations each, under all three policies, then a check of the invariants and of the total lookups. It finds real bugs only with ThreadSanitizer watching; the tests carry the concurrency label, so the tsan preset runs them, and they were run ten times in a row with no report. ThreadSanitizer reports races in the runs it watches; a clean run is evidence, not a proof.

ManualClock is not safe to advance while other threads read it, and the thread tests do not try. still_clock is never advanced, so many threads may read it, and ac_8_5, which does advance its clock, uses one thread.

AC for the change.

  • AC-7.1 An entry expires when its time to live has passed: alive just before its deadline, gone at it, and the get that finds it expired removes it.
  • AC-7.2 An entry without a time to live never expires.
  • AC-7.3 An overwrite replaces the time to live, or removes it.
  • AC-7.4 Expired entries are removed before a live one is evicted.
  • AC-7.5 An expired entry is not contains, still counts in size until removed, and remove_expired removes it.
  • AC-7.6 A time to live of zero or less is an exception, and changes nothing.
  • AC-7.7 A failed put leaves no deadline behind, and does not remove the old one.
  • AC-8.1 Many threads can share one cache under every policy, and the invariants hold afterwards.
  • AC-8.2 A slow load does not hold up other keys.
  • AC-8.3 Two misses for one key at the same time both load.
  • AC-8.4 A failed load caches nothing, and the exception reaches the caller.
  • AC-8.5 A loaded value keeps the time to live it was given.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

main.cpp
// A cache of 2 under LRU, with a session that expires and a setting that
// does not. 30min and 29min are std::chrono durations, written with the
// literals from `using namespace std::chrono_literals`. The clock is
// declared before the cache, so it is destroyed after it: the clock
// outlives the cache, as the cache requires.
void sessions_demo() {
ManualClock clock;
Cache<std::string, std::string> sessions(2, make_policy<std::string>(PolicyKind::lru), clock);
sessions.put("s-101", "token-a", 30min); // deadline: 30 min after the start
sessions.put("config", "dark-mode"); // no ttl: never expires
clock.advance(29min);
print("s-101 after 29 min", sessions.get("s-101")); // also makes config the LRU victim
clock.advance(1min); // now exactly 30 min: s-101's deadline has come
// The cache is full (2 of 2). put first removes the expired s-101,
// which leaves room, so the LRU victim, config, is not touched.
const auto evicted = sessions.put("s-102", "token-b", 30min);
std::cout << "put s-102 after 30 min: evicted " << (evicted ? *evicted : "nothing") << '\n';
print("s-101", sessions.get("s-101")); // a miss: already removed by that put
print("config", sessions.get("config")); // a hit: it never expires
const CacheStats stats = sessions.stats();
std::cout << "hits " << stats.hits << ", misses " << stats.misses << ", evictions "
<< stats.evictions << ", expirations " << stats.expirations << '\n';
}

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

main.cpp
// Four threads share one cache of 64 pages. Each thread asks for pages 0 to
// 49, twice over, with get_or_load, so 4 x 2 x 50 = 400 lookups in all.
// Which thread loads which page depends on timing, so only facts that do
// not are printed: every lookup is a hit or a miss, the 50 pages fit in
// 64 so all of them are held, and the invariants hold.
void shared_demo() {
const SteadyClock clock; // the real clock: now() is safe from any thread
SynchronizedCache<int, std::string> pages(64, make_policy<int>(PolicyKind::lfu), clock);
{
// A std::jthread starts running its function at once, and joins
// (waits for it to finish) when it is destroyed. The vector, and
// so every thread, is destroyed at the closing brace of this
// block, so all four have finished before the stats are read.
std::vector<std::jthread> threads;
for (int t = 0; t < 4; ++t) {
// [&pages]: each thread uses the one shared cache by reference.
// The cache outlives the threads, which end inside this block.
threads.emplace_back([&pages] {
for (int round = 0; round < 2; ++round) {
for (int id = 0; id < 50; ++id) {
// The inner lambda is the load: it builds the page
// for a key that missed.
static_cast<void>(
pages.get_or_load(id, [](int key) { return "page " + std::to_string(key); }));
}
}
});
}
}
const CacheStats stats = pages.stats();
std::cout << "4 threads, 400 lookups: hits + misses = " << stats.hits + stats.misses << ", "
<< pages.size() << " pages held, invariants "
<< (pages.invariants_hold() ? "hold" : "BROKEN") << '\n';
}
Expected output
s-101 after 29 min: token-a
put s-102 after 30 min: evicted nothing
s-101: (miss)
config: dark-mode
hits 2, misses 1, evictions 0, expirations 1
4 threads, 400 lookups: hits + misses = 400, 50 pages held, invariants hold

The session demo shows FR-8 at work. At 29 minutes, reading s-101 makes config the least recently used entry. At 30 minutes the cache is full and put s-102 needs room. Without FR-8, LRU would evict config, a live entry that never expires. Instead, put first removes s-101, whose time is up, and then has room: it evicts nothing. The expired session is counted as an expiration, not an eviction.

The thread demo prints only what does not depend on timing. Every one of the 400 get_or_load calls is exactly one hit or one miss, and 50 keys fit in 64 entries; how many of the 400 were misses depends on how the threads ran, so the demo does not print it.

A plan for 45 minutes, using the time boxes from The design workflow:

Time What to do What to say
About 5 min Ask what is cached, how full is measured, which rules, chosen when, how fast, one thread or many, and what a failure may do. Write FR-1 … FR-6. “Do you want one rule, or to compare several? Chosen at start-up or at compile time?”
3–5 min Sketch Cache, EvictionPolicy with its three events and one question, and the three policies. Say why the policy never sees values. “The cache tells the policy what happened and asks one question: who goes next.”
10–15 min Write LRU: the list, the map of iterators, splice. Then get and put, choosing the victim first. State INV-1 and INV-2. “A list node never moves, so the map’s iterators stay valid; splice moves a node in O(1).”
10 min LFU with buckets, or the exception-safety order of put, whichever the interviewer prefers. Show the trace. “A count only goes up by one, so a key only ever moves to the next bucket.”
About 5 min Take a change: time to live, or sharing between threads. “A hit changes the policy’s order, so get needs the exclusive lock.”

What is usually expected at each level

Level Usually expected
Junior A working LRU with a list and a map, in O(1); get that counts as a use; eviction when full; a few tests that show which key is evicted.
Mid-level All of the above, plus: the policy behind an interface, chosen at run time; LFU or FIFO as a second policy; the victim chosen before the insert; contains that is not a use; counts; edge cases (capacity 1 and 0).
Senior All of the above, plus: LFU in O(1) with buckets; the strong exception guarantee and its order of steps; a model test; the run-time versus template trade-off; time to live; why a shared lock is wrong for get; loading outside the lock and its cost.

These are this site’s judgement of common practice, as on How to approach a case study, not any company’s rubric.

  • Capacity is in entries, not bytes. A cache of large and small values cannot promise a memory limit.
  • One lock for everything. Every thread waits on one mutex. A busy service would split the cache into shards, each with its own lock and a share of the capacity, at the cost of an eviction order that is per shard, not global.
  • Duplicate loads. Two threads that miss the same key both load it. The exercise below removes that.
  • No sweep in the shared cache. SynchronizedCache does not offer remove_expired, so expired entries are removed only by a put or by a get of that key. Many expired entries can sit in memory, each counted in size, until the next put.
  • LFU forgets nothing. Counts never age, and new keys are easy to evict. See LFU’s memory.
  • Each key is stored three times under LRU and FIFO, and each hit costs two hash lookups instead of the one a dedicated LRU needs. For long string keys, the copies are real memory.
  • LFU’s empty buckets are not tested. The rule that keeps them from piling up is held only by the code and its comment; see Tests.
  • No statistics over time. The counts are totals since the cache was made. Comparing policies in production also needs hit rates per minute, which belong in the service’s metrics; see Observability.
Requirement Design element Code Tests Status
FR-1 store and read Cache::get, Cache::put step 1 cache.hpp ac_1_1_…, ac_1_2_…, ac_1_3_…, ac_5_2_get_returns_a_copy_that_outlives_the_entry Tested
FR-2 bounded Cache::put, victim first step 1 cache.hpp ac_2_1_…, ac_3_4_the_key_being_added_is_never_its_own_victim, ac_4_1_…, model test Tested
FR-3 policies LruPolicy, LfuPolicy, FifoPolicy step 1 *_policy.hpp ac_2_1_… to ac_3_5_…, inv_every_policy_matches_the_model Tested
FR-4 chosen at run time EvictionPolicy, make_policy, policy_kind step 1 make_policy.hpp ac_3_6_a_policy_is_chosen_by_name, ac_4_2_a_cache_needs_room_and_a_policy Tested
FR-5 erase and look Cache::erase, Cache::contains step 1 cache.hpp ac_1_4_…, ac_2_3_contains_does_not_count_as_a_use Tested
FR-6 counts CacheStats step 1 cache.hpp ac_5_1_stats_count_hits_misses_and_evictions, and the counts in most tests Tested
NFR-1 O(1) list plus map; LFU buckets step 1 *_policy.hpp none: argued from the structures on this page, not measured Argued
NFR-2 policies separate EvictionPolicy<K> never sees V step 1 eviction_policy.hpp the same policies serve Cache<std::string, std::string>, <int, int>, and <std::string, Fragile> Compiled
NFR-3 exception safety the order of steps in get and put; policy rollbacks step 1 cache.hpp, *_policy.hpp ac_6_1_…, ac_6_2_…, ac_6_3_a_failed_copy_is_not_a_use Tested
FR-7 time to live deadlines in a multimap, expired step 2 cache.hpp ac_7_1_… to ac_7_7_…, inv_every_policy_matches_the_model_with_expiry Tested
FR-8 expired before live remove_expired first in put step 2 cache.hpp ac_7_4_expired_entries_go_before_a_live_one_is_evicted, step 2 demo Tested
FR-9 shared SynchronizedCache, one mutex step 2 synchronized_cache.hpp ac_8_1_many_threads_share_one_cache; tsan preset Tested
FR-10 loading get_or_load, load outside the lock step 2 synchronized_cache.hpp ac_8_2_… to ac_8_5_a_loaded_value_keeps_its_ttl Tested
NFR-5 testable time Clock, ManualClock step 2 clock.hpp every step 2 time test; none sleeps Tested

Exercise: Load each key only once

Two threads that miss the same key both build the page (AC-8.3). Change get_or_load so that while one thread is loading a key, other threads that ask for the same key wait for that load and get its result, without holding the cache’s lock while they wait. Other keys must still not wait (AC-8.2).

  1. What must the cache remember while a load is running, and what type lets several threads wait for one result?
  2. Write the new get_or_load.
  3. What should the waiting threads get if the load throws, and what should the next call for that key do?
  4. How would you test “loaded once” without sleeping? The test for AC-8.3 waits for both loads to enter a gate, which will now never happen.
  5. What new way to deadlock does this add?
Show the explained answer
  1. The keys being loaded, each with a shared result. A map from key to std::shared_future<V>, guarded by the same mutex as the cache. The thread that loads holds the matching std::promise<V>. A std::future can be waited on by one thread only; a std::shared_future can be copied, and every copy waits for the same result.

  2. One way:

    IllustrativeA fragment for explanation; not compiled on its own.

    V get_or_load(const K& key, Load load, std::optional<Ttl> ttl = std::nullopt) {
    if (ttl && *ttl <= Ttl::zero()) throw std::invalid_argument("a ttl must be positive");
    std::optional<std::promise<V>> mine; // made only if this thread loads
    std::shared_future<V> theirs; // used only if another thread loads
    {
    const std::lock_guard lock(mutex_);
    if (std::optional<V> hit = cache_.get(key)) return std::move(*hit);
    if (const auto found = loading_.find(key); found != loading_.end()) {
    theirs = found->second; // another thread is loading it
    } else {
    mine.emplace();
    // share() turns the promise's one-reader future into a
    // shared_future that any number of waiters can copy.
    loading_.emplace(key, mine->get_future().share()); // may throw: nothing has changed
    }
    }
    if (!mine) return theirs.get(); // waits; rethrows the loader's exception
    std::optional<V> value;
    try {
    value.emplace(std::invoke(load, key));
    } catch (...) {
    {
    const std::lock_guard lock(mutex_);
    loading_.erase(key); // still ours: no one adds a key that is there
    }
    // std::current_exception() is the exception being handled
    // here; every waiter's get() will throw it too.
    mine->set_exception(std::current_exception());
    throw;
    }
    {
    const std::lock_guard lock(mutex_);
    loading_.erase(key); // in one lock with the put, so a later caller
    cache_.put(key, *value, ttl); // finds the load or the value, never neither
    }
    mine->set_value(*value); // wakes the waiters, outside the lock
    return std::move(*value);
    }
    // a new member, guarded by mutex_:
    std::unordered_map<K, std::shared_future<V>> loading_; // keys being loaded now

    The waiting thread copies the shared_future under the lock and waits for it after unlocking, so it holds up no one. The loader removes its key from loading_ and stores the value under one lock, so a thread that arrives later finds either the entry being loaded or the cached value, never neither. set_value happens after that, with no lock held, and wakes the waiters.

    Three details are easy to get wrong. The promise is made only on the loading path, so a hit costs no allocation. Only the load is inside the try: a put that failed there would be followed by a second erase in the catch, after the lock had been let go, which could remove another thread’s newer entry. And the time to live is checked first, so the put cannot throw for a bad one. It can still throw std::bad_alloc, and copying V in set_value may throw. In either case the promise is destroyed unfulfilled, and each waiter gets a std::future_error (a broken promise): a failure, though in the second case the value was cached. With V a std::shared_ptr<const Page>, the copy cannot throw.

  3. The same exception, and a fresh load. set_exception makes every waiter’s get() throw the loader’s exception, so each caller learns that its page could not be built. The key is removed from loading_ and nothing is cached, so the next call loads again rather than inheriting a failure. Caching failures for a short while (“negative caching”) is a separate decision with its own risks.

  4. Wait for the second miss, not for a second load. The first thread enters the gate as before. Then start the second thread and wait until stats().misses is 2. The second thread’s miss and its finding the running load happen under one lock, so once the count is 2, it is committed to waiting. Then open the gate, join both, and check that the load ran once and that both threads got the value:

    IllustrativeA fragment for explanation; not compiled on its own.

    std::jthread first([&] { static_cast<void>(cache.get_or_load("home", load)); });
    gate.wait_until_entered(1); // the first thread is loading
    std::jthread second([&] { second_got = cache.get_or_load("home", load); });
    // Spin, giving up the processor each time round, until the second
    // thread has missed: from then on it is bound to wait for the first load.
    while (cache.stats().misses < 2) std::this_thread::yield();
    gate.open();

    A second test does the same with a load that throws, and checks that both threads get the exception, nothing is cached, and the next call loads.

  5. A load that depends on its own key. If load("home") calls get_or_load("home", …) on the same thread, it finds its own load running and waits for a result only it can produce, for ever. The same happens through other keys: if loading A asks for B and loading B asks for A, the two loads wait for each other, on one thread or two. The step 2 version would have recursed without end instead; now the program silently stops. Say it in the comment: load must not depend, directly or through other keys, on the key it is loading. A load that asks for unrelated keys is fine, since no lock is held while it runs.

This answer was checked: with these changes, a version of AC-8.3 that expects one load, and the failing-load test, passed along with the other step 2 tests under GCC, AddressSanitizer, and ThreadSanitizer (ten runs), and the one-load test fails against the step 2 code, which loads twice.

  • Keep what is stored and what goes apart: the cache owns the values and tells a policy about each event; the policy owns an order and names a victim.
  • LRU and FIFO in O(1) are a list in the order that matters and a map from key to list node; splice moves a node without copying it, and list nodes never move, so the map’s iterators stay valid.
  • LFU in O(1) uses buckets of equal counts in increasing order, because a count only ever grows by one.
  • Choose the victim before adding the key, or LFU can evict the key you are adding.
  • The strong guarantee comes from ordering the steps: do everything that can fail before anything that cannot be undone, and undo your own change when a later step throws.
  • A model that is slow and obviously right can check tens of thousands of victims that no one could work out by hand.
  • Mutation shows what tests miss, and also what cannot be seen from outside; say which is which.
  • With threads, get is a write when a hit changes the order, and a slow load must happen outside the lock, at the price of duplicate loads, unless you make other callers wait for the first.