Scrivio Interview library
LeadershipPrincipal7 min read · updated 12 November 2026

The MySQL query cache, Hibernate second-level cache defaults and several in-house caches all caused incidents in your company's history. What principles would you set for caching across the organisation?

I would set a few organisation-wide rules: put caches only where the invalidation rule is known, close to the domain that owns the data, with explicit keys, TTLs and a named owner; avoid global transparent caches such as the old MySQL query cache; standardise on a small set of cache technologies with shared libraries, metrics and stampede protection; and require every cache to document how stale it may be and how staleness is corrected. Caches then become part of capacity planning and incident reviews, and we test what happens when a cache is empty or down.

Why this question is asked

Caches are attractive because they make a slow thing fast with very little code. They are also one of the most common sources of incidents, because a cache is a second copy of the data, and every second copy can be wrong, cold or overloaded. When a company has been hurt several times, a senior engineer is expected to step back from the individual fixes and set principles that stop the same class of failure. Interviewers ask this to see whether we can turn incident history into rules people can follow. In this answer, we will look at what went wrong with the MySQL query cache and generic caches, then go through the principles one by one, with the reasoning behind each, and finish with how we would roll them out.

1A Quick Recap of Why These Caches Failed

The MySQL query cache stored the exact text of a SELECT together with its result. The next identical SELECT returned the stored result without running the query. It sounded free, but it had two deep problems. Any write to a table removed every cached result that touched that table, so on a busy OLTP table the cache was constantly filled and emptied. And the cache was protected by a single global lock, so on servers with many cores, threads queued for that lock even when the cache did not help them. MySQL deprecated it in 5.7.20 and removed it completely in 8.0.

The Hibernate second-level cache, a cache of entities shared across sessions, failed in a different way. Teams switched it on for entities that other systems also updated directly in the database. Hibernate had no way of knowing about those writes, so it served old data until the entry expired, and in some configurations entries never expired at all. The in-house caches usually failed in the third classic way: a popular key expired, hundreds of requests missed at the same moment, and all of them hit the database together. This is called a cache stampede.

Notice the common thread. In each case the cache was added without anyone stating who owns its correctness, how it learns that the data changed, and what happens when it is empty.

2Principle 1: Cache Where the Invalidation Rule Is Known

The hardest part of caching is not storing data but knowing when the stored copy is wrong. The only code that reliably knows when data changes is the code that owns that data. So the first principle is that caches live close to the domain: the pricing service caches prices, because it is the only writer of prices and can evict or update the entry in the same place it writes.

Each cache must also have explicit keys, a TTL (time to live, the maximum age of an entry) and a named owning team. Explicit keys mean we can say exactly what one entry represents, for example price:sku:12345:eur, and evict it on purpose. A TTL is the safety net: even if an eviction is missed, the damage stops after, say, five minutes. Ownership means someone is paged when the cache misbehaves.

Java
// The owner of the data evicts in the same place it writes
@Transactional
public void changePrice(String sku, Money price) {
priceRepository.save(sku, price);
// after commit, so readers never cache a value that was rolled back
afterCommit(() -> priceCache.evict("price:sku:" + sku + ":" + price.currency()));
}
// priceCache is configured with expireAfterWrite = 5 minutes as the safety net

3Principle 2: No Global, Transparent Caches

A transparent cache is one that sits in front of the database and caches whatever passes through, without the application deciding what to cache. The query cache was one; generic SQL result caches in proxies or ORMs are others. They hide coupling: a team changes a write path in one service and silently invalidates, or fails to invalidate, results that a different service depended on. They also tend to fail exactly when load rises, because invalidation work grows with write traffic.

So the rule is that caching is always an explicit decision in code, reviewed like any other design choice. If a team believes a transparent cache is justified, the platform group reviews it as an exception, with the write rate and the invalidation scope written down.

4Principle 3: Few Technologies, Shared Libraries and Standard Metrics

When every team picks its own cache library, every team rediscovers stampedes, serialisation bugs and memory leaks. The principle is to standardise on a small set, for example Caffeine for in-process caches and Redis or Valkey for shared caches, wrapped in a shared library that the platform team maintains.

That library gives everyone the same metrics for free: hit ratio, evictions, size, load time and errors, exported to the normal dashboards. It also gives stampede protection by default. In-process, Caffeine's LoadingCache already loads a missing key once while other callers wait for that result. For shared caches the library can use a short lock per key, or refresh entries early, before they expire, so a popular key never goes cold for everyone at once.

Java
LoadingCache<String, Price> prices = Caffeine.newBuilder()
.maximumSize(100_000)
.expireAfterWrite(Duration.ofMinutes(5))
.refreshAfterWrite(Duration.ofMinutes(4)) // refresh popular keys before they expire
.recordStats() // hit ratio, evictions, load time
.build(sku -> priceRepository.find(sku)); // one load per key, other callers wait
prices.get("12345"); // miss: loads from the database
prices.get("12345"); // hit
prices.stats().hitRate(); // 0.5

