Introduction
In this blog post, I am going to explain “Platform Cache ” and how you are going to use. You may use many ways to improve your pages to run quickly by using custom settings and view states reduce technicians and so on. But with new platform cache, you can store Salesforce session and org data for later access and applications can run faster because they store reusable data in memory.
How does Platform Cache work?
Platform Cache uses local cache and a least recently used (LRU) algorithm to improve performance.The local cache is the application server’s in-memory container that the client interacts with during a request. Cache operations don’t interact with the caching layer directly but instead interact with the local cache.For session cache, all cached items are loaded into local cache upon the first request. All subsequent interactions use the local cache. Similarly, an org cache gets operation retrieves a value from the caching layer and stores it in the local cache. Subsequent requests for this value are retrieved from the local cache. Platform Cache uses an LRU algorithm to evict keys from the cache. When cache limits are reached, keys are evicted until the cache is reduced to 100-percent capacity. If session cache is used, the system removes cache evenly from all existing session cache instances. The local cache also uses an LRU algorithm. When the maximum local cache size for a partition is reached, the least recently used items are evicted from the local cache
Platform cache supports two types of caches
- Session cache—Stores data for individual user sessions. For example, in an app that finds customers within specified territories, the calculations that run while users browse different locations on a map are reused.
Session cache lives alongside a user session. The maximum life of a session is eight hours. Session cache expires when its specified time-to-live (ttlsecs value) is reached or when the session expires after eight hours, whichever comes first.
- Org cache—Stores data that any user in an org reuses. For example, the contents of navigation bars that dynamically display menu items based on user profile are reused.
Unlike session cache, the org cache is accessible across sessions, requests, and org users and profiles. Org cache expires when its specified time-to-live (ttlsecs value) is reached.
Distribute the cache with Partitions
Partitions allow you to improve the performance by distributing cache space in the way that works best for your applications. after setting up the partitions you can add, access, and remove data from them using the Platform Cache Apex API.In order to use Platform Cache, create at least one partition. Each partition has one session cache and one org cache segment and you can allocate separate capacity to each segment. Session cache can be used to store data for individual user sessions, and the org cache is for data that any users in an org can access. You can distribute your org’s cache space across any number of partitions. Session and org cache allocations can be zero, or five or greater, and they must be whole numbers. The sum of all partition allocations, including the default partition, equals the Platform Cache total allocation. The total allocated capacity of all cache segments must be less than or equal to the org’s overall capacity.
After you set up partitions, you can use Apex code to perform cache operations on a partition. For example, use the Cache.SessionPartition and Cache.OrgPartition classes to put, retrieve, or remove values from a specific partition’s cache. Use Cache.Session and Cache.Org to get a partition or perform cache operations by using a fully qualified key.
To access the Partition tool in Setup, enter Platform Cache in the Quick Find box, then select Platform Cache. Click new Platform Cache Partition . each Partition should have a session Cache and org Cache. enter Partition name and label as “partition”
Handling Session cache
Use the Cache.Session and Cache.SessionPartition classes to manage values in the session cache. To manage values in any partition, use the methods in the Cache.Session class. If you’re managing cache values in one partition, use the Cache.SessionPartition methods instead.
// Add a value to the cache . local is the default name space cache Cache.Session.put('local.partition.key', '1234567'); if (Cache.Session.contains('local.partition.key')) { String key = (String)Cache.Session.get('local.partition.key'); } // Dafualt cache paritions Cache.Session.put('key', '123456'); if (Cache.Session.contains('key')) { String key = (String)Cache.Session.get('key'); } // Get a cached value String val = (String)Cache.Session.get('local.partition.key');
If you’re managing cache values in one partition, use the Cache.SessionPartition methods instead. After the partition object is obtained, the process of adding and retrieving cache values is similar to using the Cache.Session methods. The Cache.SessionPartition methods are easier to use because you specify only the key name without the namespace and partition prefix.
// Get partition Cache.SessionPartition sessionPart = Cache.Session.getPartition('local.Partition'); // Retrieve cache value from the partition if (sessionPart.contains('key')) { String cachedTitle = (String)sessionPart.get('key'); } // Add cache value to the partition sessionPart.put('value', 'welcome');
Handling Org Cache
Use the Cache.Org and Cache.OrgPartition classes to manage values in the org cache. To manage values in any partition, use the methods in the Cache.Org class. If you’re managing cache values in one partition, use the Cache.OrgPartitionmethods instead.
// Add a value to the cache Cache.Org.put('local.partition.key', 'Hello '); if (Cache.Org.contains('local.partition.key')) { String key = (String)Cache.Org.get('local.partition.key'); }
If you’re managing cache values in one partition, use the Cache.OrgPartition methods instead. After the partition object is obtained, the process of adding and retrieving cache values is similar to using the Cache.Org methods. The Cache.OrgPartition methods are easier to use because you specify only the key name without the namespace and partition prefix.
// Get partition Cache.OrgPartition orgPart = Cache.Org.getPartition('local.partition'); // Retrieve cache value from the partition if (orgPart.contains('key')) { String key = (String)orgPart.get('key'); } // Add cache value to the partition orgPart.put('value','welcome');
Diagnose Platform cache
Cache diagnoses will provide the information about how much cache is used.The Diagnostics page provides valuable information, including the capacity usage, keys, and serialized and compressed sizes of the cached items. The session cache and org cache have separate diagnostics pages. The session cache diagnostics are per session, and they don’t provide insight across all active sessions.
Here is the simple code that used to store and retrieve the conversion exchange rates from the web services. Simple it checks the key is present in the Cache, it is going to retrieve the values from the platform chance otherwise it will store the values in the cache. so that you no need to make Webservice call even time to get the real time conversion rates
public class PlatformCacheController { Cache.OrgPartition orgPart ; public PlatformCacheController(){ orgPart = Cache.Org.getPartition('local.partition'); //http://apilayer.net/api/live?access_key=456fab5d3bee967f81169416e234387e¤cies=EUR,GBP,CAD,PLN&source=USD&format=1 } public String fetchData(String fromCurrency , String toCurrency ){ String keytoStoreorRet =fromCurrency+toCurrency; If(checkKeyInCache(keytoStoreorRet)){ return (String) orgPart.get(keytoStoreorRet); }else{ HttpRequest req = new HttpRequest(); req.setEndpoint('http://apilayer.net/api/live?access_key=456fab5d3bee967f81169416e234387e¤cies='+toCurrency+'&source='+fromCurrency+'&format=1'); req.setMethod('GET') ; Http h = new Http(); HttpResponse resp = h.send(req) ; orgPart.put(keytoStoreorRet , resp.getBodyAsBlob()); return resp.getBody() ; } } public void updateKeyinCache(String key ,String values){ if(!checkKeyInCache(key)){ orgPart.put(key, values); } } public boolean checkKeyInCache(String key){ if (orgPart.contains(key)) { return true ; }else{ return false ; } } }
Considerations of platform cache and best practices
- Cache isn’t persisted. and there is no guaranty on data lost.Make sure you should handle the data loss properly. You can use CacheBuilder to handle the data losses.
- Decided what type of data access you need like Concurrent vs serial retrieve and update. Org cache supports concurrent reads and writes across multiple simultaneous Apex transactions
- think how to handle cache misses like Using CacheBuiler or you can use your own retrieval or update cache handling
- Not all the data need to be stored in the cache. Including more data in the cache may impact performance. In case if you need to store the bulk data, split and store into multiple keys
- Use the cache to store static data or data that doesn’t change often rather than changing the data very often