Skip to main content

Cache Invalidation

1. Executive Summary​

Cache invalidation is the process of removing or updating cached entries so clients do not observe indefinitely stale data relative to the authoritative source. Phil Karlton's aphorism—"There are only two hard things in Computer Science: cache invalidation and naming things"—remains relevant because invalidation spans multiple cache tiers, concurrent writers, eventual propagation delay, and ambiguous ownership of who invalidates what.

Strategies include TTL-only (accept bounded staleness), write-invalidate (delete keys on mutation), write-update (push new value to cache), version stamps (compare-and-swap semantics), pub/sub fan-out (notify all app instances), CDC-driven invalidation, and CDN purge APIs. No single strategy fits all data—prices demand immediate invalidation; aggregate counters may tolerate seconds; static assets use content-hash immutability.

This chapter covers invalidation patterns, consistency models, multi-tier propagation, failure modes, CDN specifics, stampede prevention, and principal-level design for correct cached systems.

2. Why This Topic Matters​

Interviewers probe beyond "add Redis": "Product price changes—how fast do users see it?" Weak answers say "short TTL."

Strong candidates explain:

  • TTL is a staleness bound, not guaranteed freshness after writes.
  • Delete-on-write beats update-on-write for race avoidance in cache-aside.
  • CDN purge is slow and rate-limited—immutable URLs often beat purge.
  • Invalidation storms can overload origin during mass updates.
  • Derived cache keys (aggregates, joins) multiply invalidation surface.

Production bugs include double-discount from stale coupons, sold-out items still purchasable, permissions cached after revocation, and cross-region stale reads after partial purge. Invalidation is where caching becomes a correctness problem, not just performance.

3. Problems Being Solved​

ProblemNaive TTL-onlyInvalidation strategy
Stale writes visibleWait until TTLProactive delete on write
Multi-tier cachesEach tier divergesCoordinated purge or versioned URLs
Derived dataOrphan stale aggregatesTrack dependencies or recompute
Global CDNHours of stale contentPurge API or immutable asset pattern
Permission revocationSecurity windowShort TTL + explicit invalidation

Invalidation solves freshness correctness within defined SLAs. It does not provide strong linearizability across all readers without synchronous read-through or bypassing cache on critical reads.

4. Assumptions and System Model​

Assume multiple writers (admin APIs, batch jobs, replication) and multiple cache layers (local, Redis, CDN):

  • Authoritative source is database or event log.
  • Invalidation messages may be lost, duplicated, or reordered (at-least-once pub/sub).
  • Propagation is not instantaneous—milliseconds to minutes depending on tier.
  • Clock skew affects TTL expiry times slightly—not for logical versioning.

Staleness SLA examples:

Data typeTypical SLAStrategy
Stock price< 1sInvalidate + short TTL
Product description< 5 minTTL + invalidate on admin
Avatar imageMinutes–hoursImmutable URL with hash
Session permissionsImmediateNo cache or sub-second TTL + revoke

5. Essential Terminology​

TermDefinition
TTL invalidationPassive expiry by time.
Active invalidationExplicit delete/update on data change.
Write-invalidateRemove cache entry on write.
Write-updatePush new value to cache on write.
Version stampMonotonic version; readers reject old versions.
Cache taggingGroup keys under tag; invalidate tag in one operation.
Surrogate keyCDN tag for related objects (e.g., all product pages).
Purge vs banPurge removes if present; ban prevents future cache (CDN-specific).
Thundering herdMany concurrent misses after invalidation.
Torn cachePartially updated related keys—inconsistent view.

Mnemonic: Invalidate proactively; TTL is the safety net.

6. Core Mechanism​

Write-invalidate (cache-aside)​

Figure 1: Delete cache after DB commit—preferred over UPDATE cache for race safety.

Pub/sub fan-out to local caches​

Figure 2: Distributed local caches require broadcast invalidation—missed message = stale local entry until TTL.

CDN surrogate key purge​

