Close Menu
SalesforceCodex
    Facebook X (Twitter) Instagram
    Trending
    • How to Leverage Model Context Protocol (MCP) to Enhance Salesforce AI
    • Top Mistakes Developers Make in Salesforce Apex Triggers
    • Introducing Agentforce3 to Salesforce Developers
    • The Ultimate Guide to Apex Order of Execution for Developers
    • How to Handle Bulkification in Apex with Real-World Use Cases
    • How to Confidently Manage Transactions in Salesforce Apex
    • Building a Dynamic Tree Grid in Lightning Web Component
    • 10 Salesforce Chrome Extensions to Boost Your Productivity
    Facebook X (Twitter) Instagram
    SalesforceCodex
    Subscribe
    Tuesday, July 29
    • Home
    • Salesforce Platform
      • Architecture
      • Apex
      • Lightning Web Components
      • Integration
      • Flows & Automation
      • Best Practices
      • Questions
      • News
      • Books Testimonial
    • Industries
      • Artificial Intelligence
    • Hire Me
    • Certification
      • How to Prepare for Salesforce Integration Architect Exam
      • Certification Coupons
    • Downloads
      • Salesforce Release Notes
      • Apex Coding Guidelines
    • About Us
      • Privacy Policy
    • Contact Us
    SalesforceCodex
    Home»Salesforce»Apex»Enhance Apex Performance with Platform Caching

    Enhance Apex Performance with Platform Caching

    Dhanik Lal SahniBy Dhanik Lal SahniJuly 26, 20221 Comment4 Mins Read
    Facebook Twitter Pinterest LinkedIn Tumblr Email
    Enhance Apex Performance with Platform Caching
    Share
    Facebook Twitter LinkedIn Pinterest Email

    Salesforce Applications frequently need few static data while performing transactions. These data are completely static or updated very less in the application. We should store these data in memory for easy retrieval while performing apex transactions. This post will explain how to enhance apex performance with platform caching and other approaches.

    Data that need Caching

    Based on the type of application we can cache different information. Below are a few pieces of information that we can cache. These can vary based on the domain we are working on.

    • Products information
    • Country Information
    • Authentication Token
    • User Information

    Options for Caching

    We can utilize the below Salesforce features to store frequent data

    1. Custom Setting
    2. Custom Metadata Types
    3. Static object
    4. Platform Cache

    Both Custom Setting and Custom Metadata types are internally caching data after the first data retrieval. These are mostly used to store application configuration information which is structured data. We can not cache runtime data which is created at runtime. Both are used for permanent cache. We are not sure what kind of data will be cached in memory while running the application so both can not be used for caching such kind of data.

    Static variable can also be used for cache items for a transaction but we have to declare lot of variable for specific type to store runtime data. Cached data will be used in only specific transaction and can not be used by other users.

    Platform Cache can be used to store any type of data at runtime and it can be used for specific session or by all users. This will be perfect to store data for our use cases.

    Let us explore platform cache and its usage.

    Platform Cache

    The platform cache is temporary cache to store session or org specific data in Salesforce Apex. These data can be stored/retrieved for one user or for multiple users.

    Types of Platform Cache

    • Session Cache : This will be used to store data which is used for specific session of user. Cached data will be used only for current session, if user logged out from application, data will be removed from Cache. We can store user information or user specific auth token using session cache.
    • Org Cache : This can be used to store data which can be used by all application user. Product information, country information can be cached in Org cache as it can be used by all users.

    Storing/Retrieving Data in Cache

    To store data in session or org cache we have to first create partition. Refer Platform Cache Partitions to create partition. Partitions allow us to distribute cache space based on our business use case. Let us assume we have created partition myPartition to store cache items.

    Session Caching

    // Add a value to the cache
    string currentClient= [Select id,Client__c from User where Id=:UserInfo.getUserId()].Client__c;
    Cache.Session.put('local.myPartition.client', currentClient);
    
    //Retrieving cached client
    string currentClient= (string)Cache.Session.get('client');

    Org Caching

    // Add a value to the cache
    List<Product2> prds = [Select id,Name,Price from Product2];
    Cache.Org.put('local.myPartition.products', prds);
    
    //Retrieving cached products
    List<Product2> prds= (List<Product2>)Cache.Org.get('products');

    Performance Improvement

    Let us take example, our application is showing product information on lightning component. We can store that information in cache as all user will fetch products to add into cart.

    //Retrieving cached products
    List<Product2> prds=(List<Product2>)Cache.Org.get('products');
    if(prds.isEmpty())
    {
        // Add a value to the cache
        prds = [Select id,Name,Price,Price,Quantity,Description from Product2];
        Cache.Org.put('local.myPartition.products', prds);
    }

    Above code will try to retrieve product information from Org Cache and If not found in cache then it will fetch information from database and store into cache.

    Below tables are showing loading time for 49,680 products with and without using platform cache.

    Without platform Cache

    Page LoadTime required to load data
    (milliseconds)
    1st time809 ms
    2nd time798 ms
    3rd time784 ms

    Using plateform Cache

    Page LoadTime required to load data
    (milliseconds)
    1st time804 ms
    2nd time2 ms
    3rd time1 ms

    We can see the difference between using Platform Cache in application development. It will load spontaneously using the platform cache after the first load.

    Best Practise for using platform Cache

    1. Always put code to fetch data when no data exist in the cache.
    2. Try to put a list instead of multiple individual item in the cache
    3. Clear cache when cached item updated/removed
    4. The size of individual cached items is limited to 100 KB so put item based on this limitation

    References:

    Platform Cache

    Related Posts:

    Apex Trigger Code Optimization

    Optimize Code by Disabling Debug Mode

    Optimizing Salesforce Apex Code

    Optimizing Loop in Apex Code

    apex code best practice code optimization custom data type custom metadata types custom setting optimize apex optimize apex code optimize code platform cache salesforce salesforce apex soql optimization
    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
    Previous ArticleDynamic Code Execution using Callable Interface
    Next Article Build Scalable Solutions with Salesforce
    Dhanik Lal Sahni
    • Website
    • Facebook
    • X (Twitter)

    With over 18 years of experience in web-based application development, I specialize in Salesforce technology and its ecosystem. My journey has equipped me with expertise in a diverse range of technologies including .NET, .NET Core, MS Dynamics CRM, Azure, Oracle, and SQL Server. I am dedicated to staying at the forefront of technological advancements and continuously researching new developments in the Salesforce realm. My focus remains on leveraging technology to create innovative solutions that drive business success.

    Related Posts

    By Dhanik Lal Sahni6 Mins Read

    How to Leverage Model Context Protocol (MCP) to Enhance Salesforce AI

    July 28, 2025
    By Dhanik Lal Sahni7 Mins Read

    Top Mistakes Developers Make in Salesforce Apex Triggers

    July 25, 2025
    By Dhanik Lal Sahni14 Mins Read

    The Ultimate Guide to Apex Order of Execution for Developers

    July 20, 2025
    View 1 Comment

    1 Comment

    1. Pingback: Optimizing Salesforce Apex Code | SalesforceCodex

    Leave A Reply Cancel Reply

    Ranked #1 Salesforce Developer Blog by SalesforceBen.com
    SFBenTopDeveloper
    Ranked #4 Salesforce Developer Blog by ApexHours.com
    ApexHoursTopDevelopers
    Categories
    Archives
    Tags
    apex (116) apex best practices (5) apex code best practice (10) apex code optimization (6) Apex logging (4) apex rest (11) apex trigger best practices (6) architecture (22) Asynchronous apex (9) AWS (5) batch apex (10) best code practice (4) code optimization (9) custom metadata types (5) design principle (9) flow (16) google (6) google api (4) integration (19) integration architecture (6) lighting (8) lightning (66) lightning-combobox (5) lightning-datatable (10) lightning component (32) Lightning web component (64) lwc (53) named credential (8) optimize apex (5) optimize apex code (6) optimize apex trigger (5) Permission set (4) Queueable (9) queueable apex (4) rest api (23) salesforce (149) salesforce apex (52) salesforce api (4) salesforce api integration (5) Salesforce Interview Question (5) salesforce news (5) salesforce question (5) solid (6) tooling api (5) Winter 20 (8)

    Get our newsletter

    Want the latest from our blog straight to your inbox? Chucks us your detail and get mail when new post is published.
    * indicates required

    MailChimp

    Facebook X (Twitter) Instagram Pinterest YouTube Tumblr LinkedIn Reddit Telegram
    © 2025 SalesforceCodex.com. Designed by Vagmine Cloud Solution.

    Type above and press Enter to search. Press Esc to cancel.

    Ad Blocker Enabled!
    Ad Blocker Enabled!
    Our website is made possible by displaying online advertisements to our visitors. Please support us by disabling your Ad Blocker.