Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Platform cache

Boost your App with Platform Cache

  • Be the first to comment

Platform cache

  1. 1. Salesforce Apex Hours Farmington Hill Salesforce Developer Group Boost your App with Platform Cache #SalesforceApexHours #SalesforceApexHours Speaker Date Venue/Link Daniel Stange Saturday, January 04, 2020 10:00 AM EST ( 8:30 PM IST )
  2. 2. Who I am Amit Chaudhary (Salesforce MVP) • Active on Salesforce Developer Community • Blogging at • Co-Organizer of – FarmingtonHillsSFDCDug • Founder of • Follow us @Amit_SFDC or @ApexHours
  3. 3. Upcoming Session 1. OAuth Concepts on JAN 11, 2020 10:00 AM EST (8:30 PM IST) with Susannah Kate St-Germain. 2. Become an Order of Execution Hero on JAN 18, 2020 10:00 AM EST (8:30 PM IST) with Daniel Stange and Marc B. Kirsch 3. Salesforce integration Pattern & Best Practices on FEB 1, 2019 10:00 AM EST (8:30 PM IST) with Jitendra Zaa 4. Microservices in Salesforce on FEB 22, 2020 10:00 AM EST (8:30 PM IST) with Jigar Shah All Upcoming session :
  4. 4. Our Speaker Daniel Stange Technical Architect DIA die.interaktiven 20x certified System & Application Architect Frankfurt User Group Leader @stangomat
  5. 5. Agenda • Platform Cache - But why? • Key Concepts • Getting Started with Platform Cache (Demo / Code!) • Platform Cache as a key/value storage • Platform Cache as a readthrough cache • When to Use (and when not to use) Platform Cache • Q & A
  6. 6. Key Takeaways • Boost your app‘s performance significantly • Understand which kind of data to put in the cache • Know the obstacles when you use to the platform cache and prepare for cache misses and unexpected results
  7. 7. Platform Cache? But why?
  8. 8. Impact for read access to data (EE Scratch Org on CS83 / EE Dev Sandbox on CS86) Avg. to fetch 10000 records as a Map through SOQL 182-370ms 1.8 to 5.7x Faster Access 65-97ms Avg. to fetch the same map from the Org cache
  9. 9. DB vs. Cache Retrieve / per Item Impact of bulkification (100 retrieved values) DB: Initial 367ms => 3,67ms per item access Cache: Initial 117ms => 1,17ms per item access DB: avg. 11,52ms Cache: avg. 3.67ms
  10. 10. Other Gains • Handle Limits better when accessing frequently used data • Speed up data access (2x to 3x faster than Database access) • Reduce SOQL calls (access is „free“) • Reduce memory footprint • Trade-Offs: • Heap size limit (when working with maps in variables) • Cache access time (slower than accessing variables) • Less control over SOQL calls (if implemented for cache misses)
  11. 11. Big News for ISVs
  12. 12. Key Concepts
  13. 13. Platform Cache • Simple & temporary Key-Value-Storage (Map<String, Object>) • Quite Easy to implement ANY cache strategy => but fairly easy to design a GOOD, sustainable strategy • By default VISIBLE and MUTABLE => but can be RESTRICTED and set to IMMUTABLE
  14. 14. Data to Cache • PREPARABLE - REUSABLE • Static: Not changing frequently • Frequently needed in operations • Expensive to get (or keep) (in terms of system limits) • e.g. Taxonomies, Schedules, Mappings, Conversion Rates, etc.
  15. 15. Cache Types ORG one cache for all users and contexts variable TTL SESSION scoped per user Session TTL = Session length TTL: Time to Live
  16. 16. ORG: 24 hrs DEFAULT TTL Time-to-Live (TTL) ORG: 5 min MINIMUM TTL SESSION: 5 min ORG: 48 hrs MAXIMUM TTL SESSION: 8 hrs
  17. 17. Cache Eviction Strategy 1 4 3 7 5 6 ORDER OF LAST ACCESS 2 CACHE CAPACITY LRU: Least Recently Used Eviction Strategy
  18. 18. Considerations How (and when) to build / maintain your cache • Explicit Caching • Button: “Rebuild the Cache now“ • Scheduled Apex: „Rebuild the Cache every night at 1 a.m.“ • Implicit Caching • Eagerly: „Upon a Cache Miss, cache all items again“ • Lazy: „Upon a Cache Miss, cache the missing item again“
  19. 19. Considerations Invalidation • Requires careful consideration • Platform data vs. off-platform data • Frequency of change • Ability to „listen“ to change events • Strategies: • Rebuild • Evict / Replace • Combinations
  20. 20. Digging Into the Platform Cache
  21. 21. Preparation Work • Enterprise Editions Sandboxs come with a 10 MB capacity • Request a trial capacity if you are using a Developer Org or Scratch Org • SFDX / Scratch Orgs: "features": ["PlatformCache"] • Trailhead: “Platform Cache Basics”
  22. 22. Place your screenshot here Cache .[Org/Session] .put( Namespace .PartitionName .Key, Object ); Store
  23. 23. Place your screenshot here Retrieve Cache .[Org/Session] .get( Namespace .PartitionName .Key );
  24. 24. Demo Sample Implementation and Benchmark Scripts at
  25. 25. Implementation Catch miss Load from source Check for key Store Key / Value Retrieve Value Return Value
  26. 26. CacheBuilder Interface Catch miss Load from source Check for key Store Key / Value Retrieve Value Return Value
  27. 27. Two Implementation Paths • READ-THROUGH IMPLEMENTATION using CACHEBUILDER interface • Data sits in sObjects • Access can be expressed in one SOQL query • CUSTOM IMPLEMENTATION • Any off-platform data • Cross-object data that can‘t be accessed through one specific SOQL query
  28. 28. Place your screenshot here Sample Sales District Everything with Country = DE and PostalCode LIKE ‘35%’ should be assigned and have Nils as an Owner. dstdia/PlatformCache
  29. 29. Place your screenshot here Creating an Account Postal Code starts with 35 and Country = DE Should end up in Central Sample District being assigned dstdia/PlatformCache
  30. 30. Place your screenshot here And there it is! dstdia/PlatformCache
  31. 31. dstdia/PlatformCache
  32. 32. dstdia/PlatformCache
  33. 33. Read-Through Cache
  34. 34. Custom Implementation • Design a way to POPULATE the cache • Design a way to manage changes in the cached data (INVALIDATE) • Design the request to the cache • Catch cache misses • Handle misses gracefully (load data, put into cache, return)
  35. 35. „Read Through" • Implement the standard Interface Cache.CacheBuilder • Implement the doLoad() method: • Design a Query to retrieve a record ... sd = (SalesDistrict__c) Cache.Org.get( Cache_SalesDistrict.class, salesDistrictKey); ...
  36. 36. dstdia/PlatformCache
  37. 37. Considerations
  38. 38. Nice! Easy! Fast! Where‘s the catch? • It‘s still a cache, not a database. • It is short lived and per default visible and mutable • Understand the key concepts of the platform cache (in particular TTL, LRU) • Expect the cache to fail you. • What’s your strategy to invalidate cache?
  39. 39. Build your Strategies • The Cache will go away... Schedule a Cache Rebuild < TTL • Cached items will be pushed out… Use the CacheBuilder interface • Cached data goes stale… Rebuild From Triggers • Cached items must adhere to the 100kB size limits Reduce memory footprint by using Apex Classes instead of sObject or reduce the number of queried fields
  40. 40. Apex Classes vs. sObjects List<CachedProduct> cachedProducts; public class CachedProduct { String name; String productCode; Decimal leadTime; } List<Product2> products = [SELECT Name, ProductCode, LeadTime FROM Product2];
  41. 41. Size matters No cached item may exceed 100kB
  42. 42. Size matters 100kB Cache storage equals 12.5k objects same list, but stored in an Apex defined type 9k sObject records Product2 records with Id, Name, ProductCode queried
  43. 43. Repeat after me… :-) • Don‘t use the cache as a fast, limit-free database. • Don‘t use it as temporary storage for transactional data • No items larger than 100kB • Cached Items are not persisted – don‘t rely on them being there. • Unless flagged as immutable, don’t rely on the integrity of cached items
  44. 44. Best Practices • Cache lists or maps of objects rather than single objects. Tradeoff: Better performance of fewer, larger operations vs. 100kB item size limit • Use a wrapper class to reduce sObject overhead • Use the fully qualified name of your cache partition • Consider using the ‘immutable‘ flag and the visibility enum
  45. 45. Further Reading • Developer Documentation: • Trailhead: • Session Code: • Keir Bowden’s blog post: • Josh Kaplan‘s blog post: • Amit Chaudhary:
  46. 46. Q&A Connect with me • @stangomat • • Sample Code from the session:
  47. 47. Thank you! Q & A
  48. 48. Heading text goes here #SalesforceApexHours @ApexHours n-mi-developers-group/ hR_WEFepkcJw/videos g/?ref=bookmarks