Figure 3: CDN purge is asynchronous—design for brief staleness or immutable URLs.

7. Step-by-Step Walkthrough​

Scenario: Blog platform caches article HTML in Redis, local cache, and CDN.

LayerKey / mechanismInvalidation on publish
DBarticles tableSource update
Redisarticle:{slug}DEL on publish webhook
LocalCaffeine article:{slug}Redis pub/sub invalidate:{slug}
CDNURL /articles/{slug}Surrogate-key purge article-{id}

Ordering requirement:

StepActionRisk if wrong order
1Commit DB with new content—
2DEL RedisStale if before DB commit
3PUBSUB local evictBrief local staleness if missed
4CDN purgeAsync delay unavoidable

Derived key problem:

Cached keyDepends on
homepage:featuredArticles 1, 5, 9
category:tech:listAll tech articles

Updating article 5 must invalidate all derived keys—maintain dependency graph or avoid caching aggregates without tagging.

Version stamp alternative:

ApproachMechanism
Store {value, version} in cacheWriter bumps version in DB
Reader compares cache version to DB version on readReject stale cache

Higher read cost but simpler fan-out for read-heavy paths.

Two-cache problem (Martin Thompson):

When two independent caches store related data without coordination, readers may observe inconsistent combinations—cache A fresh, cache B stale. Example: product price cache updated but category listing cache still shows old price.

SolutionTradeoff
Single aggregate cache keyLarger values; over-invalidation
Version vector on all related keysReader checks all versions match
Invalidate all related on any changeTag-based invalidation
Don't cache aggregatesHigher origin load

Probabilistic early expiration (stampede prevention detail):

Instead of fixed TTL expiry for hot keys, each read has small probability p of treating the key as expired even if TTL remains:

if (now > expiry - jitter) OR (random() < p):
trigger background refresh (single-flight)
return stale value if refresh in progress

This spreads refresh load over time rather than concentrating at exact expiry. Libraries like cachestampede implement variants—verify algorithm against your staleness SLA.

Invalidation via change data capture (CDC):

StepComponent
1Database commit changes row
2Debezium reads WAL/binlog
3Invalidation service consumes change event
4Maps table row to cache key(s) via config
5DEL Redis keys; optional pub/sub to local caches

Advantage: Writers do not need cache knowledge—decouples teams. Disadvantage: CDC lag (typically ms–seconds) creates invalidation delay; derived key mapping must be maintained in invalidation service config.

Legal and compliance invalidation:

GDPR right to erasure requires deleting personal data from all cache tiers including CDN edge nodes—not just origin database. Maintain a data map listing which cache keys may contain PII and automate purge on erasure requests. Failure to purge CDN cached profile pages is a documented compliance gap in several enforcement actions—treat CDN as part of data storage scope.

Cache-aside race conditions (detailed):

RaceSequenceOutcome
Read stale after writeT1: Writer updates DB; T2: Reader misses cache (not yet invalidated); T2: Reader loads OLD DB value if read replica lags; T2: Reader SETs stale valueExtended staleness
Thundering populateN readers miss; N concurrent DB queriesOrigin spike
Lost invalidationInvalidation message lost; TTL only recoveryStale until TTL

Fix for populate race: Use per-key lock (mutex) or SETNX with short TTL during populate—only one loader per key.

Write-behind consistency window:

Write-behind caches acknowledge writes immediately and batch-flush to DB asynchronously:

BenefitRisk
Sub-ms write latencyData loss if cache node crashes before flush
Absorbs write spikesComplex conflict resolution on flush

Use write-behind only when business tolerates seconds of durability risk and you have WAL/replay on cache failure—or restrict to non-critical counters.

CDN cache key normalization:

CDNs cache by full URL including query string—?v=1 and ?v=2 are different cache entries. Standardize:

  • Version in path (/assets/app.v42.js) not query for cache efficiency.
  • Normalize query parameter ordering if query-based keys unavoidable.
  • Use surrogate keys for logical invalidation across URL variants.

