Salesforce Developer Platform Cache Eviction And Expiration

salesforce-developer-platform-cache

// Salesforce - Developer - Platform Cache - Eviction and Expiration:

Platform Cache is intended as a temporary space. For example, the cache might 
have expired. Even if the cache is still alive, it is possible that your cached 
data might be evicted from the cache. Just like chipmunks clean out their cheeks 
to make space for more acorns, Platform Cache also clears some space for more 
data! When the partition limit is exceeded, Salesforce evicts cached data based 
on a least recently used (LRU) algorithm. The cache eviction takes place until 
usage is reduced to less than or equal to 100% capacity. Also, if you exceed the 
local cache limit, items can be evicted from the local cache before the request 
has been committed.

The amount of time during which data is kept in the cache is called the 
time-to-live value (ttlsecs). You specify the time-to-live value when you store 
a key-value pair in the cache using Apex methods. For session cache, your data 
can live up to 8 hours in the cache. For org cache, your data can live up to 48 
hours in the cache. By default, the time-to-live value for org cache is 24 
hours.

Our code should anticipate and accommodate points of failure. Always assume that 
a cache miss can happen. A cache miss is when you request a value for a key 
from the cache but the value is not found. The value that your get() call 
returns is null. Check the result of the get() call for null and handle it 
accordingly. For example, if the result is null, get the value from the database 
or an API call.

The following Apex snippet shows how to handle a cache miss by checking whether 
the returned value from the cache is not null.  If the value is not null, you can use 
the value, for example, to display it on a page. Otherwise, fetch this value from 
another source, such as an API call or from Salesforce.

Cache.OrgPartition orgPart = Cache.Org.getPartition('local.CurrencyCache');
String cachedRate = (String)orgPart.get('DollarToEuroRate');
// Check the cache value that the get() call returned.
if (cachedRate != null) {
    // Display this exchange rate   
} else {
    // We have a cache miss, so fetch the value from the source.
    // Call an API to get the exchange rate.
}
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License