Data and Distributed Systems · 18 min · free lesson

Caching and Invalidation

Caching is easy; deciding when the cache is wrong is not.

Core idea

Every cache needs a bound, an eviction policy, and a stated staleness budget.

Lesson map: an LRU cache get, load and put sequence, above the rule that every cache needs a bound, an eviction policy and a staleness budget.
Cache pseudocode: supply the cache type, capacity API, error context and loader; concurrent refill needs an explicit policy.

Understand it

A TTL trades staleness for simplicity, explicit invalidation trades simplicity for correctness, and write-through trades write latency for both. The failure modes are the interesting part: a stampede when a hot key expires, and unbounded growth without an eviction policy. Naming which staleness your product can tolerate is the real answer.

A cache is a second copy of data, so every design must answer when that copy is valid. A time-to-live is easy to operate but permits bounded staleness. Explicit invalidation can reduce staleness but must account for every writer and failure path. Write-through updates cache and source together from the application's point of view, but partial failure and ordering still need a policy. The right choice depends on whether a stale value is harmless, confusing, or financially dangerous.

Suppose a product page is read thousands of times but price changes rarely. A short TTL may be acceptable for descriptive text, while a checkout price needs a fresh authoritative check. When a hot key expires, many callers can stampede the database. Use request coalescing, a staggered expiry, or stale-while-revalidate where the product permits it. Put a capacity and eviction policy on the cache; otherwise high-cardinality keys can consume unbounded memory.

For an interview, write the read path, write path, failure path, and invalidation path on the board. Ask how the cache behaves when the source is down and how a client knows it got an old value. Measure hit rate alongside tail latency and database load; a high hit rate can still hide one critical uncached query. State the acceptable staleness as a product requirement before arguing about implementation.

Cache keys need versioning too. If an authorization rule or schema changes, a key that omits the relevant version can return a logically invalid result even before its TTL expires. Define whether negative results are cached and for how long; an absent item that soon appears is a common source of stale behavior. Test invalidation under concurrent writes.

Interview follow-up: What happens to single-flight waiters when the refresh fails or its initiating request is cancelled? Define stale-data policy too.

Read the code

let cache = LruCache::new(10_000);
if let Some(hit) = cache.get(&key) {
    return Ok(hit.clone());
}
let value = load(&key).await?;
cache.put(key, value.clone());

Cache pseudocode: supply the cache type, capacity API, error context and loader; concurrent refill needs an explicit policy.

Practice starter

// Many requests miss the same key before any refill completes.
// Cache lookup and origin loading are separate operations.

Practise this code in Playground ↗

Try it

Choose an invalidation strategy for two different kinds of data.

What success looks like: Each choice names the staleness it accepts and the eviction policy.

Check your understanding

With no request coalescing, what can concurrent misses for one expired hot key cause?

Reveal the answer
  1. The cache API automatically serializes every application’s refill function.
  2. Several overlapping origin loads, increasing pressure during the refill interval.
  3. A TTL guarantees that only one caller can observe an expired entry.

A stampede is possible, not a claim that every request always reaches the origin. Use a bounded single-flight or another explicit refresh policy.

Go deeper

Common misconception: A TTL guarantees that only one caller can observe an expired entry.

A TTL only sets when an entry expires. Every request that arrives before the refill completes can see the same miss, unless something coalesces them.

  1. Identify the contract: Caching is easy; deciding when the cache is wrong is not.
  2. Trace the concrete example: Bounded, with a policy for what leaves and when.
  3. Test the changed constraint: What happens to single-flight waiters when the refresh fails or its initiating request is cancelled? Define stale-data policy too.

Transfer challenge: What happens to single-flight waiters when the refresh fails or its initiating request is cancelled? Define stale-data policy too.

Connections

  • Idempotency and Retries: Making at-least-once safe
  • Complexity in Practice: Constants, cache, and amortised cost
Learn this lesson with AI

Paste this into Claude, Codex, Cursor or another agent connected to Crabrix Academy. It contains only this lesson’s public details.

I'm learning Rust with Crabrix Academy. Teach me this lesson with the Crabrix Academy tools.
Lesson: Caching and Invalidation (courseId "interview", lessonId "q-caching")
Link: https://crabrix.com/learn/interview/q-caching/
Goal: Every cache needs a bound, an eviction policy, and a stated staleness budget.
Practice: open the starter in the Crabrix Playground (https://crabrix.com/playground/?lesson=interview/q-caching) and I will write the code there.
Explain it step by step for my level, let me write the code myself, give hints before any solution, and do not mark anything as passed: only Crabrix checks do that.

In Claude Code, Codex or Cursor, paste it into a chat with Crabrix Academy connected. On a phone, the Claude and ChatGPT apps open the same links.