Invalidation SLA documentation template:

Every cached entity should have an entry in the cache contract:

FieldExample
EntityProduct.price
Cache keysproduct:{id}, CDN surrogate product-{id}
Max staleness5 seconds
Invalidation triggerProductUpdated event, admin API
Owner teamCatalog
FallbackTTL 60s

This template forces explicit ownership—gaps surface in architecture review rather than production incidents.

Multi-writer invalidation coordination:

When multiple services can update the same entity (e.g., admin API and batch price sync job), invalidation must be centralized or idempotent:

ApproachDescription
Single writer principleOnly one service mutates; others request via API
Shared invalidation topicAll writers publish InvalidateKey events
Version monotonicHighest version wins; stale invalidations harmless

Without coordination, race between two writers can leave cache inconsistent with DB even after both invalidate—last writer to DB must win; use DB version in cache value.

Principal review checkpoint: Ask "what is the maximum staleness a customer can observe after an admin update?" If the team cannot answer with a number and tier breakdown (local, Redis, CDN), the invalidation design is incomplete.

Hands-on validation: Measure end-to-end staleness with integration tests that write to DB, poll CDN edge and Redis until fresh or timeout—automate this in CI for price-sensitive entities.

8. Invariants and Guarantees​

PropertyTypeStatement
Fresh read after invalidationSafety (eventual)After propagation completes
No stale read foreverLivenessTTL provides ultimate bound
Immediate global consistencyNot guaranteedCDN and local tiers lag
Invalidation idempotencySafetyDuplicate DEL safe

9. Failure Scenarios​

Scenario 1: Invalidation before DB commit​

Setup: DELETE cache then DB transaction rolls back.

Effect: Cache empty; next read loads old DB value—OK. Worse variant: UPDATE cache then rollback leaves wrong cache.

Mitigation: Invalidate only after commit; transactional outbox for invalidation events.

Scenario 2: Missed pub/sub message​

Setup: App instance offline during invalidation broadcast.

Effect: Stale local cache until TTL.

Mitigation: Short local TTL; periodic version check for critical data.

Scenario 3: Partial derived invalidation​

Setup: Product update; homepage aggregate not invalidated.

Effect: Wrong featured price on homepage.

Mitigation: Tag-based invalidation; recompute aggregates from events.

Scenario 4: CDN purge rate limit​

Setup: Black Friday mass price update; 10k purges.

Effect: Purge queue backlog; widespread stale prices.

Mitigation: Immutable versioned URLs (/price/v42); batch surrogate purge; accept SLA.

Scenario 5: Invalidation stampede​

Setup: DEL hot key; 50k requests miss simultaneously.

Effect: Origin overload.

Mitigation: Single-flight reload; soft TTL with background refresh.

Scenario 6: Cross-region replication lag​

Setup: Write to primary region; read from replica before replicate.

Effect: Cache repopulated with stale replica data.

Mitigation: Read-your-writes routing; invalidate after replication ack.

10. Performance Characteristics​

StrategyWrite path costRead path costFreshness
TTL onlyLowLowBounded stale
Write-invalidateMedium (DEL)Low after warmGood post-propagation
Write-updateMediumLowest if hitRace risk
Version check each readLow writeHigher readStronger
CDC invalidationAsync lagLowNear-real-time

Pub/sub fan-out: O(instances) messages per invalidation—acceptable for admin edits; problematic for high-frequency writes.

11. Scalability Limits​

  • Tag purge cardinality—some CDNs limit tags per object.
  • Dependency graph maintenance complexity grows with aggregate caches.
  • Invalidation rate during flash sales may exceed purge API quotas.
  • Global CDN purge propagation 150ms–minutes (vendor-dependent; verify docs).

