# Platform Cache for Transactions

## Understanding Platform Cache

Salesforce Platform Cache is a distributed caching service that stores frequently accessed data in memory. Triton leverages platform cache to store transaction IDs, making them accessible across different execution contexts without requiring direct parameter passing.

{% hint style="info" %}
**Prerequisites**: Before using platform cache with Triton, you must configure a default cache partition with session cache allocation. See [Platform Cache Setup](/pharos-triton/installing-pharos-triton.md#platform-cache-setup) in the installation guide for detailed configuration instructions.
{% endhint %}

## 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

{% hint style="info" %}
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.
{% endhint %}

## Using Cache Instead of Direct Parameter Passing

While our previous article [⚡ LWC and Apex](/pharos-triton/beyond-apex/lwc-and-apex.md) 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:

{% code title="logDemo.js" %}

```javascript
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));
        }
    }
}
```

{% endcode %}

And in your Apex controller:

{% code title="LogDemoController.cls" %}

```apex
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);
        }
    }
}
```

{% endcode %}

## 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

{% hint style="warning" %}
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.
{% endhint %}

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


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://triton.pharos.ai/pharos-triton/beyond-apex/lwc-and-apex-cache.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
