> For the complete documentation index, see [llms.txt](https://triton.pharos.ai/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://triton.pharos.ai/triton-best-practices/transaction-management.md).

# Transaction Management

Stitching logs from LWC, Apex, and Flow into a single trace — starting, resuming, and stopping transactions, and passing the id versus using platform cache.

A transaction id is the thread that ties otherwise-disconnected logs into one story. Without it, a user clicking "Convert" produces an LWC log here, an Apex log there, and a Flow log somewhere else — three records you have to correlate by hand, by timestamp, at 2am. With it, they're one trace you read top to bottom.

Triton keeps a transaction id as static state for the life of an Apex transaction, and gives you three verbs to manage it — `startTransaction`, `resumeTransaction`, `stopTransaction` — plus `withCache` for the hands-off approach. This page is about using them across boundaries.

## The three verbs

* **`Triton.startTransaction()`** — mint a fresh correlation id and return it. Call this at a true entry point (a user action, a scheduled job kicking off).
* **`Triton.resumeTransaction(id)`** — adopt an id that was created elsewhere. This is how a hop *joins* an existing trace.
* **`Triton.stopTransaction()`** — clear the id at the end of the unit of work.

{% code lineNumbers="true" %}

```apex
String txId = Triton.startTransaction();   // begin a trace
// ... log some things — they all carry txId ...
Triton.stopTransaction();                  // end it
```

{% endcode %}

{% hint style="info" %}
**You don't always need to start one explicitly.** Within a single Apex transaction, logs already share static state and correlate fine on their own. Explicit transaction management earns its keep when you're crossing a boundary — LWC → Apex, Apex → Flow, or one async hop to the next — where the static state would otherwise reset.
{% endhint %}

## The pattern: start at the edge, resume on each hop, stop at the end

The rule of thumb:

1. **Start** the transaction at the outermost entry point (usually the LWC, or the first Apex if there's no UI).
2. **Carry** the id across each boundary and **resume** it on the other side.
3. **Stop** it when the top-level unit of work finishes.

## Crossing LWC → Apex

Two ways to move the id across the wire. Pick based on how complex the flow is.

### Approach 1 — pass the id explicitly

The most explicit and the easiest to debug. Start the transaction in the LWC, read `triton.transactionId`, and pass it as a method parameter. On the Apex side, resume it.

{% code lineNumbers="true" %}

```javascript
// opportunityList.js
import loadOpps from '@salesforce/apex/OppController.loadOpps';
import Triton, { TYPE, AREA } from 'c/triton';

export default class OpportunityList extends LightningElement {
    triton;

    connectedCallback() {
        this.triton = new Triton().bindToComponent('opportunityList');
        this.triton.startTransaction();
        this.triton.setTemplate(
            this.triton.makeBuilder()
                .type(TYPE.FRONTEND)
                .area(AREA.OPPORTUNITY_MANAGEMENT)
                .relatedObjects([this.recordId])
        );
    }

    async loadData() {
        try {
            // Hand the transaction id to Apex
            const data = await loadOpps({
                accountId: this.recordId,
                txId: this.triton.transactionId
            });
            this.triton.log(this.triton.fromTemplate().summary(`Rendered ${data.length} opportunities`));
        } catch (error) {
            this.triton.logNow(this.triton.fromTemplate().exception(error).summary('Failed to load opportunities'));
        }
    }

    disconnectedCallback() {
        this.triton.stopTransaction();
    }
}
```

{% endcode %}

{% code lineNumbers="true" %}

```apex
// OppController.cls
public with sharing class OppController {
    @AuraEnabled(cacheable=false)
    public static List<Opportunity> loadOpps(Id accountId, String txId) {
        // Join the trace the LWC started
        if (String.isNotBlank(txId)) {
            Triton.resumeTransaction(txId);
        } else {
            Triton.startTransaction();
        }

        Triton.setTemplate(Triton.makeBuilder()
            .category(TritonTypes.Category.Apex)
            .area(TritonTypes.Area.OpportunityManagement)
            .relatedObject(accountId));

        try {
            List<Opportunity> opps = [SELECT Id, Name, Amount FROM Opportunity WHERE AccountId = :accountId LIMIT 200];
            Triton.info(Triton.t.summary('Loaded opportunities').details('count=' + opps.size()));
            return opps;
        } catch (Exception e) {
            Triton.logNow(Triton.t.exception(e));
            throw e;
        } finally {
            Triton.flush();
        }
    }
}
```

{% endcode %}

### Approach 2 — let platform cache carry it

For complex UIs with many components and async calls, threading a `txId` parameter through everything gets tedious. `Triton.withCache()` backs the transaction id with platform cache, so Apex can pick up the LWC's id automatically — no parameter required.

{% code lineNumbers="true" %}

```apex
@AuraEnabled
public static void doWork() {
    Triton.withCache();   // resumes the cached transaction id if one exists, else starts one
    Triton.setTemplate(Triton.makeBuilder()
        .category(TritonTypes.Category.Apex)
        .area(TritonTypes.Area.Community));
    // ... logs here automatically join the LWC's trace ...
    Triton.flush();
}
```

{% endcode %}

The trade-offs and setup are covered in [Beyond Apex → Platform Cache for Transactions](https://triton.pharos.ai/beyond-apex/lwc-and-apex-cache.md). Quick guidance:

| Use explicit passing when…               | Use `withCache()` when…                                     |
| ---------------------------------------- | ----------------------------------------------------------- |
| The path is simple and linear            | Many components / async calls make passing an id cumbersome |
| You want maximum clarity while debugging | You'd rather not thread a parameter everywhere              |
| You're just getting started              | Platform cache is available and configured in the org       |

## Crossing Apex → Flow

Flow correlation is largely automatic. When Apex commits a DML that fires an autolaunched Flow, and the Flow's **Log** actions pass `$Flow.InterviewGuid`, Triton groups the Flow's logs under the same transaction — and even attaches any **unhandled** Flow exception to the trace with no extra code. Always pass `$Flow.InterviewGuid` on every Flow log action. The full walkthrough (LWC → Apex → Flow, both approaches) is in [End-to-End Logging](https://triton.pharos.ai/end-to-end.md).

## Async hops: Queueable, Batch, Future

Each async execution is a *new* Apex transaction with fresh statics — so the id doesn't ride along automatically. If you want a chained job to stay on the same trace, capture the id before enqueuing and resume it inside:

{% code lineNumbers="true" %}

```apex
public class ChainedJob implements Queueable {
    private final String txId;
    public ChainedJob(String txId) { this.txId = txId; }

    public void execute(QueueableContext qc) {
        Triton.resumeTransaction(txId);   // rejoin the originating trace
        Triton.setTemplate(Triton.makeBuilder()
            .category(TritonTypes.Category.Apex)
            .area(TritonTypes.Area.OpportunityManagement));
        try {
            // ... work ...
            Triton.info(Triton.t.summary('Chained job done'));
        } finally {
            Triton.flush();
        }
    }
}

// Enqueue with the current trace id so the job stays correlated
System.enqueueJob(new ChainedJob(Triton.TRANSACTION_ID));
```

{% endcode %}

## What good looks like

Done right, one user action reads as one tree in Pharos:

{% code lineNumbers="true" %}

```
Transaction: 7fb8c320-e8f9-4f1b-9742-1a5768b9e0d2
├── LWC log (button clicked)
├── Apex log (DML performed)
└── Flow execution
    ├── Flow start
    ├── Flow operation
    └── Unhandled Flow error (auto-captured)
```

{% endcode %}

{% hint style="warning" %}
**Always stop what you start, and flush before you stop.** Leaving a transaction open risks bleeding context into unrelated work if statics are reused; forgetting to flush first loses buffered logs. In LWC, `stopTransaction()` in `disconnectedCallback` flushes remaining logs for you — but in Apex, put your `flush()` before `stopTransaction()` (a `finally` block is the safe home for both).
{% endhint %}

## Related reading

* End-to-end walkthrough across all three layers: [End-to-End Logging](https://triton.pharos.ai/end-to-end.md).
* Cache-backed correlation setup: [Beyond Apex → Platform Cache for Transactions](https://triton.pharos.ai/beyond-apex/lwc-and-apex-cache.md).
* LWC-side transaction details: [Beyond Apex → LWC Transaction Management](https://triton.pharos.ai/beyond-apex/lwctransaction.md).
