Salesforce Platform Cache & Partitions using Apex

Platform Cache

Platform Cache is a memory layer that stores Salesforce session and org data for later access which improves the performance of your applications. Platform Cache improves performance by distributing cache space so that some applications or operations don’t steal capacity from others.
Salesforce allow you to create partitions. Partitions allow you to distribute cache space in the way that works best for your applications. Caching data to designated partitions ensures that it’s not overwritten by other applications or less-critical data.

When you use Platform Cache, your applications will run faster because they store reusable data in memory. Applications can quickly access this data; they don’t need to duplicate calculations and issue requests to the database on subsequent transactions. In short, think of Platform Cache as RAM for your cloud application.

 

Let’s enable the Platform Cache and do some hands-on !!

Turn On Platform Cache

1. Go to Platform Cache.

Platform Cache.png
2. Request Trial Capacity.
Trail Capacity
3. Create a New Platform Cache Partition.
Screen Shot 2018-10-09 at 2.47.27 PM.png
3.  To use Platform Cache, first set up is to create at least one partition. Once you’ve set up partitions, you can add, access, and remove data from them using the Platform Cache Apex API.
Screen Shot 2018-10-15 at 3.20.28 PM
We have turned on the Platform Cache and created one partition called “DefaultCache”.

Org & Session Cache

There are two types of cache:
  • 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, 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.

  • 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.

Scenario:  A Developer wants to store the list of Contacts for given Account in Cache. We can implement this scenario using Org & Session Cache using Default Partition or a specific Partition.
Here are the implementation scenarios for both type of cache:

1) Implement Org Cache using Apex

The Org cache uses two classes Cache.Org and Cache.OrgPartition to the access values stored in cache.
Using Default Partition:
In the below code, the default partition named “DefaultCache” will be used to store the contacts in cache. We can make default cache by checking the box called “Default Partition” while creating cache as given in the above steps.

Screen Shot 2018-10-15 at 4.13.14 PM

If there a Apex Class:
public class ContactCacheDefaultPartion {
    
    public static void putContacts(String accId, Contact[] contacts) {
        Cache.org.put(accId,contacts);
    }
    
    public static Contact[] getContacts(String accId) {
        List conList = (List)Cache.Org.Get(String.valueOf(accId));
        return conList;
    }
    
}
Every time you call the put operation the value in the cache will be overridden if there a change to the values for a given key.
The parameter ‘true’ when specified will prevent overriding cached value when calling from another Namespace/package.
The following example also sets the lifetime of the cached value (3600 seconds or 1 hour) and makes the value available to any namespace.
Cache.Org.put(accId, contacts, 3600, Cache.Visibility.ALL, true);

With Specific Partition:
We can create a new partition called “ContactCache” without checking the box Default Cache. This will store the contacts in allocated partition given by partition name ‘ContactCache”. Minimum Partition size can be 5 MB.
Apex Class:
public class ContactCachePartion {

    public static void putContacts(String accId, Contact[] contacts) {
        Cache.OrgPartition orgPart = 
                     Cache.Org.getPartition('local.ContactCache');
        orgPart.put(accId, contacts);
    }
    
    public static Contact[] getContacts(String accId) {
        Cache.OrgPartition orgPart = 
                      Cache.Org.getPartition('local.ContactCache');
        
        List conList = (List)orgPart.get(String.valueOf(accId));
        return conList;
    }
}

Run the script in Developer Console:

In the below code, we are calling the methods defined in the apex class. It stores the contacts in cache and displaying the data in debug logs. The main feature of Cache is to get the same data which is already stored in memory even running the script multiple times.

//e.g. Using Cache Default Partition
List accList = [Select Id,(Select Id,Name From Contacts) 
From Account Limit 2]; 

ContactCacheDefaultPartion.putContacts(accList[0].Id,accList[0].Contacts); 
ContactCacheDefaultPartion.putContacts(accList[1].Id,accList[1].Contacts); 
System.debug('1st Account: '+ ContactCacheDefaultPartion.getContacts(accList[0].Id)); 
System.debug('2nd Account: '+ ContactCacheDefaultPartion.getContacts(accList[1].Id)); 


//e.g. Using Specific Cache Partition
List accList = [Select Id,(Select Id,Name From Contacts) 
                       From Account Limit 2];
ContactCachePartion.putContacts(accList[0].Id,accList[0].Contacts);
ContactCachePartion.putContacts(accList[1].Id,accList[1].Contacts);

System.debug('1st Account: '+ ContactCachePartion.getContacts(accList[0].Id));
System.debug('2nd Account: '+ ContactCachePartion.getContacts(accList[1].Id));


Output

Screen Shot 2018-10-16 at 9.46.31 PM.png

2) Implement Session Cache using Apex

The session cache is similar to the org cache, except the class names are different. A developer can use the Cache.Session and Cache.SessionPartition classes to access values stored in the session cache.

Please re-use the Org cache code above implemented with the following changes to implement Session cache:

Using Default Partition:
Cache.Session.put(accId, contacts, 3600, Cache.Visibility.ALL, true);
With Specific Partition:
// Get partition
Cache.SessionPartition sessionPart = 
          Cache.Session.getPartition('local.ContactCache');

// Add cache value to the partition
sessionPart.put(accId, contacts);
// Retrieve cache value from the partition
List conList = (List)sessionPart.Get(String.valueOf(accId));

 

Using Default Partition Vs. Using Specific Partition

The code with default partition automatically access the default cache. There can be only one default cache at a time. When using specific partition, we have to always mention the name of partition in apex code.

Reference:

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

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

Author:

Ajomon Joseph AJOMON JOSEPH
Senior Salesforce Architect
In Connect me on LinkedIn
twitter Follow me on Twitter @apexcoder
blogger Subscribe to my blog https://apexcoder.com
email Email me ajomon@apexcoder.com

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s