You are using an older browser that might negatively affect how this site is displayed. Please update to a modern browser to have a better experience. Sorry for the inconvenience!

Effective Callouts Using Platform Cache


By: Radha

In Winter ’16 Salesforce released a feature named Platform Cache, a memory layer that provides faster performance and better reliability when caching Salesforce user’s session and org data. We can specify what to cache and for how long (Time to Live) without using custom objects and settings or overloading the Visualforce view state. By distributing cache space across various applications or operations, Platform Cache improves performance such that cache capacity cannot be stolen by other applications or processes.

Platform Cache 

Platform Cache is a memory layer that stores Salesforce session and org data for future use. Applications run faster, when we use Platform Cache because they store reusable memory. They can access this data quickly and they don’t need to duplicate calculations and requests to the database on subsequent transactions.

Types of Platform Cache: 

1.Org Cache 

Org cache can store Org-wide data such that anyone in the Org can access it. Org cache is accessible across sessions, requests, and org users and profiles. For org cache, data can live up to 48 hours in the cache. By default, the time-to-live(TTL) value for org cache is 24 hours.

2.Session Cache 

Session cache stores data that are tied to a user’s session such that other users in the Org cannot access this data. The maximum life of a session cache is 8 hours.

Creating Platform Cache Partition: 

By default, our Developer org has 0 MB cache capacity. We can request a trial cache of 10 MB. To request a trial, click Your Name [Symbol] Setup [Symbol] Develop [Symbol] Platform Cache[Symbol] New Platform Cache Partition.

Requesting Trial Capacity for Platform Cache: 

Provide a suitable Name, and Label for the partition. 

Specifying available Cache capacity:  

Check default partition checkbox to use your cache name directly in Apex codes, without the namespace prefix.

If the trial cache capacity is available, then specify the capacity for both session cache and org cache.

Note: Sum of both the session and org cache capacity should be equal to the total available cache capacity. (Minimum Capacity is 5 MB)

Store/Retrieve Data in Org Cache: 

To store values in an Org Cache use put(<CacheNameKey>,<Value>); and to retrieve values from an Org Cache we can use get(<CacheNameKey>);

  1. // Get partition
  1. Cache.OrgPartition orgPart = Cache.Org.getPartition(‘local.CurrencyCache’);
  1. // Add cache value to the partition
  1. orgPart.put(‘DollarToEuroRate’, ’0.91′);
  1. // Retrieve cache value from the partition
  1. String cachedData = (String)orgPart.get(‘DollarToEuroRate’);
  1.  System.assertEquals(‘0.91’, cachedData);

Store/Retrieve Data in Session Cache: 

We can use the Cache.Session and Cache.SessionPartition classes to manage values in the session cache. For managing values in any partition, use the methods in the Cache.Session class. If managing cache values are in one partition, use the Cache.SessionPartition methods instead.

Using Cache.Session: 

To store a value in the session cache, call the Cache.Session.put() method and provide a key and value. The key name is in the format namespace.partition.key. To retrieve, use the key in the cache.Session.get() method.

  1. String username = ‘DemoUser’;
  1. // Add a value to the cache
  1. Cache.Session.put(‘local.MyCache.usernameCache’, username);
  1. if (Cache.Session.contains(‘local.MyCache.usernameCache’)) {
  1. // Retrieve value from the cache
  1.     String cachedData = (String)Cache.Session.get(‘local.MyCache.usernameCache’);
  1.     System.assertEquals(username, cachedData);
  1. }

Using Cache.SessionPartition: 

To store a value in the session cache, call the Cache.Session.put() method and provide a key and value. The key name is in the format namespace.partition.key.

  1. // Get partition
  1. Cache.SessionPartition sessionPart = Cache.Session.getPartition(‘local.CurrencyCache’);
  1. // Add cache value to the partition
  1. sessionPart.put(‘FavoriteCurrency’, ’JPY’);
  1. // Retrieve cache value from the partition
  1. String cachedRate = (String)sessionPart.get(‘FavoriteCurrency’);

Storing Callout responses in a Platform Cache: 

Now we implement this Platform Cache in a useful scenario – storing weather data temporarily in a platform cache. When a user request for weather details for a city for the first time from Salesforce, a callout is sent to a web service to fetch the weather details and the data is stored in platform cache with a specific time-to-live, say 6 hours. When the user requests again for the same city within that 6 hours, data is fetched from Platform Cache rather than sending callouts to web service.

Apex Visual Page (FetchWeather_VF): 

  1. <apex:page controller=”FetchWeatherController”>
  1.     <apex:sectionHeader title=”Fetch Weather Report” subtitle=”Select City”/>
  1.     <apex:form>
  1.         <apex:selectList size=”1″ value=”{! selectedCity}”>
  1.             <apex:selectOptions value=”{! allUScities}”></apex:selectOptions>
  1.         </apex:selectList>
  1.        <apex:commandButton action=”{! retrieveWeatherDetails}” value=”Get Weather”/>
  1.        <apex:outputPanel rendered=”{! IF(combinedResultsList.size != 0, TRUE, FALSE)}”>
  1.             <apex:pageBlock tabStyle=”Contact”>
  1.                 <apex:pageBlockSection title=”{! selectedCity}’s Current weather”>
  1.       <h3>Temperature </h3><apex:outputText value=”{! combinedResultsList[0]} K” />
  1.       <h3>Pressure </h3><apex:outputText value=”{! combinedResultsList[1]}” />
  1.       <h3>Humidity </h3><apex:outputText value=”{! combinedResultsList[2]} %” />
  1.       <h3>Min Temperature </h3><apex:outputText value=”{! combinedResultsList[3]} K” />
  1.       <h3>Max Temperature </h3><apex:outputText value=”{! combinedResultsList[4]} K” />
  1.                 </apex:pageBlockSection>
  1.             </apex:pageBlock>
  1.         </apex:outputPanel>
  1.     </apex:form>
  1. </apex:page>