12. Operational Considerations​

  • Invalidation audit log—who purged what, when.
  • Dashboards: stale read reports, purge queue depth, post-deploy cache hit drop.
  • Runbooks: emergency global purge; disable cache toggle flag.
  • Integration tests: publish → assert all tiers within SLA.
  • Feature flag to bypass cache for debugging.

13. Security Considerations​

  • Authorization cache must invalidate on role change—security-critical.
  • Purge API keys highly privileged—prevent attacker mass purge DoS.
  • Cache key guessing after invalidation may timing-attack—low risk but awareness.
  • GDPR erasure requires delete across all tiers including CDN.

14. Cost Considerations​

  • CDN purge API may be priced per request at scale.
  • Over-invalidation increases origin load—balance freshness vs cost.
  • Immutable asset pattern reduces purge needs—storage for multiple versions.
  • Engineering time for dependency tracking—expensive for complex aggregates.

15. Production Implementations​

Redis keyspace notifications / pub/sub​

Lightweight app instance coordination—not durable; missed messages possible.

Debezium CDC → invalidation service​

Database change stream triggers cache deletes—decouples writers from cache knowledge.

Varnish / Fastly surrogate keys​

Tag-based bulk purge for related HTML fragments.

CloudFront invalidation​

Path-based purge; limits on concurrent invalidations—check AWS current quotas.

Hibernate second-level cache​

Region invalidation on entity update—ORM-managed; understand session boundaries.

GraphQL @cacheControl​

Schema-level TTL and scope—CDN integration in Apollo Router and similar.

16. Alternatives and Tradeoffs​

ApproachFreshnessComplexityWrite amplification
TTL onlyPoor on changeLowestNone
Write-invalidateGoodMediumLow
Immutable URLsExcellent for assetsMediumNew object per version
No cache on critical readsPerfectLow read perfNone
Event-driven materialized viewsEventualHighRecompute on event

17. Common Misconceptions​

MisconceptionReality
"Zero staleness with CDN"Purge is async; plan for window.
"UPDATE cache is simpler than DELETE"Races cause stale writes winning.
"One TTL fits all"Entity-specific SLAs required.
"Invalidation is instant everywhere"Multi-tier propagation takes time.
"CDC solves everything"Lag + derived keys still hard.

18. Principal Architect Perspective​

  1. Classify data into freshness tiers before choosing strategy.
  2. Prefer immutable URLs for static content over purge-heavy workflows.
  3. Delete not update cache on write in cache-aside.
  4. Tag related keys early—retrofit is painful.
  5. Test invalidation in CI as first-class scenario.

Governance: Cache invalidation contracts in API design—every write endpoint documents which keys/tags it invalidates.

19. Architecture Review Exercise​

Scenario: Marketplace caches seller ratings aggregate; individual review updates don't invalidate; 1-hour TTL.

Review prompts:

  1. Fraudulent review hidden—visible in aggregate?
  2. Legal takedown timeline met?
  3. Redesign invalidation?

Expected findings: Invalidate aggregate on review change; event-driven recompute; shorter TTL for legal-sensitive data.

20. Whiteboard Explanation​

90-second version:

"Cache invalidation keeps cached data from going stale wrong. TTL alone means users see old data until expiry—use TTL as safety net, not primary strategy. On writes, commit to database first, then delete cache keys—delete beats update because concurrent reads won't write stale values back. Multiple tiers need coordinated invalidation: Redis DEL plus pub/sub to evict local caches plus CDN surrogate-key purge. CDN purge is async and rate-limited—use content-hash immutable URLs when possible. Derived caches like homepage lists need tag invalidation or dependency tracking. Watch thundering herd after mass invalidation—single-flight reload. Classify data by staleness SLA—prices aren't like profile bios."

