How does Platform Cache enhance integration performance and minimize redundant remote callout latency?
Answer
Basics: There are two caches: Org Cache (shared by all users, for example a token or a currency table) and Session Cache (per user session, for example user-specific lookups). You allocate capacity to named partitions in Setup, Platform Cache. Data is read with Cache.Org.get(key) and written with Cache.Org.put(key, value, ttlSeconds). It is a cache, not a database.
How it works (cache-aside):
- Try
getfrom the cache. - On a miss (null), do the callout or query.
putthe result with a TTL.- Next requests hit memory; the cache evicts entries on TTL expiry or when space runs out.
Keys use the form
namespace.partition.key(orlocal.Partition.key); alphanumeric only.
Advanced / deep dive: Capacity depends on edition and purchases (Developer Edition includes a small free allocation, commonly 10 MB; verify current allocations). TTL limits are roughly up to 48 hours for org cache and 8 hours for session cache. A single cached item has a size limit (commonly cited as 100 KB). Cache.CacheBuilder implements doLoad(String key) so a get automatically loads on miss. Good candidates: OAuth tokens from custom flows (TTL slightly shorter than token life), reference lists, feature flags, expensive aggregate results. Bad candidates: anything requiring transactional correctness, data that changes every request, or secrets without considering exposure to other Apex code. Because eviction is unpredictable, every read path must tolerate a miss. Invalidate explicitly with remove when the source data changes. In tests, cache is empty and isolated from org data, so design for miss and use stubs where required. It reduces API consumption and latency, but concurrent requests that all miss can cause a "thundering herd" of identical callouts.
Code / config example:
public static String getToken() {
Cache.OrgPartition part = Cache.Org.getPartition('local.Integration');
String token = (String) part.get('erpToken');
if (token == null) { // cache miss
token = ErpAuth.fetchToken(); // one callout
part.put('erpToken', token, 3300); // 55 minutes for a 60-minute token
}
return token;
}
Hidden gotchas & must-remember points:
- A null result may mean miss or eviction; never assume presence.
- Session cache is per session and unavailable in async contexts like batch (no session).
- Zero allocation means
putsilently does nothing or errors depending on setup; check partition capacity. - Cached values must be serializable.
- It does not replace Named Credentials, which already manage tokens.
Best practice: Cache only read-heavy, tolerant data with a deliberate TTL and an explicit invalidation path.