Pharos Triton
  • 🔱About Pharos Triton
  • 🏁Installing Pharos Triton
  • Apex Logging Basics
  • Common Apex Usage Patters
    • Batch Logging
    • Integration Logs
    • Apex Rest Logging
    • Full Control with TritonBuilder
  • Beyond Apex
    • LWC
    • 🔄LWC Transaction Management
    • ⚡LWC and Apex
    • 💾Platform Cache for Transactions
    • Flows
    • 〰️LWC, Apex and Flows
  • 📖Methods Reference
    • 📔Apex
      • Triton
      • TritonBuilder
      • TritonTypes
      • TritonLwc
        • ComponentLog
        • Component
        • Error
        • RuntimeInfo
      • TritonFlow
        • FlowLog
      • TritonHelper
        • PostProcessingControlsBuilder
      • LogBuilder
    • LWC
      • Triton
      • TritonBuilder
      • TritonUtils
  • Help and Support
Powered by GitBook
On this page
  • Understanding Platform Cache
  • How Triton Uses Platform Cache
  • Using Cache Instead of Direct Parameter Passing
  • How withCache() Works
  • Benefits and Considerations
  • Benefits
  • Caveats
  • Best Practices
  1. Beyond Apex

Platform Cache for Transactions

Learn how to use Salesforce Platform Cache with Triton to manage transaction IDs across different contexts without direct parameter passing.

PreviousLWC and ApexNextFlows

Last updated 1 month ago

Understanding Platform Cache

Salesforce Platform Cache is a distributed caching service that stores frequently accessed data in memory. Before using platform cache with Triton, you'll need to:

  1. Set up a partition in Setup > Platform Cache

  2. Allocate some memory to the partition

  3. Create a default partition if you haven't already

If you don't have a default partition, you can create one by going to Setup > Platform Cache > New Partition and naming it "default".

For detailed instructions on setting up platform cache, see in the Salesforce documentation.

How Triton Uses Platform Cache

Triton uses platform cache to store transaction IDs, making them accessible across different execution contexts. This is particularly useful when:

  • Direct parameter passing is impractical

  • You're dealing with multiple components or services

  • You need to correlate logs across asynchronous operations

When you enable caching using withCache(), Triton:

  1. Stores the transaction ID in the platform cache

  2. Uses the running user's ID as part of the cache key

  3. Automatically retrieves the transaction ID when needed

Note that Triton automatically checks for platform cache availability and will gracefully fall back to direct parameter passing if caching is unavailable or no partitions are configured.

Using Cache Instead of Direct Parameter Passing

logDemo.js
export default class LogDemo extends LightningElement {
    triton;
    
    connectedCallback() {
        // Bind triton to this component
        this.triton = new Triton().bindToComponent('LogDemo');
    }
    
    async executeScenario() {
        await this.triton.logNow(
            this.triton.debug(TYPE.FRONTEND, AREA.ACCOUNTS)
                .summary('Cache Demo - Start')
                .details('Starting execution with cache enabled')
        );

        try {
            // Note we're not passing transactionId here
            await apexActionThatGeneratesDMLError({
                cacheEnabled: true
            });
        } catch (error) {
            await this.triton.logNow(this.triton.exception(error));
        }
    }
}

And in your Apex controller:

LogDemoController.cls
public with sharing class LogDemoController {
    @AuraEnabled
    public static void apexActionThatGeneratesDMLError(Boolean cacheEnabled) {
        if (cacheEnabled) {
            // This will automatically retrieve the transaction ID from cache
            Triton.instance.withCache();
        }
        
        Triton.instance.debug(
            TritonTypes.Type.Backend,
            TritonTypes.Area.Community,
            'Cache Demo - Apex',
            'Executing with cached transaction ID'
        );
        
        try {
            ContentVersion contentVersion = new ContentVersion();
            contentVersion.ContentLocation = 'Apex Error';
            contentVersion.Title = 'Apex Error';
            contentVersion.PathOnClient = 'ApexError.pdf';
            insert contentVersion;
        } catch (Exception e) {
            Triton.instance.error(TritonTypes.Area.Community, e);
        }
    }
}

How withCache() Works

When you call withCache(), Triton follows this logic:

  1. First, it checks if platform cache is available and configured

  2. If cache is available:

    • It uses the running user's ID to create a unique cache key

    • Looks for an existing transaction ID in the cache

    • If found, resumes that transaction

    • If not found, generates a new transaction ID and stores it in cache

  3. If cache is not available:

    • Automatically falls back to starting a new transaction

    • Continues execution without using cache

This automatic fallback behavior means you don't need to explicitly handle transaction management when cache is unavailable - Triton handles this for you.

Benefits and Considerations

Benefits

  • Simplified parameter passing

  • Works across asynchronous boundaries

  • Reduces code complexity

  • Makes transaction ID management transparent

Caveats

Since Triton uses the running user's ID as part of the cache key, all operations performed by the same user within the cache timeout period will share the same transaction ID. This can lead to unintended log grouping in scenarios like:

  1. If a batch job runs on behalf of the same user who initiated an LWC action

  2. When multiple browser tabs are executing similar operations

  3. If the cache isn't cleared properly between operations

Consider these scenarios when deciding whether to use cache or direct parameter passing.

Best Practices

  1. LWC components and their associated Apex controllers are ideal candidates for platform cache, especially when dealing with multiple server calls or asynchronous operations

  2. Use direct parameter passing for simple, synchronous operations

  3. Reserve cache usage for complex scenarios involving multiple contexts

  4. Monitor cache usage and adjust partition sizes as needed

  5. Consider using startTransaction() to generate a new transaction ID when you want to ensure separation between operations

Platform cache provides a powerful way to manage transaction IDs across different execution contexts, but it should be used thoughtfully based on your specific use case.

While our previous article demonstrated passing transaction IDs directly through method parameters, here's an example of how to use platform cache with Triton. This example shows a common scenario where an LWC component needs to log actions and errors across both frontend and backend contexts - one of the most common and effective use cases for platform cache:

💾
Set Up Platform Cache
⚡ LWC and Apex