5Principle 4: A Written Consistency Model for Every Cache

Every cache must answer two questions in its design note: how stale may this data be, and how is staleness corrected. For a product description, ten minutes of staleness may be fine and the TTL is the whole correction. For an account balance, any staleness may be wrong, which often means the right answer is no cache. In between sit cases like stock levels, where we might allow 30 seconds of staleness on the product page but always read the database at checkout.

Writing this down turns a vague hope into something we can test and review. It also makes the cost visible to product managers, who can then decide whether 30 seconds of stale stock is acceptable for the speed it buys.

A consistency model for each cache
CacheAllowed stalenessCorrectionOwner
Product description10 minutesTTL onlyCatalogue team
Price per SKU5 minutes, evicted on changeEvict after commit, TTL as backupPricing team
Stock on product page30 secondsTTL; checkout always reads the databaseInventory team
Account balanceNoneNot cachedPayments team
The note is short, but it forces every team to state the rule before the cache ships.

6Principle 5: Caches Belong in Capacity Planning and Incident Reviews

A cache with a 95 percent hit ratio means the database sees only 5 percent of reads. If the cache is flushed, or a deploy restarts every instance at once, the database suddenly sees twenty times its usual load. So capacity planning must include the cold-cache case: either the database can survive it, or we have a warm-up plan and a way to shed load.

We test this deliberately. In a load test we disable the cache, or start with it empty, and watch what breaks. In incident reviews we ask whether a cache was involved and whether its consistency note was right. Over time this builds the habit that caches are part of the system's design, not a free optimisation added at the end.

Step throughReviewing a new cache proposal
  1. Does the owner of the data control its writes?
    YesCache close to that domainNoRedesign or do not cache
  2. Write keys, TTL and ownerexplicit keys, a safety TTL, a paging team
  3. Write the consistency modelallowed staleness and how it is corrected
  4. Use the shared librarymetrics and stampede protection by default
  5. Does the system survive a cold or failed cache?
    YesApproveNoAdd warm-up or load shedding first

5 steps in order. Play them, or step through them one at a time.

7Follow-up questions

How do you handle invalidation when another system writes to the same table?

First I would ask whether that other system should be writing there at all, because two writers is the root problem. If it must, the cache owner needs a change signal, for example change data capture from the database log into Kafka, so the cache can evict entries for rows changed by anyone. Until that exists, I would keep the TTL short enough that the staleness is acceptable, and say so in the consistency note.

Is the Hibernate second-level cache always a bad idea?

No. It works well for reference data that changes rarely and is written only through Hibernate, such as country lists or product categories, with READ_ONLY or NONSTRICT_READ_WRITE strategies and a TTL. The problems come from enabling it broadly, for entities that other systems update, or from enabling the query cache, which is invalidated whenever any of the tables it touches is written.

8Conclusion

In this answer, we saw that the MySQL query cache, a broadly enabled Hibernate second-level cache and home-grown caches failed for related reasons: nobody owned their correctness, invalidation was implicit, and an empty cache had never been planned for. The principles that follow from that history are to cache close to the domain with explicit keys, TTLs and owners, avoid transparent global caches, standardise on a few technologies with shared metrics and stampede protection, write a consistency model for each cache, and include the cold or failed cache in capacity planning, testing and incident reviews.

What to say in the interviewAbout 90 seconds aloud

Open with

Looking at our incidents, the common cause was not the technology but caches nobody owned. The MySQL query cache invalidated whole tables on every write and serialised on a global lock, which is why MySQL removed it in 8.0.

Then, if they want more

Our second-level cache served stale data because other systems wrote to the same tables, and the in-house caches stampeded the database when hot keys expired. So I would set five principles. Cache only where the invalidation rule is known, which means close to the domain that owns the writes, with explicit keys, a safety TTL and a named owner.

No transparent global caches; caching is an explicit, reviewed decision. Standardise on a couple of technologies, say Caffeine and Redis, behind a shared library that gives hit ratio, eviction and size metrics and stampede protection by default.

Every cache gets a short written consistency model: how stale it may be and how that is corrected, and some data, like balances, is simply not cached. And caches are part of capacity planning: we load test with the cache empty or down, and incident reviews ask whether a cache was involved.

I would roll this out through the design review template and the shared library, and ask each team to inventory its existing caches, fixing the ones without TTLs or with unknown writers first.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Official documentation
MySQL reference manual
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "The MySQL query cache, Hibernate second-level cache defaults and several in-house caches...": https://scrivio-interview-library.netlify.app/databases/mysql/331e0e76f9/