Platform Cache In Salesforce

What is Cache?
Cache is a temporary data storing technique. We use Cache to store static data, that is being used frequently in our application for faster performance and better reliability.

What is Platform Cache?
Platform Cache is a memory layer that stores Salesforce session and org data for later access. When we use Platform Cache, the application can run faster because they store reusable data in memory. Application can quickly access this data; they don’t need to duplicate calculations and requests to the database on subsequent transactions. The Platform Cache is like the RAM for the cloud application.

There are two types of Platform Cache:

Session Cache: It stores data for individual user sessions and lives alongside a user session. The maximum life of a session is 8 hours. Session cache expires when its specified time-to-live is reached or when the session expires after eight hours, whichever comes first.

Org Cache: It stores data that any user in an org reuses. Unlike session cache, org cache is accessible across sessions, requests, and org users and profiles. Org cache expires when its specified time-to-live is reached.

When can we use Platform Cache?
We can use Platform Cache, when we want to store temporary data to use in code, but do not want to save it in database. Using cached data improves the performance of the application and is faster than performing SOQL queries repetitively, making multiple API calls, or computing complex calculations.

Platform Cache Considerations:

  • Cache isn’t persisted. There’s no guarantee against data loss.
  • Some or all cache is invalidated when you modify an Apex class in your org.
  • Data in the cache isn’t encrypted.
  • Org cache supports concurrent reads and writes across multiple simultaneous Apex transactions.
  • Session cache doesn’t support asynchronous Apex. Like we can’t use future methods or batch Apex with session cache.
  • The session cache can store values up to eight hours and the org cache can store values up to 48 hours.

Platform Cache Limits:

Cache Allocations by Edition:

  • Developer Edition (0 MB by Default, but can get 10 MB as a trial).
  • Enterprise Edition (10 MB by default)
  • Unlimited Edition (30 MB by default)
  • Performance Edition (30 MB by default)

Session Cache Limits:

  • Maximum size of a single cached item for put() methods (100 KB)
  • Maximum local cache size for a partition, per-request (500 KB)
  • Minimum developer-assigned time-to-live 300 seconds (5 minutes)
  • Maximum developer-assigned time-to-live 28,800 seconds (8 hours)
  • Maximum session cache time-to-live 28,800 seconds (8 hours)

Org Cache Limits:

  • Maximum size of a single cached item for put() methods (100 KB)
  • Maximum local cache size for a partition, per-request (1,000 KB)
  • Minimum developer-assigned time-to-live 300 seconds (5 minutes)
  • Maximum developer-assigned time-to-live 172,800 seconds (48 hours)
  • Default org cache time-to-live 86,400 seconds (24 hours)

Create Partition of Platform Cache:
Go to Setup | Search “Platform Cache” in Quick Find Box | Click Platform Cache

In developer edition, it is 0 MB space default. But we can get 10 MB on click of “Request Trial Capacity” button.

Now Click on “New Platform Cache Partition” to create 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 org cache is for data that any users in an org can access.


Note: We cannot delete default Partition. If you want to delete partition, you have to uncheck the default partition option.

Put and retrieve data using Platform cache:
To call Partition in apex code we use namespace.partitionName. local as namespace can be used in both scenario if you have namespace enabled or not enable in your org. In below example I’m using “myPartition” partition.

Store and Retrieve Values from the Session Cache:

Session Cache in Apex Class:

//Add a value to the cache
Integer cartValue = 22;
Cache.Session.put('local.myPartition.CartValue', cartValue);
if (Cache.Session.contains('local.myPartition.CartValue')) {
    Integer cachedCartValue = (Integer)Cache.Session.get('local.myPartition.CartValue');
}

To refer to the default partition and the namespace of the invoking class, we can omit the namespace.partition prefix and specify the key name.

//Use of default partition without namespace and partition
Cache.Session.put('CartValue', 22);
if (Cache.Session.contains('CartValue')) {
    Integer cachedCartValue = (DateTime)Cache.Session.get('CartValue');
}

Session Cache in Visualforce Page:

<apex:outputText value="{!$Cache.Session.local.myPartition.CartValue}"/>

Store and Retrieve Values from the Org Cache:

Org Cache in Apex Class:

//Add a value to the cache
Integer cartValue = 22;
Cache.Org.put('local.myPartition.CartValue', cartValue);
if (Cache.Org.contains('local.myPartition.CartValue')) {
    Integer cachedCartValue = (Integer)Cache.Org.get('local.myPartition.CartValue');
}
//Use of default partition without namespace and partition
Cache.Org.put('CartValue', 22);
if (Cache.Org.contains('CartValue')) {
    Integer cachedCartValue = (DateTime)Cache.Org.get('CartValue');
}

Org Cache in Visualforce Page:

<apex:outputText value="{!$Cache.Org.local.myPartition.CartValue}"/>

Run Case or Lead Assignment Rule From Apex

Run Lead Assignment From Apex Sample Code:

//Get your Lead records
List<Lead> leadList = [SELECT Id From Lead LIMIT 10];

if(!leadList.isEmpty()) {
    //Run Lead assignment rule from apex
    Database.DMLOptions dmlOption = new Database.DMLOptions();
    dmlOption.assignmentRuleHeader.useDefaultRule = true;
    Database.update(leadList, dmlOption);
}

Run Case Assignment From Apex Sample Code:

//Get your Case records
List<Case> caseList = [SELECT Id From Case LIMIT 10];

if(!caseList.isEmpty()) {
    //Run Case assignment rule from apex
    Database.DMLOptions dmlOption = new Database.DMLOptions();
    dmlOption.assignmentRuleHeader.useDefaultRule = true;
    Database.update(caseList, dmlOption);
}

Salesforce Update Records With Inactive Owners

In some scenarios, we need to update records which Owners are inactive. For example, we are migrating data to Salesforce using data loader, some record owners are inactive. For those inactive owner records, we will get “A record owner cannot be Inactive” error. We have to change ownership of the record to an active owner.

To update records with inactive Owners, we have to enable

Enable “Set Audit Fields upon Record Creation” and “Update Records with Inactive Owners” User Permissions.

Go to Setup | Enter User Interface in the Quick Find box | Select User Interface | Enable “Set Audit Fields upon Record Creation” and “Update Records with Inactive Owners” User Permissions.

After enabled the above setup, enable Update Records with Inactive Owners of the user Profile or in a Permission Set. You can set audit fields only in API-enabled editions of Salesforce.

Create Chatter Post With Attachment Using Apex

Sample Code:

//Upload File
ContentVersion cv = new ContentVersion();
cv.Title = 'Chatter Post Document';//File title
cv.PathOnClient = 'chattertestdoc.pdf';//File name
cv.VersionData = Blob.valueOf('Test Content');//File body (Add content or body of uploaded file)
cv.Description = 'Chatter Post Document';//File description
insert cv;

//Create Chatter Post
FeedItem fi = new FeedItem();
fi.Body = 'Chatter post from apex with attachment';
fi.ParentId = '0010I00002AbcMm'; //Record Id
insert fi;

//Associate attachment to the post
FeedAttachment fa = new FeedAttachment();
fa.FeedEntityId = fi.Id;//Chatter Post Id
fa.RecordId = cv.Id;//Document Id
fa.Type = 'CONTENT'; 
insert fa;