Versioned Cache Keys
What you'll learn: How to embed version identifiers directly into cache keys so old data expires automatically without manual deletion.
The Core Idea
Instead of trying to find and delete old cached data when something changes, you can include a version number or identifier in the cache key itself. When the data updates, you simply change the version—making the old cached entries unreachable and effectively "invalidated" without touching them.
Think of it like this: instead of erasing an old note on a whiteboard, you write a new note with "v2" in the title. The old "v1" note still exists, but everyone knows to ignore it. Eventually, it gets cleaned up automatically (through TTL expiration).
How It Works
A typical cache key might look like:
user:12345:profile
With versioning, you embed the version:
user:12345:profile:v7
When you update the user's profile, increment the version to v8. Now all code requests user:12345:profile:v8, and the v7 entry is simply abandoned. Your eviction policy (LRU, TTL, etc.) will eventually remove it.
Why This Matters
This approach solves several invalidation headaches at once:
- No manual deletion logic needed across your codebase
- Atomic updates - new version appears instantly, no race conditions
- Gradual migration - old and new versions can briefly coexist
- Simplified code - just change the version identifier
Key Takeaway: Versioned cache keys let you "invalidate" data by simply ignoring it—changing the version makes old entries unreachable, and your eviction policy cleans them up naturally.