Skip to content
System Design Lab
Design to Scale

Cache Invalidation

Decide how cached copies learn that the database changed — wait for a TTL, delete on write, or write through — and measure how stale your users' data really is.

Intermediate 4 min read· Updated 2026-11-18

What you will learn

  • Compare TTL expiry, delete-on-write and write-through invalidation.
  • Measure staleness instead of guessing it.
  • Spot the race that puts an old value back after a delete.
  • Choose TTLs as a safety net, not the only mechanism.

Before you start

Overview

A shop prints price tags from its price list. If the manager changes a price, the old tag stays on the shelf until someone replaces it. Cache invalidation is deciding who replaces the tag, and when.

With cache-aside the cache holds a copy of database data. When the data changes, the copy is wrong until it is removed or replaced. The three common approaches differ in who does that: time (TTL), the writer deleting the key, or the writer updating it.

Run it

Every cached value remembers the database version it came from, so the simulation counts stale hits exactly. Compare A, B and C, then lower the TTL in A to see the trade-off between staleness and database reads.

Loading simulation…

Strategies

StrategyOn writeStalenessWatch out for
TTL onlyNothingUp to the TTLShort TTLs cost hit ratio; long TTLs show old data
Delete on writeUpdate DB, then delete the keyTiny, from racesA concurrent read can re-cache the old value
Write-throughUpdate DB, then set the new valueTinyCaching values nobody reads; two writers can race
Event-drivenConsumers of change events (CDC) delete keysEvent lagMore moving parts; works across services

The delete-on-write race

  1. Reader misses and reads version 1 from the database.
  2. Writer updates the database to version 2 and deletes the key (nothing to delete yet).
  3. Reader stores version 1 in the cache — now stale until the TTL expires.

That is why B is not quite zero. Fixes include a short TTL as a safety net, a delayed second delete, or storing the version with the value and refusing to overwrite a newer one.

Implementation

Delete after commit, with a TTL safety net
@Transactional
public void changePrice(long productId, Money price) {
    products.updatePrice(productId, price);
    // Delete only after the transaction commits, otherwise a reader could re-cache the old row.
    TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
        @Override public void afterCommit() { redis.delete("product:" + productId); }
    });
}

public Product getProduct(long productId) {
    String key = "product:" + productId;
    Product cached = redis.get(key);
    if (cached != null) return cached;
    Product fresh = products.findById(productId).orElseThrow();
    redis.set(key, fresh, Duration.ofMinutes(10));   // TTL bounds the damage of any missed invalidation
    return fresh;
}

Trade-offs

BenefitsCosts
FreshnessExplicit invalidation keeps data fresh within milliseconds.Every write path must remember to invalidate — one forgotten path serves old data until the TTL.
LoadWrite-through keeps hot keys cached through updates.Delete-on-write turns every update of a hot key into a miss.
SimplicityTTL-only needs no coordination at all.Staleness equals the TTL; you trade freshness against hit ratio.

Production considerations

  • Always keep a TTL, even with explicit invalidation.
  • Invalidate from one place — ideally change events (CDC) — so new write paths cannot forget.
  • Decide per data type how stale is acceptable: prices and stock seconds, profile pictures hours.
  • Sample cached values against the database in production to measure real staleness.

Further reading

Related topics