Cache policies and invalidation
What you will learn on this page
Section titled “What you will learn on this page”- Why a cache is a copy that can be wrong, and why the first design question is how wrong it may be, and for how long.
- Where a cache sits: cache-aside or read-through, and what happens on a write: write-through, invalidate on write, or write-behind.
- How a time to live bounds the age of what the cache serves, and why the clock should be injected.
- What a full cache throws away: oldest write, LRU, LFU, and when each one fits.
- The ways a cache learns that its copy is old (invalidation), and the stale-data risks that remain, including a race that keeps an old value cached after a write.
The problem: fast, and possibly wrong
Section titled “The problem: fast, and possibly wrong”An online shop shows product pages. Each page needs the product’s name and price from the catalogue database, and suppose a read takes about 20 milliseconds. A category page lists 40 products, so reading them one after another takes 800 milliseconds before anything else happens. Yet most reads are for the same few hundred products, and a price changes a few times a day at most.
Keeping recently read products in memory makes the repeat reads almost free. That is a cache. The catch is that a cache holds a copy, and a copy does not change when the original does. Every cache will, at some moment, answer with data that is no longer true. The design is about making that deliberate and bounded:
- What is kept, and how much of it (memory is not free).
- How long a copy may be served before it must be checked again.
- How the cache hears about changes, if it hears at all.
- What a wrong answer costs in each place that reads it.
The last question matters most, and it is a question about requirements, not about code. A price on a product page that is 30 seconds old is usually harmless. A price at checkout that is 30 seconds old means charging the customer a different amount than the shop intends.
Requirements
Section titled “Requirements”The shop’s team agreed on these:
- R1. A product page may show a price up to 30 seconds old.
- R2. Checkout must charge the current price. It never reads from the cache.
- R3. The cache holds at most a fixed number of products, set by configuration.
- R4. A change saved through the catalogue service is seen at once by that service’s next read.
- R5. A nightly import also writes prices straight into the database, without going through the catalogue service.
- R6. Tests must check expiry exactly and must not sleep.
R1 and R5 together decide a great deal. Because some writes bypass the service (R5), the cache cannot hear about every change, so something else must bound the age of a copy: the 30 seconds of R1.
Step 1: where the cache sits, and what a write does
Section titled “Step 1: where the cache sits, and what a write does”There are two common places for the code that fills a cache.
Cache-aside. The caller looks in the cache, and on a miss loads from the source itself and stores the result:
// Cache-aside: the caller itself manages the cache. `cache` and// `database` stand for objects the caller can reach.std::optional<Product> product_for_page(const std::string& sku) { // `cached` is declared in the condition; the condition is true when // the optional the cache returned holds a product. if (auto cached = cache.get(sku)) { return cached; // a hit: the database is not asked } // A miss: go to the source of truth. std::optional<Product> loaded = database.find(sku); if (loaded) { // *loaded is the Product inside the optional; keep a copy of it // so the next caller gets a hit. cache.put(sku, *loaded); } return loaded; // may be empty: no such product}This code is illustrative and was not compiled. It is simple and flexible, but every caller must repeat it, and every caller must get the write side right too.
Read-through. The cache, or an object around it, loads on a miss. Callers ask one object and do not know whether the answer came from memory. In C++ the natural shape is a caching proxy: a class with the same interface as the source, holding the cache and a pointer to the real source. The rules live in one place.
A write must also do something to the cached copy:
| On a write | What happens | Risk | Fits when |
|---|---|---|---|
| Write-through | Write to the source, then put the new value in the cache | Caches values that may never be read; if the cache update fails after the source write, the copy is stale; two writers can update the cache in the opposite order to the source, leaving the older value cached | The written value is likely to be read soon |
| Invalidate on write | Write to the source, then remove the cached copy; the next read loads the new value | One extra load after each write | Most cases: simple, and the cache never holds a value it did not read |
| Write-behind | Write to the cache only; a background task writes to the source later, often batched | Writes accepted but not yet stored are lost if the program stops; other readers of the source see old data | Losing recent writes is acceptable, and the source is the bottleneck |
The catalogue uses read-through with invalidate on write. Write-behind is ruled out: the source would lag behind the cache, and checkout (R2), which reads the source, would charge old prices. It would also lose saved price changes if the service stopped.
Step 2: how long a copy may live
Section titled “Step 2: how long a copy may live”Every entry gets a time to live (TTL): an age after which the cache will not serve it. When the cache cannot hear about every change (R5), the TTL is the only thing that bounds how old an answer can be, so it comes straight from the requirement: 30 seconds (R1).
Two details decide whether the TTL is reliable:
- Measure age with a steady clock.
std::chrono::system_clockis the wall clock, and it can jump when the computer’s time is corrected. A jump back would make entries live too long; a jump forward would expire everything at once.std::chrono::steady_clocknever goes back, and an age is a difference, which is all a TTL needs. - Inject the clock. If the cache calls
steady_clock::now()itself, a test of a 30-second TTL must wait 30 seconds, and a test of “29.999 seconds is still fresh” cannot be written at all (R6). A smallClockinterface lets production pass the steady clock and tests pass a clock they move by hand. This is the same seam as the injected sleeper on Idempotency and retries.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// 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.// Clock is an interface: it has no data, and its one job, now(), is// written by each kind of clock. The cache is handed a `const Clock&`,// keeps a pointer to it, and never knows which kind it was given.class Clock {public: // A short name for "a moment in time", the steady clock's own type. // Both clocks below return this type, so they can stand in for each // other, and the cache can add a time to live to a moment and compare // moments, whichever clock it was given. using time_point = std::chrono::steady_clock::time_point;
// Virtual, so that deleting a clock through a Clock pointer runs the // right destructor. virtual ~Clock() = default; // `= 0` makes this pure virtual: Clock has no answer of its own, and // every class derived from it must supply one. `const`: reading the // time does not change the clock. [[nodiscard]] virtual time_point now() const = 0;
protected: // Protected, so only a derived clock can create or copy the Clock // part. Outside code cannot copy a whole clock through a `Clock&`, // which would slice off the derived part (see the idiom reference). 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 for tests and the demo: time stands still until someone calls// advance, so "29.999 s later" means exactly that. `final`: nothing can// derive from it.class ManualClock final : public Clock {public: // Answers with the stored moment; only advance changes it. [[nodiscard]] time_point now() const override { return now_; }
// Moves time forward by `step`, for example clock.advance(30s). // Throws std::invalid_argument for a negative step, and then leaves // the time unchanged. void advance(std::chrono::milliseconds step) { // count() is the raw number of milliseconds inside the duration. if (step.count() < 0) { throw std::invalid_argument("a steady clock never goes back"); } now_ += step; // a moment plus a length of time is a later moment }
private: // `{}` starts it at the clock's zero point (its epoch). The real date // does not matter: the cache only adds to moments and compares them. time_point now_{}; // the epoch; only differences matter};Clockis an interface: one pure virtual function and a virtual destructor, with copying protected so that aClock&cannot be sliced by accident.ManualClock::advancerefuses a negative step, so a test cannot build a clock that goes back, which a steady clock never does.now()isconst: asking the time does not change the clock.
Step 3: what to throw away when the cache is full
Section titled “Step 3: what to throw away when the cache is full”A bounded cache (R3) must sometimes remove an entry that has not expired. The rule it uses is its eviction policy:
| Policy | Removes | Cost | Fits when | Fails when |
|---|---|---|---|---|
| Oldest write (FIFO) | The entry written longest ago | One list in write order | Every entry has the same TTL, and age matters more than use | A popular entry is removed even while it is being read all the time |
| Least recently used (LRU) | The entry not read for longest | A list reordered on every read, plus a map into it | Recent reads predict the next reads | One pass over many keys (a report that reads every product once) pushes out the hot set |
| Least frequently used (LFU) | The entry read the fewest times | A count per entry, and a way to find the smallest quickly | Popularity is stable over a long time | Old popularity lingers: last month’s best seller keeps its place unless counts age |
| TTL only, no limit | Nothing until it expires | None | The set of keys is small and known | The keys are unbounded, such as one per user or per search |
There is no best policy. The choice depends on how the keys are read, and the honest way to choose between LRU and LFU for a real workload is to record which keys are read and replay that record against each policy, counting hits.
The catalogue uses oldest write, for a reason specific to this cache: every entry has the same TTL, so the entry written longest ago is also the first to expire. One list in write order then serves both jobs. Expired entries are at its front, and so is the entry to evict. With a TTL that differs per entry, that stops being true, and the cache needs a structure ordered by expiry time instead, such as the map of deadlines in the cache eviction case study.
The design: a bounded cache with a time to live
Section titled “The design: a bounded cache with a time to live”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// A bounded cache whose entries expire a fixed time after they were// written. Every entry has the same time to live, so the oldest write is// also the first to expire: one list in write order serves both expiry// and eviction.//// K must be copyable and hashable, with a hash and an equality that do// not throw. V must be copyable, and its move assignment must not throw.// get returns a copy, never a reference: the entry can expire or be// evicted by the next call, and a reference to it would dangle.//// Thread safety: not safe. Lifetime: the clock must outlive the cache.//// `template <typename K, typename V>`: `K` is the key type and `V` the value// type. The class is written once, and the compiler makes a separate// version for each pair it is used with, such as// TtlCache<std::string, Product> in the caching proxy below.template <typename K, typename V>class TtlCache {public: // Throws std::invalid_argument for a capacity of 0 or a time to live // that is not positive. // capacity: the most entries kept at once. ttl: how long each entry // may be served after it is written. clock: where "now" comes from. // The cache keeps the clock's address (&clock), not a copy of it. // If the check throws, no cache is created, so a bad configuration // can never be used. TtlCache(std::size_t capacity, std::chrono::milliseconds ttl, const Clock& clock) : clock_(&clock), ttl_(ttl), capacity_(capacity) { if (capacity_ == 0 || ttl_.count() <= 0) { throw std::invalid_argument("a cache needs room and a positive time to live"); } }
// Each entry holds an iterator into this cache's own list, so a // member-wise copy would point into the other cache's list. // `= delete` makes any attempt to copy a cache a compile error. TtlCache(const TtlCache&) = delete; TtlCache& operator=(const TtlCache&) = delete;
// The value, if present and younger than the time to live. An // expired entry is removed and counted as a miss. [[nodiscard]] std::optional<V> get(const K& key);
// Stores a copy of value, replacing any old one and restarting its // time to live. When that makes the cache too full, removes the // oldest write. Strong guarantee: if a copy throws, nothing changed. void put(const K& key, const V& value);
// Removes the entry, if there is one; true if something was removed. bool invalidate(const K& key);
// Includes expired entries that no call has removed yet. [[nodiscard]] std::size_t size() const noexcept { return entries_.size(); } [[nodiscard]] CacheStats stats() const noexcept { return stats_; }
private: // The write order: a linked list of keys, oldest write at the front. using Order = std::list<K>; // What the map stores for each key. struct Entry { V value; // the cache's own copy of the value Clock::time_point expires; // the moment it stops being served // An iterator is a position in a container, here a pointer-like // handle to one node of the list, so the key can be moved or // removed in O(1) without searching the list. `typename` tells the // compiler that Order::iterator, which depends on `K`, is a type. typename Order::iterator place; // this key's node in by_age_ }; // Key to entry, found in O(1) on average by hashing the key. using Entries = std::unordered_map<K, Entry>;
// Erases one entry from both containers; `found` must point at a real // entry. noexcept: erasing never throws (the hash and equality of `K` // must not throw), which put and get rely on. void remove(typename Entries::iterator found) noexcept;
const Clock* clock_; // not owned: the cache only reads the time from it std::chrono::milliseconds ttl_; std::size_t capacity_; Entries entries_; Order by_age_; // keys, oldest write first CacheStats stats_;};Classifying what is here:
TtlCacheowns copies. Its values live in the map, and the cache decides when they die. That is whygetreturnsstd::optional<V>by value, notconst V&orconst V*: an entry can be evicted or expire on the very next call, and a reference into it would then dangle. For values that are expensive to copy, storestd::shared_ptr<const V>: the copy returned is then a cheap pointer copy, and the value lives as long as anyone still holds it.getis notconst. Reading can remove an expired entry and always updates the hit and miss counts. Pretending otherwise withmutablewould hide real changes to the cache’s state.- The two containers hold one invariant:
by_age_holds exactly the keys ofentries_, each once, and each entry’splacepoints at its own node. Every function that changes one container changes the other before it returns. That is why astd::listis used for the order: its iterators stay valid when other nodes are added, removed, or moved, soplacestays correct. It is also whyTtlCachecannot be copied: a member-wise copy would copy eachplace, still pointing into the other cache’s list, so the copy operations are deleted. - The clock is a pointer, not owned. The cache uses a clock that someone else creates and keeps alive, as the header says.
- The requirements on
KandVare written down, because the exception guarantees below depend on them.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Looks a key up. Three outcomes: no entry (a miss), an entry that is too// old (removed, and a miss), or a fresh entry (a copy of its value, and a// hit). Strong guarantee: if copying the value throws, the cache and its// counts are as they were.template <typename K, typename V>std::optional<V> TtlCache<K, V>::get(const K& key) { // find returns an iterator to the key's map element, or end() if the // key is not there. found->first is the key, found->second the Entry. const auto found = entries_.find(key); if (found == entries_.end()) { ++stats_.misses; return std::nullopt; } // `>=`: an entry written at 0 s with a 30 s time to live expires at // exactly 30 s, and is still served at 29.999 s. if (clock_->now() >= found->second.expires) { // After this, `found` points at an erased element; it is not used // again. remove(found); // too old to serve, and no use to keep ++stats_.misses; ++stats_.expired; return std::nullopt; } // Copy the value out first; if that copy throws, the hit below is // never counted and nothing in the cache has changed. std::optional<V> copy = found->second.value; ++stats_.hits; return copy; // the caller gets its own copy, which cannot dangle}- An entry is expired when its age has reached the TTL: written at 0 seconds with a 30-second TTL, it is served at 29.999 seconds and not at 30. The test below checks both sides of that edge.
- An expired entry is removed when found, so that it does not take
a place. Entries that are never read again are removed later, by
eviction from the front of the list.
size()can therefore count expired entries, as its comment says. - The hit is counted after the copy is made. If copying throws, no hit is recorded for an answer that was never given.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Stores a copy of `value` under `key`, fresh for one time to live from// now. Two paths: an existing key is updated in place and becomes the// newest write; a new key is added to the list and the map, and then, if// the cache is over capacity, the oldest write is evicted. Strong// guarantee: every step that can throw runs before anything is changed,// or is undone if it fails, and every step after it cannot throw.template <typename K, typename V>void TtlCache<K, V>::put(const K& key, const V& value) { // The new deadline: now plus the time to live, for example 0 s + 30 s. const Clock::time_point expires = clock_->now() + ttl_; // An if with an initializer: `found` exists only inside this if. if (const auto found = entries_.find(key); found != entries_.end()) { // An existing key. Make the risky copy into a local first; then // std::move hands its contents over instead of copying again. V copy = value; // may throw; nothing changed yet found->second.value = std::move(copy); // cannot throw, by the rule above found->second.expires = expires; // splice relinks the key's existing node at the end of the same // list: no copy, no allocation, no exception. The node itself does // not move in memory, so the iterator in `place` stays valid. by_age_.splice(by_age_.end(), by_age_, found->second.place); // now the newest // The number of entries did not change, so there is nothing to // evict. return; } // A new key. First, put a copy of it at the back of the list. If this // throws, push_back itself leaves the list as it was. by_age_.push_back(key); // may throw; nothing changed yet try { // std::prev(by_age_.end()) is the position of the last node: the // one just pushed. Entry{...} copies the value (it may throw), and // try_emplace adds a map element holding a copy of the key and // that Entry (it may throw too, for example if memory runs out). entries_.try_emplace(key, Entry{value, expires, std::prev(by_age_.end())}); } catch (...) { // catch (...) catches any exception. Take the key back off the // list, so the list and the map hold the same keys again; then // `throw;` sends the same exception on to the caller. by_age_.pop_back(); // undo, so a failed put changes nothing throw; } // At most one entry too many. The front of the list is the oldest // write, and with a capacity of at least 1 it is never the key just // added. find and remove do not throw (`K`'s hash and equality must // not throw), so the guarantee still holds. if (entries_.size() > capacity_) { remove(entries_.find(by_age_.front())); // the oldest write ++stats_.evictions; }}- Replacing a value restarts its TTL and moves its key to the back
of the list with
splice, which moves the node without copying the key and cannot throw. - Strong guarantee. For an existing key, the new value is copied
first, into a local; only then is anything changed, and the move into
place cannot throw because
V’s move assignment must not throw. For a new key, the key is added to the list first; if adding the entry to the map then throws, the key is taken back off the list. Either way, a failedputleaves the cache as it was. Exception safety covers this “do the risky part first” shape. - Eviction happens after the insert, so the cache briefly holds one more entry than its capacity. Evicting first would be simpler to read, but if the insert then failed, an entry would have been lost for nothing.
How this code works: TtlCache::put
put first works out the new deadline, now + ttl, and then takes one
of two paths.
- The key is already there. Copy the new value into a local
V. This is the only step that can throw, and nothing has changed yet. Then move the copy into the entry, set the new deadline, andsplicethe key’s list node to the back, so it counts as the newest write. None of these three steps can throw. The number of entries is the same, soputreturns without evicting. - The key is new. Push a copy of the key onto the back of
by_age_. If that throws, the list is unchanged. Then build theEntry(a copy of the value, the deadline, and the position of the node just pushed) and add it to the map. If anything in that step throws, thecatchblock pops the key back off the list and rethrows, so the list and the map again hold the same keys. - Too full? Only a new key can make the map one entry larger than
the capacity. Then the key at the front of the list, the oldest
write, is found in the map and removed from both containers. Finding
and removing cannot throw, so a
putthat got this far succeeds.
A worked example. The test rewriting_a_key_makes_it_the_newest
uses a capacity of 2:
| Call | Path | by_age_ after (oldest first) |
entries_ after |
Evicted |
|---|---|---|---|---|
put("a", 1) |
new key | a |
a = 1 |
none |
put("b", 2) |
new key | a, b |
a = 1, b = 2 |
none |
put("a", 10) |
existing key: copy, move, splice | b, a |
a = 10, b = 2 |
none |
put("c", 3) |
new key: 3 entries, more than 2 | a, c |
a = 10, c = 3 |
b |
In the last row, the list is briefly b, a, c and the map holds three
entries; eviction removes b, the front. Because splice moved a
behind b, the rewrite saved a.
Which guarantee, and why. put gives the strong guarantee: if
it throws, the cache is exactly as it was. Path 1 does its only risky
step before changing anything. Path 2 changes the list, then undoes that
change if the map step fails. Step 3 cannot fail. This rests on the
rules in the class comment: moving a V into place, and hashing or
comparing a K, must not throw.
The caching proxy
Section titled “The caching proxy”The catalogue reads products through an interface, so that the cache can stand in front of the database without callers changing:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Where products come from. In the shop this is the database: the// source of truth, and slow to read. An interface, like Clock: the// virtual functions ending in `= 0` have no body here, and each kind of// source (the in-memory store, the caching proxy, the test fakes)// supplies its own. Callers hold a ProductSource& and cannot tell which// kind they have.class ProductSource {public: virtual ~ProductSource() = default;
// nullopt if there is no product with this sku. Not const: a source // may change itself while reading, as the store counts its reads and // the proxy fills its cache. [[nodiscard]] virtual std::optional<Product> find(const std::string& sku) = 0; // Creates the product, or replaces the one with the same sku. virtual void save(const Product& product) = 0;
protected: // Protected so a ProductSource& cannot be copied by accident, which // would slice off the derived part; derived classes can still copy. ProductSource() = default; ProductSource(const ProductSource&) = default; ProductSource& operator=(const ProductSource&) = default;};VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// A caching proxy: the same interface as the source, in front of it.// Reads are read-through: a miss loads from the source and keeps the// product for the time to live, so a product may be up to that old.// Writes go to the source first, then remove the cached copy, so the// next read loads the new product. A change made to the source// directly, not through this object, is seen once the copy expires.// "Not found" is not cached: every read of a missing sku reaches the// source.// Thread safety: not safe. Lifetime: the source and the clock must// outlive this object.class CachedProducts final : public ProductSource {public: // Throws std::invalid_argument for a capacity of 0 or a time to live // that is not positive (the TtlCache inside makes that check). // `source` is the real source to read through; it is kept by address. CachedProducts(ProductSource& source, std::size_t capacity, std::chrono::milliseconds ttl, const cache::Clock& clock);
// The same two functions as every ProductSource; `override` makes the // compiler check that they really replace the interface's versions. [[nodiscard]] std::optional<Product> find(const std::string& sku) override; void save(const Product& product) override;
[[nodiscard]] cache::CacheStats stats() const noexcept { return cache_.stats(); }
private: ProductSource* source_; // not owned: the real source, read on a miss // Owned by value: sku to a copy of the product, with a time to live. cache::TtlCache<std::string, Product> cache_; std::uint64_t saves_ = 0; // counts saves, to notice one made during a load};CachedProducts is a caching proxy, in the sense of
Proxy: it has the source’s interface, holds a
pointer to the real source, and decides when to call it. It is not a
Decorator, even though the two look alike in code: it does not add
behaviour to each call, it avoids calls. Decorator vs
Proxy draws that line.
Its comment states the stale-data contract: what a reader may see, and for how long. That contract is the most important line in the class. A cache whose staleness is not written down will be used, sooner or later, by code that assumes it is never stale.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Read-through: answer from the cache if it can, otherwise load from the// source, keep a found product for later, and return what was loaded.// Returns nullopt if the source has no such product. If the source// throws, the exception passes to the caller and nothing is put in the// cache (the get before it may already have removed an expired copy).std::optional<Product> CachedProducts::find(const std::string& sku) { // `cached` is declared inside the condition and holds the cache's // answer; the condition is true when that optional holds a product. if (std::optional<Product> cached = cache_.get(sku)) { return cached; // a hit: the source is not asked } // Remember how many saves there had been before the slow load starts. const std::uint64_t saves_before = saves_; std::optional<Product> loaded = source_->find(sku); // the slow part // A save that ran while we were loading may have replaced the product // after we read it. Keeping what we read would serve the old product // for a whole time to live, so keep it only if no save happened. // (This object is single threaded, so here that can only happen if // the source calls back into it; the race test does exactly that.) // `loaded &&`: a missing product is never cached. *loaded is the // Product inside the optional; put stores its own copy of it. if (loaded && saves_ == saves_before) { cache_.put(sku, *loaded); } return loaded;}- A hit never reaches the source. A miss loads and keeps the result for the TTL.
- “Not found” is not cached. Caching it, called negative caching, would protect the database from repeated reads of a sku that does not exist, but a product added a moment later would stay invisible for a whole TTL. The catalogue reads missing products rarely, so it does not need the protection.
- The
saves_check handles a save that happens while a load is under way. It is explained in Stale-data risks below.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Write-then-invalidate. The source gets the new product first; then the// save is counted, for find's check above, and the cached copy is// dropped, so the next find loads the new product. invalidate's true or// false result is not needed here.void CachedProducts::save(const Product& product) { source_->save(product); // if this throws, nothing changed and the cached copy is still right ++saves_; cache_.invalidate(product.sku); // after the write, never before it}- The source is written first. If that throws, nothing has changed: the database still has the old product, and the cached copy, which matches it, is still right.
- The copy is removed after the write, never before. Removing it first leaves a window in which a reader misses, loads the old product from the database, and caches it again, just before the write lands.
Text description of the diagram
At 0 seconds the caller asks CachedProducts for the mug. The cache
has nothing, so the proxy reads the store, gets the mug at 12.00, puts
it in the cache, fresh until 30 seconds, and returns it. At 10 seconds
the caller asks again; the cache has it, so the store is not read. Then
the caller saves the mug at 10.00. The proxy writes the store first and
then invalidates the cached mug. The next find misses, reads 10.00 from
the store, caches it, and returns it.
Diagram source (Mermaid)
sequenceDiagram
participant U as Caller
participant P as CachedProducts
participant C as TtlCache, ttl 30 s
participant S as Store
U->>P: find(mug) at 0 s
P->>C: get(mug)
C-->>P: nothing
P->>S: find(mug)
S-->>P: Blue mug 12.00
P->>C: put(mug), fresh until 30 s
P-->>U: Blue mug 12.00
U->>P: find(mug) at 10 s
P->>C: get(mug)
C-->>P: Blue mug 12.00, a hit
P-->>U: Blue mug 12.00
U->>P: save(mug at 10.00)
P->>S: save(mug at 10.00)
P->>C: invalidate(mug)
U->>P: find(mug)
P->>C: get(mug)
C-->>P: nothing
P->>S: find(mug)
S-->>P: Blue mug 10.00
P->>C: put(mug)
P-->>U: Blue mug 10.00Invalidation: how a cache learns that its copy is old
Section titled “Invalidation: how a cache learns that its copy is old”Invalidation is whatever makes a cache stop serving a copy that no longer matches the source. The catalogue uses two kinds at once, and there are others:
| Strategy | How the cache learns | Stale for at most | Weak spot |
|---|---|---|---|
| Time to live | It does not; it stops trusting old copies | The TTL | Serves old data for up to the TTL; a short TTL means more loads |
| Invalidate on write | The code that writes also removes the copy | Nothing, for writes that go through this code | Writes that bypass it (R5) are missed; with several servers, each has its own cache to invalidate |
| Change notifications | The source, or a message queue, announces each change, and the cache removes keys | The delivery delay | A lost or delayed message leaves a copy stale indefinitely, so keep a TTL as well |
| Versioned keys | The key includes a version or a hash of the content, so a change means a new key | Nothing: an old key is never asked for again | The reader must know the current version; old entries stay until evicted |
| Do not cache | It never has a copy | Nothing | Every read pays the full cost |
The catalogue combines invalidate on write (R4: its own saves are seen at once) with a TTL (R5: the nightly import’s changes are seen within 30 seconds). Checkout uses the last row: it reads the source (R2). Choosing “do not cache” for one reader and “cache for 30 seconds” for another is normal; staleness is a property of a use, not of the data.
Stale-data risks
Section titled “Stale-data risks”Even with a TTL and invalidation, there are ways for a cache to serve data that is older than its contract allows, or to fail in other ways.
The write that lands during a load
Section titled “The write that lands during a load”This is the subtle one. Suppose CachedProducts were shared by two
threads. A thread that misses must call the slow source, and it must not
hold the cache’s lock while doing so: that would block every other
reader for the whole load, and a source that calls back into the cache
would deadlock, as Deadlocks explains. So there
is a gap between the miss and the put, and a write can land in it:
Text description of the diagram
The reader thread misses in the cache and starts loading the mug from the store, which still has 12.00. While the reader is between the load and the put, the writer thread saves the mug at 10.00 and invalidates the cache, which has nothing to remove yet. Then the reader puts 12.00 in the cache. Until the entry expires, every reader is served 12.00, although the store has 10.00 and the save went through the cache as it should.
Diagram source (Mermaid)
sequenceDiagram
participant R as Reader thread
participant C as Cache
participant S as Store
participant W as Writer thread
R->>C: get(mug)
C-->>R: nothing
R->>S: find(mug)
S-->>R: Blue mug 12.00, the old price
W->>S: save(mug at 10.00)
W->>C: invalidate(mug), nothing to remove
R->>C: put(mug at 12.00)
Note over C: 12.00 is served until it expires, though the store has 10.00Invalidation ran, in the right order, and the cache is still stale for a
whole TTL. The fix is for the load to notice that a save happened while
it was running, and then not keep what it read. CachedProducts counts
saves in saves_: find notes the count before loading and puts the
result only if the count has not changed. In a thread-safe version,
find would read the count and check it again under the cache’s lock,
with the put under the same lock, and save would increment the count
and invalidate under that lock, after writing the source. A load that
started before the save either puts its product before the save’s
invalidate, which then removes it, or after, when it sees a changed
count and keeps nothing. A load that started after the save reads the
new product. That last step assumes a read that starts after a write has
finished sees it; a source that reads from a lagging replica breaks
this, and then only the TTL bounds the staleness.
The check is coarse: a save of any product stops the load of every product that overlaps it. A count per key would be finer, at the cost of memory for every key ever saved. For a catalogue where saves are rare, an occasional extra load is a fair trade.
CachedProducts itself is single threaded, so in this example the
race can only happen if the source calls back into the cache in the
middle of a load. The race test below does exactly that, to stand in
for the second thread. The check has the same job in both cases.
Other risks
Section titled “Other risks”- Readers that need the truth. A cache that is fine for display can be wrong for a decision. Checkout reads the source (R2); so should anything that commits money, stock, or permissions.
- Many copies. If the catalogue runs on four servers, each has its own cache. A save through server 1 invalidates server 1’s copy only; the others serve the old price until their TTL ends. The TTL is then the real bound for everyone, and the “seen at once” of R4 holds only for the server that saved.
- A stampede. When a popular entry expires, every reader that arrives before the reload finishes misses and goes to the database at once. A cache in front of a busy database can make that spike worse than having no cache. Common fixes: let one reader load while the others wait for its result, or refresh popular entries a little before they expire.
- A count is not a memory bound. A capacity of 1,000 products is a bound on memory only if a product has a bounded size. If values vary a lot in size, bound their total size as well, as with bounded queues on Backpressure.
Running it
Section titled “Running it”The demo uses a store with three products, a cache with room for two,
and a 30-second TTL. It moves a ManualClock by hand and prints how
many times the store has been read after each step.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
#include "cached_products.hpp"#include "clock.hpp"#include "products.hpp"
#include <chrono>#include <iomanip>#include <iostream>#include <optional>#include <sstream>#include <string>
// Lets the code write durations as 10s, 30s, or 29'999ms.using namespace std::chrono_literals;
// namespace { ... } with no name keeps these helpers private to this file.namespace {
// Prices are whole cents, to avoid rounding errors; this turns 250 into// "2.50". cents / 100 is the whole units (integer division drops the// rest) and cents % 100 the cents left over. setw(2) with setfill('0')// prints that remainder as two digits, so 5 cents shows as "05".std::string price(long long cents) { std::ostringstream text; // builds a string with the same << as std::cout text << cents / 100 << '.' << std::setw(2) << std::setfill('0') << cents % 100; return text.str();}
// Prints one line of the demo: a label, the product or "not found", and// how many times the store has been read so far, which shows whether// the answer came from the cache.void show(const std::string& what, const std::optional<shop::Product>& product, const shop::InMemoryStore& store) { std::cout << what << ": "; if (product) { std::cout << product->name << ' ' << price(product->price_cents); } else { std::cout << "not found"; } std::cout << " (store reads: " << store.reads() << ")\n";}
} // namespace
int main() { // Declared first, so they outlive the proxy that points at them. cache::ManualClock clock; shop::InMemoryStore store; // {sku, name, price in cents}: 12'00 is 1200 cents, that is 12.00. The // ' is only a digit separator, placed here to look like a price. store.save({"mug", "Blue mug", 12'00}); store.save({"pen", "Black pen", 2'50}); store.save({"cap", "Red cap", 15'00});
// Room for two products, each kept for 30 seconds. Every find below // goes through `products`, except the checkout line, which reads the // store directly. shop::CachedProducts products(store, 2, 30s, clock);
// 1. Read-through: a miss loads from the store; a hit does not. show("mug, first read", products.find("mug"), store); clock.advance(10s); show("mug, 10 s later", products.find("mug"), store);
// 2. Expiry: 30 s after it was loaded, the copy is too old. clock.advance(20s); show("mug, 30 s after loading", products.find("mug"), store);
// 3. A save through the cache is seen at once. products.save({"mug", "Blue mug", 10'00}); show("mug, after a save through the cache", products.find("mug"), store);
// 4. A change made in the store directly is not seen until expiry. store.save({"mug", "Blue mug", 9'00}); show("mug, after a direct change", products.find("mug"), store); show("checkout reads the store", store.find("mug"), store); clock.advance(30s); show("mug, 30 s later", products.find("mug"), store);
// 5. Capacity: a third product pushes out the oldest write. show("pen", products.find("pen"), store); show("cap", products.find("cap"), store); show("mug, after pen and cap", products.find("mug"), store);
// 6. "Not found" is not cached. show("hat", products.find("hat"), store); show("hat again", products.find("hat"), store);
const cache::CacheStats stats = products.stats(); std::cout << "hits " << stats.hits << ", misses " << stats.misses << " (expired " << stats.expired << "), evictions " << stats.evictions << '\n';}mug, first read: Blue mug 12.00 (store reads: 1)mug, 10 s later: Blue mug 12.00 (store reads: 1)mug, 30 s after loading: Blue mug 12.00 (store reads: 2)mug, after a save through the cache: Blue mug 10.00 (store reads: 3)mug, after a direct change: Blue mug 10.00 (store reads: 3)checkout reads the store: Blue mug 9.00 (store reads: 4)mug, 30 s later: Blue mug 9.00 (store reads: 5)pen: Black pen 2.50 (store reads: 6)cap: Red cap 15.00 (store reads: 7)mug, after pen and cap: Blue mug 9.00 (store reads: 8)hat: not found (store reads: 9)hat again: not found (store reads: 10)hits 2, misses 9 (expired 2), evictions 2- Read-through: the first read loads (1 store read); the read 10 seconds later is a hit (still 1).
- Expiry: at exactly 30 seconds after loading, the copy is too old, and the mug is loaded again (2).
- A save through the cache is seen at once (R4): the cached copy was removed, so the next read loads 10.00 (3).
- A direct change to the store, as the nightly import makes (R5), is not seen: the page still shows 10.00, while checkout, which reads the store, sees 9.00. Thirty seconds later the copy expires and the page shows 9.00 too. That is R1 in action: stale, but for no more than 30 seconds.
- Capacity: reading the pen and then the cap makes three products in a cache with room for two, so the oldest write, the mug, is evicted. Reading the mug again loads it and evicts the pen in turn. The two evictions in the last line are these.
- Not found is not cached: both reads of the hat reach the store.
Testing
Section titled “Testing”Every test uses a ManualClock, so no test sleeps and every edge is
checked to the millisecond (R6).
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// 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.// LLD_CHECK_THROWS(expression, type) fails unless the expression throws// that type of exception. They come from the site's small test header,// lld_test.hpp. Every test makes its own ManualClock, so time only moves// when the test says so.
// Sets up: one entry written at 0 s, with a 30 s time to live. Proves// both sides of the edge: served at 29.999 s, gone at exactly 30 s, and// removed (not just hidden) once found expired.LLD_TEST(an_entry_is_served_until_its_time_to_live_ends) { ManualClock clock; TtlCache<std::string, int> cache(4, 30s, clock); cache.put("a", 1); clock.advance(29'999ms); // 29,999 milliseconds; ' separates digits // get returns std::optional<int>; comparing it with 1 is true only if // it holds a value and that value is 1. LLD_CHECK(cache.get("a") == 1); clock.advance(1ms); // exactly 30 s old: expired LLD_CHECK(cache.get("a") == std::nullopt); // std::size_t{0} gives the 0 the same type as size(), so both sides // of the == are the same unsigned type. LLD_CHECK_EQ(cache.size(), std::size_t{0}); // the expired entry was removed LLD_CHECK_EQ(cache.stats().expired, std::size_t{1});}
// Proves that put on an existing key resets its deadline: written at 0 s// and again at 20 s, the entry is still fresh at 40 s (until 50 s).LLD_TEST(a_new_write_restarts_the_time_to_live) { ManualClock clock; TtlCache<std::string, int> cache(4, 30s, clock); cache.put("a", 1); clock.advance(20s); cache.put("a", 2); clock.advance(20s); // 40 s after the first write, 20 s after the second LLD_CHECK(cache.get("a") == 2);}- The TTL edge: fresh at 29.999 seconds, expired at exactly 30, and removed when found.
- A rewrite restarts the TTL: 40 seconds after the first write but 20 after the second, the entry is fresh.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Room for two; a third write evicts the oldest, "a", and only "a".LLD_TEST(a_full_cache_removes_the_oldest_write) { ManualClock clock; TtlCache<std::string, int> cache(2, 30s, clock); cache.put("a", 1); cache.put("b", 2); cache.put("c", 3); LLD_CHECK(cache.get("a") == std::nullopt); LLD_CHECK(cache.get("b") == 2); LLD_CHECK(cache.get("c") == 3); LLD_CHECK_EQ(cache.stats().evictions, std::size_t{1});}
// Writing "a" again moves it to the back of the write order (b, then a),// so writing "c" evicts "b", not "a".LLD_TEST(rewriting_a_key_makes_it_the_newest) { ManualClock clock; TtlCache<std::string, int> cache(2, 30s, clock); cache.put("a", 1); cache.put("b", 2); cache.put("a", 10); cache.put("c", 3); LLD_CHECK(cache.get("a") == 10); LLD_CHECK(cache.get("b") == std::nullopt);}
// The policy is "oldest write", not "least recently used": reading an// entry does not keep it.LLD_TEST(reading_an_entry_does_not_keep_it) { ManualClock clock; TtlCache<std::string, int> cache(2, 30s, clock); cache.put("a", 1); cache.put("b", 2); LLD_CHECK(cache.get("a") == 1); cache.put("c", 3); LLD_CHECK(cache.get("a") == std::nullopt);}
// The constructor refuses a capacity of 0 and a time to live of 0 s. The// extra brackets around each expression are needed because the macro// would otherwise split its argument at the comma inside// <std::string, int>.LLD_TEST(a_cache_needs_room_and_a_positive_time_to_live) { ManualClock clock; LLD_CHECK_THROWS((TtlCache<std::string, int>(0, 30s, clock)), std::invalid_argument); LLD_CHECK_THROWS((TtlCache<std::string, int>(2, 0s, clock)), std::invalid_argument);}- The oldest write goes first, and a rewrite makes a key the newest.
- Reading does not keep an entry. This test documents the policy: under LRU it would fail, because reading “a” would have made “b” the one to evict. A test that pins down a deliberate choice stops someone from “fixing” it by accident.
- A cache with no room, or with a TTL that is not positive, is refused, so a bad configuration fails at startup.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// A value whose copy throws while *fail is true.// `fail` points at a bool owned by the test, so the test can switch// failures on and off after values are already in the cache. Its moves// are noexcept and never fail, which TtlCache requires of a value's move// assignment. Only its copy constructor can throw.struct Fragile { int number = 0; const bool* fail = nullptr;
Fragile(int n, const bool* f) : number(n), fail(f) {} Fragile(const Fragile& other) : number(other.number), fail(other.fail) { if (*fail) { throw std::runtime_error("copy failed"); } } Fragile(Fragile&&) noexcept = default; Fragile& operator=(const Fragile& other) = default; Fragile& operator=(Fragile&&) noexcept = default;};
// Sets up: a cache of two holding "a" = 1. Then, with copies failing, it// tries a new key and an existing key; both throw. Proves that both// failed puts changed nothing, including the hidden write order.LLD_TEST(a_put_that_throws_changes_nothing) { ManualClock clock; bool fail = false; TtlCache<std::string, Fragile> cache(2, 30s, clock); cache.put("a", Fragile(1, &fail)); // copies work: "a" is stored fail = true; // from now on, every copy throws // A new key: the copy inside Entry{...} throws, so put must undo its // push_back of "b" onto the write order. LLD_CHECK_THROWS(cache.put("b", Fragile(2, &fail)), std::runtime_error); // An existing key: the copy into the local throws before "a" changes. LLD_CHECK_THROWS(cache.put("a", Fragile(10, &fail)), std::runtime_error); fail = false; // copies work again, so get can copy "a" out LLD_CHECK_EQ(cache.size(), std::size_t{1}); const std::optional<Fragile> kept = cache.get("a"); LLD_CHECK(kept && kept->number == 1); // The failed new key left nothing behind in the write order either: // three more writes evict "a", then "c", and nothing else. cache.put("c", Fragile(3, &fail)); cache.put("d", Fragile(4, &fail)); cache.put("e", Fragile(5, &fail)); // An empty optional converts to false, a full one to true. LLD_CHECK(!cache.get("c")); LLD_CHECK(cache.get("d") && cache.get("e")); LLD_CHECK_EQ(cache.stats().evictions, std::size_t{2});}- A failed
putchanges nothing, for a new key and for an existing one.Fragileis a value type whose copy can be made to throw, the same idea as the fault-injection tests on Exception safety, which make allocations fail instead. The three writes at the end check that the failed new key left nothing in the write order: ifputforgot to undo itspush_back, the list would hold a key with no entry, and the next eviction would remove an entry that is not there. That is undefined behaviour, not a clean failure: with that line removed, the GCC 11 test program crashed both with and without AddressSanitizer.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// These tests use the real proxy over an InMemoryStore, whose reads()// counts how often the store was asked. price(source, sku), a helper// defined earlier in this file, returns the price of the product found, or an empty// optional if there is none.
// Two finds of the same sku within the time to live: one store read.// find is [[nodiscard]], so static_cast<void>(...) says the result is// ignored on purpose.LLD_TEST(a_hit_does_not_reach_the_source) { ManualClock clock; InMemoryStore store; store.save({"mug", "Blue mug", 12'00}); CachedProducts products(store, 4, 30s, clock); static_cast<void>(products.find("mug")); static_cast<void>(products.find("mug")); LLD_CHECK_EQ(store.reads(), 1);}
// The mug is cached at 12.00; a save through the proxy removes that copy,// so the very next read loads 10.00, with no wait for the time to live.LLD_TEST(a_save_through_the_proxy_is_seen_at_once) { ManualClock clock; InMemoryStore store; store.save({"mug", "Blue mug", 12'00}); CachedProducts products(store, 4, 30s, clock); static_cast<void>(products.find("mug")); products.save({"mug", "Blue mug", 10'00}); LLD_CHECK(price(products, "mug") == 10'00);}
// A change written to the store directly bypasses the proxy: the old// 12.00 is served until the copy is 30 s old, and then 9.00 is loaded.LLD_TEST(a_direct_change_to_the_source_is_seen_after_the_time_to_live) { ManualClock clock; InMemoryStore store; store.save({"mug", "Blue mug", 12'00}); CachedProducts products(store, 4, 30s, clock); static_cast<void>(products.find("mug")); store.save({"mug", "Blue mug", 9'00}); LLD_CHECK(price(products, "mug") == 12'00); // stale, as documented clock.advance(30s); LLD_CHECK(price(products, "mug") == 9'00);}
// A miss for a sku the store does not have is not remembered: once the// hat is added, the next read finds it at once.LLD_TEST(not_found_is_not_cached) { ManualClock clock; InMemoryStore store; CachedProducts products(store, 4, 30s, clock); LLD_CHECK(products.find("hat") == std::nullopt); store.save({"hat", "Green hat", 20'00}); LLD_CHECK(price(products, "hat") == 20'00); // found at once}
// BrokenSaves (defined earlier in this file) passes reads to the store but throws on// every save. The failed save must leave the cached 12.00 in place,// because the store still has 12.00: the next read is a hit.LLD_TEST(a_failed_save_keeps_the_cached_copy) { ManualClock clock; InMemoryStore store; store.save({"mug", "Blue mug", 12'00}); BrokenSaves source(store); CachedProducts products(source, 4, 30s, clock); static_cast<void>(products.find("mug")); LLD_CHECK_THROWS(products.save({"mug", "Blue mug", 10'00}), std::runtime_error); LLD_CHECK(price(products, "mug") == 12'00); // still what the store has LLD_CHECK_EQ(store.reads(), 1); // and still cached}- Hits do not reach the source, saves through the proxy are seen at once, direct changes are seen after the TTL and not before, and “not found” is not remembered.
- A failed save keeps the cached copy, which is right, because the database did not change either. The store’s read count shows that the next read was a hit.
- The tests check prices through a small
pricehelper that returns an empty optional for a missing product. An earlier version used checks such asLLD_CHECK_EQ(cache.get("a")->number, 1), which bind a reference to a member of a temporarystd::optionalthat is destroyed at the end of the statement. Both compilers accepted them; AddressSanitizer stopped the test run at the first one withstack-use-after-scope. It is the same mistake as the one described on Backpressure, and dereferencing the optional would also have been undefined if a product were missing.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
LLD_TEST(a_save_during_a_load_keeps_the_old_product_out_of_the_cache) { ManualClock clock; InMemoryStore store; store.save({"mug", "Blue mug", 12'00}); // InterruptedSource (defined earlier in this file) reads the store, then runs // during_next_find once, before it returns what it read. InterruptedSource source(store); CachedProducts products(source, 4, 30s, clock); // The action: a lambda that saves 10.00 through the proxy. [&] lets // it use `products` by reference. It runs in the middle of the first // load, after 12.00 has been read: the race, on one thread. source.during_next_find = [&] { products.save({"mug", "Blue mug", 10'00}); };
// This load read 12.00, then the save replaced it. LLD_CHECK(price(products, "mug") == 12'00); // The old product was not kept, so the next read loads the new one. LLD_CHECK(price(products, "mug") == 10'00);}- The race, made deterministic.
InterruptedSourcereads the old product and then, before returning it, runs a save through the proxy: exactly the interleaving in the race diagram. The load returns what it read, 12.00, but does not keep it, and the next read loads 10.00. - When we removed the
saves_check fromfindand ran the tests, this test failed, and no other did. It is the only test that guards that line.
How this code works: The race test, step by step
The test makes one call to price(products, "mug") that runs a whole
save in the middle of a load, and then reads again.
| Step | What runs | saves_ |
Store has | Cache has |
|---|---|---|---|---|
| 1 | find: cache_.get misses; saves_before is set to 0 |
0 | 12.00 | nothing |
| 2 | InterruptedSource::find reads the store and gets 12.00 |
0 | 12.00 | nothing |
| 3 | The action runs products.save at 10.00: store written, saves_ counted, invalidate finds nothing |
1 | 10.00 | nothing |
| 4 | Back in find: saves_ (1) is not saves_before (0), so no put; 12.00 is returned |
1 | 10.00 | nothing |
| 5 | Second price call: a miss, the store gives 10.00, no save ran, so it is kept |
1 | 10.00 | 10.00 |
Without the check, step 4 would put 12.00 in the cache, and step 5
would be a hit returning 12.00, so the second LLD_CHECK would fail.
The first read returning the old 12.00 is fine: that read started
before the save.
All 13 tests also run under the asan-ubsan and tsan presets. The
example has no threads, so ThreadSanitizer has nothing to find here; the
run shows only that the build works with it.
The design at a glance
Section titled “The design at a glance”class cache::TtlCache<K, V>
not thread safe; owns copies of its values
Data members
const Clock* clock_;not ownedstd::chrono::milliseconds ttl_;std::size_t capacity_;std::unordered_map<K, Entry> entries_;std::list<K> by_age_;keys, oldest write firstCacheStats stats_;
Member functions
TtlCache(std::size_t capacity, std::chrono::milliseconds ttl, const Clock& clock);throws std::invalid_argument for 0 or a ttl that is not positiveTtlCache(const TtlCache&) = delete;entries hold iterators into by_age_std::optional<V> get(const K& key);nodiscard; a copy; removes an expired entryvoid put(const K& key, const V& value);strong guarantee; may evict the oldest writebool invalidate(const K& key);std::size_t size() const noexcept;counts expired entries not yet removedCacheStats stats() const noexcept;
struct cache::TtlCache<K, V>::Entry
private to the cache
Member functions
V value;Clock::time_point expires;std::list<K>::iterator place;this key's node in by_age_
interface (abstract class) cache::Clock
Member functions
virtual time_point now() const = 0;nodiscard
class cache::SteadyClock
production; wraps std::chrono::steady_clock
Member functions
time_point now() const override;std::chrono::steady_clock::now()
class cache::ManualClock
for the tests and the demo
Data members
time_point now_;
Member functions
void advance(std::chrono::milliseconds step);throws std::invalid_argument if negative
interface (abstract class) shop::ProductSource
Member functions
virtual std::optional<Product> find(const std::string& sku) = 0;nodiscardvirtual void save(const Product& product) = 0;
class shop::CachedProducts
a caching proxy; not thread safe
Data members
ProductSource* source_;not ownedcache::TtlCache<std::string, Product> cache_;std::uint64_t saves_;to notice a save during a load
Member functions
CachedProducts(ProductSource& source, std::size_t capacity, std::chrono::milliseconds ttl, const cache::Clock& clock);std::optional<Product> find(const std::string& sku) override;read-throughvoid save(const Product& product) override;the source first, then invalidatecache::CacheStats stats() const noexcept;
struct cache::CacheStats
a value
Member functions
std::size_t hits;std::size_t misses;absent or expiredstd::size_t expired;std::size_t evictions;
When a cache fits, and when it does not
Section titled “When a cache fits, and when it does not”A cache fits when:
- Reads repeat. The same keys are read many times between changes. A cache of keys that are each read once only adds work.
- Reading the source is expensive compared with a memory lookup: a database, a remote service, or a long computation.
- Some staleness is acceptable, and the acceptable amount can be written down for each reader (R1, R2).
Something else fits better when:
- Every read needs the current value. Then a cache can only be wrong. Make the source faster, or read it.
- The source is already fast enough. A cache adds memory, code, tests, and a new kind of bug. Measure before adding one; the cost of a read in your system is a number to look up, not to guess.
- The data never changes and is small. Load it once at startup into a plain container. No TTL, no eviction, no invalidation.
- The expensive part is one slow query, not repeated reads. Fix the query.
Common mistakes
Section titled “Common mistakes”- No stated staleness. A cache without a written “may be up to N seconds old” will be read by code that assumes it is current.
- Returning references into the cache. The next call may evict the
entry. Return a copy, or a
std::shared_ptr<const V>. - Invalidating before the write. A reader can reload the old value in the gap and cache it again.
- Ignoring writes that bypass the cache. Imports, scripts, and other services write too. Without a TTL, their changes are never seen.
- Measuring age with the wall clock. A correction can expire everything
at once, or keep entries far longer than their TTL. Use
std::chrono::steady_clock. - Unbounded caches. A cache keyed by user, search, or URL grows without limit. Bound it, and count evictions so that a too-small bound is visible.
- Caching decisions. Checkout, stock reservation, and permission checks that matter must read the source, or must be designed to tolerate the stated staleness.
- Holding a lock while loading. Every reader waits for one slow load, and a source that calls back deadlocks.
When the requirements change
Section titled “When the requirements change”- “Each product type needs a different TTL.” The write-order list
is no longer expiry order. Keep entries in a structure ordered by
expiry time, such as a
std::multimapfrom time to key, or a heap, and expire from its front; keep the eviction order separately. - “Evict the least recently used product instead.” Move a key to
the back of the list on every hit as well as on every write.
getthen changes the order, and the “reading does not keep an entry” test must be rewritten, on purpose. - “Several threads read the catalogue.” Add one mutex for the cache
and the
saves_count, release it while loading, and check the count under it before the put, as described above. Thread safety covers writing that contract. - “When the database is down, show the last known price.” Keep
expired entries for a while longer, and let
findreturn one, marked as old, when the source throws. The stale-data contract then has two numbers: normally 30 seconds, and during an outage longer, with a limit. - “The catalogue now runs on four servers.” Either accept a TTL of staleness everywhere except the server that saved, or publish each save as a change notification that every server applies, and keep the TTL as the bound for lost notifications.
Exercise
Section titled “Exercise”Exercise: Choose invalidation for a scenario
For each scenario, choose how the cached data is kept current: a TTL (say roughly how long), invalidate on write, change notifications, versioned keys, do not cache, or a combination. Say why, and what a stale answer would cost.
- Product descriptions and photos, shown on product pages and edited a few times a month in the catalogue’s own admin screens.
- Currency exchange rates, which a feed updates every 60 seconds. They are shown next to prices, and checkout converts the amount charged.
- A user’s roles, checked on every request to decide what they may do. An administrator can remove a role from someone at any time.
- Thumbnails made from uploaded images. An upload never changes; a new image is a new upload.
- A stock count shown on product pages as “only 3 left”. Orders change it all day.
Show the explained answer
1. Invalidate on write, with a long TTL as a safety net. Every edit goes through the service that owns the cache, so it can remove the copy at once, and a reader sees the edit on the next read. A TTL of an hour or so catches anything that bypasses the service. A stale answer costs little: an old photo for a short time. What would change it: if several servers each have a cache, the edit must reach all of them, or the TTL must shrink to what the business accepts.
2. A TTL no longer than the feed period for display; no cache for checkout. With a TTL equal to the feed period, a rate shown may lag the feed by up to a minute, so up to two minutes after that rate was published; if that is too much, shorten the TTL or invalidate when the feed delivers a new rate. Checkout must use a rate it can stand behind: read the current rate, or better, record the rate used with the order, so that the amount charged can be explained later. What would change it: if the shop promises “the price you saw is the price you pay”, checkout must use the rate that was shown, so that rate is stored with the customer’s basket, not looked up again.
3. A short TTL plus change notifications, or no cache for sensitive actions. A role removed from someone who is misusing it must stop working quickly, and “quickly” must be written as a requirement, for example “within 10 seconds”. A TTL of a few seconds bounds the delay even if a notification is lost; a notification makes the usual delay much shorter. For the most sensitive actions, such as deleting data or moving money, check the source every time. What would change it: a stated limit of zero; then this data is not cached at all.
4. Versioned keys, and no invalidation at all. If the key is the
image’s upload ID or a hash of its content, a thumbnail for a key can
never become wrong. Eviction alone decides what stays. What would
change it: if the thumbnail size or format changes, add that to the
key (upload-77, 200 px, v2), so the new thumbnails get new keys.
5. A short TTL for display; the source for any reservation. “Only 3 left” that is 10 seconds old is acceptable on a product page. Putting an item in a basket, or checking out, must reserve stock in the source, which refuses when none is left. What would change it: if the shop must never show “in stock” for a sold-out item, the page needs change notifications from the stock system, or no cache.
Summary
Section titled “Summary”- A cache is a copy that can be wrong. Decide, for each reader, how wrong it may be and for how long, and write that stale-data contract in the cache’s header.
- Read-through behind a caching proxy keeps the rules in one place. On a write, invalidate after writing the source; write-through keeps the value warm, and write-behind risks losing writes.
- A time to live is the only bound on staleness for changes the cache does not hear about. Measure it with a steady clock, and inject the clock so that tests do not sleep.
- A full cache needs an eviction policy: oldest write, LRU, or LFU, chosen by how the keys are read.
- Invalidation can come from a TTL, from the writing code, from change notifications, or from versioned keys; real systems combine them.
- A load that overlaps a write can put an old value back after invalidation. Notice the write, and do not keep the result.
- Code that needs the truth, such as checkout, reads the source.