Caching reduces redundant work — query, callout, computation.
Cache types:
1. Apex Platform Cache.
- Org Cache — shared across users; for org-wide data.
- Session Cache — per-user; for user-specific.
- API:
Cache.Org.put / get,Cache.Session.put / get. - TTL configurable.
- Capacity tied to license.
- Up to 100 KB per value.
2. Custom Metadata Type cache.
- CMDT auto-cached.
getInstance()is essentially free. - Best for static-ish config.
3. Lightning Data Service cache.
- LWC
getRecordresults cached client-side. - Shared across components on same page.
4. Record cache via SOQL.
- Apex transaction-level cache: same SOQL within transaction returns same data.
- Useful for utility methods called repeatedly.
5. CDN / Static Resources.
- Static assets cached at browser / CDN.
6. External cache (Redis / Memcache).
- Via Heroku / external infra.
- For high-volume, complex caching beyond Salesforce limits.
Architectural questions:
- What to cache? Frequently-read, rarely-changed data. Country lists. Tax rates. Permission profiles.
- Where to cache? Org Cache for shared data. Session for user-specific. CMDT for static.
- How long? TTL based on staleness tolerance. 1 hour for moderately-changing; 24 hours for stable.
- Eviction policy? TTL or LRU.
- Cache miss handling? Graceful — recompute on miss.
Anti-patterns:
- Caching mutable per-user data in Org Cache — security leak.
- No miss handling — assumes cache always has data.
- Stale data sin — cache hit returns wrong data; users confused.
- Cache stampede — many concurrent misses recompute simultaneously, overwhelming the source.
Cache coherence:
When source data changes, invalidate cache. Patterns:
- TTL-based expiry.
- Event-driven invalidation (Platform Event triggers cache clear).
- Versioned cache keys (change key on data change).
Architect role: define what gets cached, where, with what TTL. Without strategy, caching is ad-hoc and inconsistent.
The senior insight: caching is one of the great optimisations and one of the great bug sources. Used thoughtfully, it transforms performance. Used carelessly, it produces stale-data nightmares.