21. Interview Questions​

  1. TTL vs active invalidation?

    • Signals: Bound vs proactive; combine both.
  2. Delete vs update cache on write?

    • Signals: Delete avoids races.
  3. CDN stale after purge?

    • Signals: Async propagation; immutable URLs.
  4. Invalidate local + Redis?

    • Signals: Pub/sub, short local TTL.
  5. Derived aggregate invalidation?

    • Signals: Tags, dependency graph, avoid cache.
  6. CDC for invalidation?

    • Signals: Decouple; eventual lag.
  7. Security-sensitive cache?

    • Signals: Short TTL, explicit revoke, no cache.
  8. Thundering herd after purge?

    • Signals: Single-flight, soft TTL.
  9. Design price change flow.

    • Signals: DB commit, DEL keys, CDN purge, SLA.
  10. Karlton quote implications?

    • Signals: Multi-tier, races, ownership complexity.

Scoring rubric:

DimensionStrongWeak
OrderingInvalidate after commitBefore commit
Multi-tierCDN + Redis + localRedis only
Derived dataTags/dependenciesSingle key focus

22. Interview Follow-Ups​

  1. Mass invalidation during sale—strategy?

    • Signals: Versioned URLs, batch surrogate purge, pre-warm.
  2. Invalidation event lost?

    • Signals: TTL backup, durable invalidation log, version check.
  3. Global active-active invalidation?

    • Signals: Cross-region pub/sub, CRDTs rare; often sticky routing.

22A. Production Low-Level Design (Interview + Game Day)​

Write-path invalidation with stampede protection on hot keys. Production LLD and Game Day Standard.

Control vs data plane​

PlaneComponents
ControlOutbox / PriceChanged bus, invalidation matrix per entity, version monotonic
DataRegional Redis DEL, local LRU evict (pub/sub), CDN surrogate purge, backup TTL

Step-by-step flow:

StepActionFailure if skipped
1Commit DB + bump price_versionStale authoritative data
2Emit durable invalidation event (outbox)Lost DEL on crash
3Regional Redis DEL / SET new valueCross-region staleness
4Pub/sub flush in-process LRUPod serves stale until local TTL
5–7Singleflight on miss + jittered TTLThundering herd melts origin

Contract​

FieldExample
Max staleness SLA5s p99 price (active invalidate; TTL 60s backup)
IdempotencyDuplicate PriceChanged → idempotent DEL
StampedePer-key lock / singleflight.Group on miss

One SLO​

Price freshness: time from DB commit → p99 edge serving version ≥ committed < 5s; alert on invalidate lag p99 > 3s.


22B. Game Day Playbooks​

#DrillInjectDetectMitigateVerify
GD-1Lost invalidation messageDrop pub/sub to 10% podsStale price probe failsShort local TTL + version check on readp99 freshness < SLA within 60s
GD-2Thundering herd after mass purgeDEL 1k hot keys; spike trafficOrigin QPS 10×; p99 latencyEnable singleflight; soft TTL refreshDB QPS returns to baseline
GD-3CDN purge backlogRate-limit purge APISurrogate-key queue depthServe price via uncached API JSONProbe edge freshness < 5s

GD-2 — Thundering herd after invalidation​

23. Strong Answer Example​

Question: "Ensure product price updates visible within 5 seconds globally."

Answer this as a 45-minute design discussion using the PRACTICE framework. Below is how a strong student sounds aloud—active invalidation across tiers, not "TTL=5s."

PRACTICE interview answer map for global price freshness within 5 seconds

Figure A: PRACTICE map — Problem → Requirements → Assumptions → Capacity → Topology → Invariants → Constraints → Evolution.


Student interview script (PRACTICE)​

P — Problem framing​

"A 5-second global freshness SLO for product prices means: after the pricing write commits, users in every region should observe the new price within 5s (I'd define p99 of regions/edges).

TTL alone fails. A 5-minute Redis TTL can leave stale prices for minutes. Even TTL=5s means up to 5s average wait without tying expiry to the write—and it hammers origin. TTL is a safety net, not the primary control.

Short answer: Commit price + version to DB → durable invalidate fan-out (outbox) to all regional Redis + flush local caches → keep price JSON off long-lived CDN (or purge surrogate keys) → single-flight on miss → measure end-to-end staleness."