Apex Controller Class (FetchWeatherController): 

  1. public class FetchWeatherController
  1. {
  1.     public String[] combinedResultsList { get; set; }
  1.     public String selectedCity { get; set; }
  1.     private static String cachename = ’WeatherCache’;
  1.     private static String apiKey = ”;
  1.     private static String endPointURL= ”;
  1.     public Cache.SessionPartition thisSession;
  1.     private Cache.SessionPartition getPartition()
  1.     {
  1.         if(thisSession == null)
  1.             thisSession = Cache.Session.getPartition(cacheName);
  1.         return thisSession;
  1.     }
  1.     public SelectOption[] allUScities { get
  1.     {
  1.         allUScities = new List<SelectOption>();
  1.         for(US_Cities__c option : US_Cities__c.getAll().values())
  1.             allUScities.add(new SelectOption(option.City_API__c,option.Name));
  1.         return allUScities;
  1.     } private set;}
  1.     public void initializeAPI()
  1.     {
  1.         apiKey = ’XxxxxxxxxxxxxxxxxxxxxxxxxxxxxxX’;
  1.         endPointURL = ’http://api.openweathermap.org/data/2.5/weather’;
  1.         combinedResultsList = new List<String>();
  1.         thisSession = getPartition();
  1.     }
  1.     public FetchWeatherController()
  1.     {
  1.         combinedResultsList = new List<String>();
  1.         thisSession = getPartition();
  1.     }
  1.     public void retrieveWeatherDetails()
  1.     {
  1.         initializeAPI();
  1.         endPointURL += ’?q=’+selectedCity;
  1.         endPointURL += ’&APPID=’ + apiKey;
  1.         if(thisSession.contains(selectedCity))
  1.         {
  1.             combinedResultsList.addAll((List<String>)thisSession.get(selectedCity));
  1.             return;
  1.         }
  1.         else
  1.         {
  1.             // Instantiate a new http object
  1.             Http h = new Http();
  1.     // Instantiate a new HTTP request, specify the method (GET) as well as the endpoint
  1.             HttpRequest req = new HttpRequest();
  1.             req.setEndpoint(endPointURL);
  1.             req.setMethod(‘GET’);
  1.             // Send the request, and return a response
  1.             HttpResponse res = h.send(req);
  1.             System.debug(”+res.getBody()+’ Code: ’+res.getStatusCode());
  1.             if (res.getStatusCode() == 200)
  1.             {
  1.                 Map<String, Object> resultsMap = (Map<String, Object>) JSON.deserializeUntyped(res.getBody());
  1.                 Map<String, Object> mainResultsMap = (Map<String, Object>)(resultsMap.get(‘main’));
  1.                 combinedResultsList.add(String.valueOf(mainResultsMap.get(‘temp’)));
  1.                combinedResultsList.add(String.valueOf(mainResultsMap.get(‘pressure’)));
  1.                combinedResultsList.add(String.valueOf(mainResultsMap.get(‘humidity’)));
  1.                combinedResultsList.add(String.valueOf(mainResultsMap.get(‘temp_min’)));
  1.                combinedResultsList.add(String.valueOf(mainResultsMap.get(‘temp_max’)));
  1.                 thisSession.put(selectedCity,combinedResultsList, 21600);
  1.             }
  1.             if(combinedResultsList.isEmpty())
  1.             {
  1.                 combinedResultsList = new List<String>{‘Data Not available’,’Data Not available’,’Data Not available’,’Data Not available’,’Data Not available’};
  1.             }
  1.         }
  1.     }
  1. }

Notes: 

Using Platform Cache, we can replace custom settings or custom metadata, and, we can set Time-to-Live (TTL) for each data we store, which is an added advantage.

In the above scenario, we have minimized usage of web callouts, by retrieving temporary data from platform cache rather than callouts.

Similarly, we can store sObjects, SOQL queries, or any other data types in Platform Cache.

We can diagnose the performance of using platform cache in the following option:

Click Your Name [Symbol] Setup [Symbol] Develop [Symbol] Platform Cache [Symbol] <Your Platform Cache Name> [Symbol] Diagnostics

Diagnosing Cache usage: 

Limits of Platform Cache: 

Cache Allocations by Edition: 

Platform Cache is available for Enterprise Edition orgs and above. These are the following editions that come with some default cache space. We can increase number of cache for greater performance enhancements.

  • Enterprise Edition (10 MB by default)
  • Unlimited Edition (30 MB by default)
  • Performance Edition (30 MB by default)
  • Developer Edition (request Trial capacity for 10 MB, 0 MB by default)
LIMITS SESSION CACHE ORG CACHE
Minimum partition size 5 MB 5 MB
Maximum size of a single cached item 100 KB 100 KB
Maximum local cache size for a partition, per-request 500 KB 1000 KB
Minimum time-to-live 300 seconds (5 minutes) 300 seconds (5 minutes)
Maximum time-to-live 28,800 seconds (8 hours) 172,800 seconds (48 hours)
Default cache time-to-live 28,800 seconds (8 hours) 86,400 seconds (24 hours)

Conclusion: 

Platform Cache can increase performance, replace Custom Settings and Custom Meta Data Types by storing data temporarily without any need of extra storage, and eliminates the need to use web callouts (as per our scenario).

References: 

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_platform_cache_limits.htm

https://trailhead.salesforce.com/modules/platform_cache