# How can Platform Cache optimize data retrieval within Batch Apex execution chunks?

**Topic:** Apex · **Difficulty:** Medium · **Tags:** Apex, Asynchronous Apex, Platform Cache

Read it on the site: https://www.forcechallenges.com/interview-questions/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:**
1. An admin allocates cache capacity to a partition (Setup, Platform Cache).
2. In `execute()`, try `Cache.Org.getPartition('local.RefData').get('key')`.
3. On a miss, query, build the map, and `put` it with a TTL.
4. 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:**
```apex
public static Map<String,Decimal> getRates() {
    Cache.OrgPartition part = Cache.Org.getPartition('local.RefData');
    Map<String,Decimal> rates = (Map<String,Decimal>) part.get('rates');
    if (rates == null) { // miss or evicted: rebuild
        rates = new Map<String,Decimal>();
        for (Rate__c r : [SELECT Code__c, Value__c FROM Rate__c]) {
            rates.put(r.Code__c, r.Value__c);
        }
        part.put('rates', rates, 3600); // TTL in seconds
    }
    return rates;
}
```

**Hidden gotchas & must-remember points:**
- Session cache is unavailable in batch, queueable, future and scheduled contexts.
- Never assume a hit; always code the miss path.
- Cache calls count toward CPU and heap, not toward SOQL.
- Partition must exist and have capacity, and tests need `Cache` stubs or tolerate misses.
- Stale data: invalidate or version your keys when reference data changes.

**Best practice:** Cache only small, read-mostly reference data with a sensible TTL and an always-present fallback query.

---
Source: ForceChallenges · last updated 2026-11-02