R — Requirements​

RequirementDesign implication
≤5s visible globally (p99)Active invalidate; budget propagation ≤ ~3–4s
No forever-stale on lost messageShort backup TTL (e.g. 30–60s) + version checks
Don't melt DB on mass sale updatesSingle-flight; soft TTL refresh; batch/tag purge
Correct vs description freshnessPrice path stricter than blurb/images
Multi-tier (local, Redis, CDN, HTML)Invalidate every tier that embeds price

"I'd ask: is price in API JSON only, or also SSR HTML / CDN edge? How many regions?"

A — Assumptions (state aloud)​

AssumptionWhy it matters
Multi-region Redis / app podsMust fan out, not DEL one cluster
At-least-once invalidation busHandlers idempotent; versions monotonic
CDN may cache HTML with embedded priceBiggest hidden staleness source
DB is source of truthCache never wins over committed version
5s is p99, not mathematical zeroCDN purge can be async—design around it

"I'd say out loud: immutable hashed images don't need 5s; price fields do."

C — Capacity​

Admin / batch price updates → outbox → invalidate workers (not sync purge in request path)
Cross-region fan-out → dominate the 5s budget; parallel DELs per region
Pub/sub to N app instances → OK for admin rates; careful under huge write storms
CDN purge quotas → avoid per-SKU HTML on CDN; or surrogate-key batch purge
Backup TTL 30–60s → bounds damage if invalidate lost; still not primary

"I'd spend the latency budget on reliable fan-out, not on hoping TTL aligns with the write."

T — Topology (draw this)​

Global price invalidation path for ≤5s freshness

Figure B: DB commit with price_version → outbox fan-out to regional Redis + local evict; price API not long-CDN-cached; total budget < 5s.

TTL-only vs active invalidation for 5s price SLO

Figure C: TTL-only cannot meet a write-triggered 5s SLO; versioned keys + regional invalidate + edge policy can.

TierStrategy for 5s price SLO
DBAuthoritative price + monotonic price_version
Redis (each region)Write-invalidate (DEL) or write-update after commit; backup TTL
In-process LRUPub/sub / bus flush; short local TTL (seconds) as backup
Price API responseCache-Control: private, max-age=0 / no-store—don't CDN-cache price JSON
SSR / product HTMLSurrogate-key purge or fetch price client-side from uncached API
ImagesImmutable URLs—out of scope for 5s price

Optional upgrade: write-update (SET new price) after invalidate to warm hot SKUs and shrink miss storms.

I — Invariants (safety)​

"Non-negotiable:

  1. Invalidate only after DB commit (outbox)—never before.
  2. Every tier that can show price is in the invalidation matrix.
  3. TTL is backup, not the 5s mechanism.
  4. Versions in cache values—reject/reload if cached.version < db.version.
  5. Idempotent invalidation handlers (at-least-once).
  6. SLO metric defined: time from commit → p99 edge/API serving new version."

C — Constraints (second C)​

ConstraintDesign response
Lost pub/sub to one podShort local TTL; version check on read for critical paths
CDN purge rate limits / async lagDon't put live price in long-lived CDN objects
Read replica lagRead-your-writes on primary for reload after invalidate
Black Friday mass updatesBatch/tag invalidation; single-flight; consider SET new value
Derived caches (category lists)Tags / dependency invalidate—or don't embed live price in list cache
Multi-writer price jobsCentral invalidate topic; highest price_version wins

E — Evolution (prove it)​

Phased delivery:

PhaseDeliverable
M1ADR: 5s p99 price SLO; invalidation matrix per tier
M2Outbox PriceChanged → regional Redis DEL + local evict
M3Strip price from CDN-cached HTML / set no-store on price API
M4price_version in responses/cache; backup TTL 60s
M5Integration probe: write → poll US/EU/APAC until fresh; alert if >5s
M6Chaos: drop invalidation message; verify TTL/version recovery

Failure modes:

