How can Platform Cache optimize data retrieval within Batch Apex execution chunks?
Answer
Basics: Each execute() is a separate transaction with fresh limits, so a lookup that each chunk needs (for example a mapping table) would be queried again 5,000 times for a million records. Caching it in Platform Cache saves SOQL and CPU.
How it works:
- An admin allocates cache capacity to a partition (Setup, Platform Cache).
- In
execute(), tryCache.Org.getPartition('local.RefData').get('key'). - On a miss, query, build the map, and
putit with a TTL. - Use the value for the chunk.
Advanced / deep dive: Cache is best-effort: entries can be evicted at any time (capacity pressure or TTL), so code must always have a fallback. Org cache TTL ranges up to 48 hours. Values must be serializable and are copied on read, so very large maps cost heap and CPU. Capacity depends on edition and purchased allocation (verify in current docs); without allocation, calls fail or return null. Alternatives: Database.Stateful (state persists across chunks within one job, but costs heap each chunk), Custom Metadata (cached, queryable, no SOQL limit consumption for getAll), or static variables loaded once per transaction (only per chunk). Cache is not transactional and not for secrets. Parallel chunks and concurrent jobs can race on population, so make loading idempotent.
Code / config example:
public static Map<String,Decimal> getRates() {
Cache.OrgPartition part = Cache.Org.getPartition();
Map<String,Decimal> rates = (Map<String,Decimal>) part.get();
(rates == ) {
rates = <String,Decimal>();
(Rate__c r : [SELECT Code__c, Value__c FROM Rate__c]) {
rates.put(r.Code__c, r.Value__c);
}
part.put(, rates, );
}
rates;
}