Avoid Cache misses with Cache.CacheBuilder Interface

Shama Gurav
2 min readJan 14, 2025

--

Platform cache in salesforce is an API which is provided to save and retrieve frequently used data across salesforce sessions or org.

Please refer below article for more information about platform cache,

If you are using platform cache then it is substantial to handle the cache misses to avoid data loss or any other implications caused by it.

Cache misses can be handled by writing your own custom code as described in above article. Or by using Cache.CacheBuilder interface.

Using Cache.CacheBuilder interface is easy and less time consuming.

Cache.CacheBuilder interface has method doLoad(var). This method needs to be implemented to use this interface.

doLoad(var):

This method consist of the logic to avoid cache misses. If data is missing for provided cache key then this method caches the values and return the same. This method gets called indirectly when you reference the class which implements CacheBuilder interface.

CacheBuilder Implementation Example:

Apex class CountryCodeCache has implemented Cache.CacheBuilder interface. doLoad method is being used to cache Country Object using SOQL.

public class CountryCodeCache implements Cache.CacheBuilder{
public Object doLoad(String countryName) {
country__c country = (country__c)[SELECT Id, name, CountryCode__c FROM country__c WHERE name =: countryName];
return country;
}
}
public class CountryCode {
public static country__c getCountryCode(string countryName)
{
return (country__c) Cache.Org.get(CountryCodeCache.class, countryName);
}
}

CountryCode apex class fetch the Country record for given country Name from platform cache. If CountryName exists in org cache then it gets returned. If it doesn’t exist, then doLoad(String Var) method re-executed, and new values are cached and returned.

Execute below statement and observe the output,

country__c countCode=CountryCode.getCountryCode('INDIA'); 

After executing the statement first time, country data is cached by executing the CountryCodeCache.doLoad(string Var) method and then return the same.

After executing the statement second time, already cached data for country name ‘INDIA’ gets returned from cache without executing CountryCodeCache.doLoad(string Var) method.

If you remove the cached data and execute the statement, then CountryCodeCache.doLoad(string Var) will get re-executed and country details for country name ‘INDIA’ will be cached first and then return the data.

Reference:

--

--

No responses yet