FailureMitigation
"TTL=5 seconds"Active invalidate + versions
HTML CDN still stalePurge or uncache price in HTML
Local cache not flushedBus + short local TTL
Invalidate before commitOutbox after commit
Herd after mass DELSingle-flight / soft refresh

Observability: invalidate lag p50/p99 by region, stale-version serve rate, CDN purge queue depth, price probe SLO compliance, origin QPS after sales.


Closing line (interview)​

"So for prices visible within 5 seconds globally, I won't set TTL=5. I commit price + version, emit PriceChanged via outbox, invalidate every regional Redis and local cache, and keep live price off long-lived CDN (or purge surrogate keys). TTL stays a backup. I'd measure commit→edge freshness per region and alert when p99 exceeds 5s—and use single-flight so mass invalidation doesn't stampede the DB."

Scoring signals​

StrongWeak / red flag
Active invalidate + 5s budget"Set Redis TTL to 5 seconds"
Multi-tier matrix (local/Redis/CDN/HTML)Redis-only thinking
Outbox after commit + versionsInvalidate-before-write / no version
Price API cache-control policyIgnore CDN-embedded prices
SLO probe / metricsNo measurement
Stampede after mass invalidateBlind DEL storm

Compact outline (if time-boxed to 2 minutes)​

"Not TTL=5. Commit price+version, outbox fan-out invalidate to all regional Redis and local caches, don't CDN-cache live price JSON/HTML. TTL as backup. Probe p99 freshness <5s. Single-flight on miss."

24. Weak Answer Example​

Question: "Ensure product price updates visible within 5 seconds globally."

"Set Redis TTL to 5 seconds."

Why weak / red flags: TTL is not write-triggered freshness; ignores CDN/local tiers and global fan-out; causes origin load; no version/SLO measurement—classic interview trap.

25. Hands-On Exercise​

  1. Cache-aside with Redis; update DB without invalidation—measure stale duration.
  2. Add post-commit DEL; compare.
  3. Demonstrate update-cache race with concurrent readers.
  4. Add Redis pub/sub local eviction.
  5. Simulate 100 concurrent misses after DEL—add single-flight.
  6. Model tag invalidation for category:* keys.
  7. Document invalidation matrix per API endpoint.

26. Knowledge Check​

  1. Invalidate before or after DB commit? (After.)
  2. DELETE vs UPDATE cache? (DELETE safer.)
  3. CDN purge synchronous? (No—async.)
  4. TTL role with active invalidation? (Safety net.)
  5. Derived cache challenge? (Multiple keys to invalidate.)

27. Flashcards​

#FrontBack
1Write-invalidateDEL cache on write.
2Surrogate keyCDN group purge tag.
3TTL safety netBounds max staleness.
4Pub/sub evictLocal cache coordination.
5Immutable URLHash in path avoids purge.
6Thundering herdPost-invalidation miss storm.
7CDC invalidationDB change stream triggers DEL.
8Version stampLogical freshness check.
9Tag invalidationBulk related key purge.
10Torn cacheInconsistent related keys.

28. Cheat Sheet​

WRITE ORDER
1. DB COMMIT
2. DEL cache keys / tags
3. PUBSUB local evict
4. CDN purge (async)

PREFER
DELETE over UPDATE (races)
Immutable URLs for static
TTL as backup not primary

DERIVED KEYS
Tag-based invalidation
Or avoid caching aggregates

HERD
Single-flight after invalidation
Jittered soft TTL

SECURITY
Invalidate on auth change
Short TTL on permissions

30. References​

Primary sources​

  • Karlton, P. — aphorism on cache invalidation (widely cited; primary publication unverified).
  • Lamport, L. — ordering and staleness reasoning applicable to version-based invalidation.

Engineering​

Distinction​

Claim typeSource
Delete-on-write patternEngineering practice; Redis patterns
CDN purge behaviorVendor documentation—verify quotas
CDC invalidationDebezium and similar operational guides