Sub topic 2
Where a Transaction Starts and Ends
This chapter assumes you can write basic Apex, run DML statements such as insert and update, and use try/catch. It also assumes you know that governor limits exist. It covers how Apex decides where one transaction stops and the next begins. That boundary determines what a rollback can undo, which later chapters rely on.
The boundary in one sentence
A transaction is one unit of Apex execution that started at an entry point. It ends when that execution finishes. If it finishes normally, Salesforce commits all its DML. If an exception goes unhandled, Salesforce rolls back all its DML.
Apex has no BEGIN or COMMIT statement. You never start or commit a transaction by hand. The platform does both, and you work inside the span it gives you.
Entry points that start a transaction
A new transaction begins whenever the platform invokes your code from the outside. Common entry points:
| Entry point | What counts as one transaction |
|---|---|
| Anonymous Apex | One execution of the script |
| DML from the UI, API, or Data Loader | The save operation, including every trigger it fires |
| `@AuraEnabled` or Visualforce controller method | One server call from the client |
| `@RestResource` or `webservice` method | One request and its response |
| `Schedulable.execute` | One scheduled run |
| `Database.Batchable.execute` | One chunk (scope) of records |
| `Queueable.execute` | One job run |
| `@future` method | One invocation |
| Test method | The method body, rolled back when the test ends |
Each row is a separate transaction with its own governor limits. A scheduled job that enqueues a queueable job has started two transactions, not one.
What stays inside one transaction
Everything triggered synchronously by your DML stays in the same transaction as that DML:
- Before and after triggers.
- Record-triggered flows and other automation that runs as part of the save.
- Any Apex those triggers call, however deeply nested.
- DML performed by that called code.
If a trigger on Contact updates an Account, and a trigger on Account inserts a Task, all three records are saved or lost together. One exception thrown anywhere in the chain rolls back the whole chain.
Governor limits are measured across this whole span. A DML statement in a trigger counts against the same 150-statement budget as the one that fired it. You can see the running total with Limits.getDmlStatements().
trigger AccountAudit on Account (after insert) {
// Counts toward the same transaction as the insert that fired it
System.debug('DML statements so far: ' + Limits.getDmlStatements());
}Static variables also live exactly as long as the transaction. A static set in one transaction is gone in the next, and each async job starts with fresh statics.
Asynchronous work starts a new transaction
Queuing async work does not extend the current transaction. The job waits until the current transaction finishes, then runs later in its own transaction with its own limits. The following code shows the difference.
public class BoundaryDemo implements Queueable {
public void execute(QueueableContext ctx) {
// A new transaction: the DML counter starts again at 0
System.debug('Queueable, before insert: ' + Limits.getDmlStatements());
insert new Account(Name = 'From queueable');
System.debug('Queueable, after insert: ' + Limits.getDmlStatements());
}
}Run this in anonymous Apex, assuming no triggers on Account add DML of their own:
insert new Account(Name = 'From caller');
System.debug('Caller: ' + Limits.getDmlStatements()); // 1
System.enqueueJob(new BoundaryDemo());The caller logs 1. The queueable logs 0 before its insert and 1 after. Its count did not continue from the caller's.
This has two consequences:
- The job runs after the enqueuing transaction has committed, so it can see that transaction's records.
- A failure in the job cannot roll back the caller. The caller has already committed. Likewise, the caller cannot catch an exception thrown inside the job.
Batch Apex: one transaction per chunk
A batch job is the clearest case of many transactions from one request. The start, each execute, and finish are separate transactions. Each chunk of records commits or rolls back on its own.
public class AccountCleanupBatch implements Database.Batchable<SObject> {
public Database.QueryLocator start(Database.BatchableContext bc) {
return Database.getQueryLocator(
'SELECT Id FROM Account WHERE Name LIKE \'Temp%\''
);
}
public void execute(Database.BatchableContext bc, List<Account> scope) {
delete scope; // commits or rolls back for this chunk only
}
public void finish(Database.BatchableContext bc) {
}
}Start it with:
Database.executeBatch(new AccountCleanupBatch(), 200);Suppose the job has 1,000 records, so five chunks of 200. If chunk 3 throws an unhandled exception, the platform rolls back chunk 3 only. Chunks 1 and 2 stay committed. Chunks 4 and 5 still run unless you stop the job. A batch job is therefore not atomic as a whole. If you need all-or-nothing across the full data set, a batch job is the wrong tool.
Separate client calls are separate transactions
A client that calls Apex twice has run two transactions, even if the calls happen a moment apart. A Lightning component might call saveHeader() and then saveLines(). If saveLines() fails, the header is already committed. No savepoint in saveLines() can reach back and undo it.
Commit timing and visibility
Within a transaction, your own SOQL queries see your uncommitted DML. Other users and other transactions do not see it until the commit. The records you modified are locked until the transaction ends. A long transaction that touches many records can therefore block other users or jobs and cause UNABLE_TO_LOCK_ROW errors. Keeping transactions short and focused reduces that risk.
Callouts and the boundary
HTTP callouts interact with transaction boundaries. Calling out to an external system while a transaction holds uncommitted DML raises an error. A later chapter covers this and the usual ways around it. For now, note that this restriction exists because a callout cannot be rolled back.
Test methods
A test method is its own transaction. Salesforce rolls back all data the test created when it finishes, so tests do not pollute the org. Test.startTest() and Test.stopTest() do not start a new transaction. They give the code between them a fresh set of governor limits, and they force queued async jobs to run when stopTest() is called. Those jobs still run as separate transactions inside the test.
Common mistakes
- Assuming async work shares limits with the caller. It does not. Each async job gets its own limits, which is one reason to move heavy work there.
- Expecting a rollback to undo an enqueued job's effects. If the job has already run in its own transaction, its changes are committed.
- Treating a batch job as atomic. Only each
executechunk is atomic. - Splitting a unit of work across client calls. The first call commits before the second begins.
- Reading
Limitsvalues as if they were global. They describe the current transaction only.
Exercise
A Lightning web component calls the Apex method createOrder(), which inserts an Order and then returns. The component then calls createOrderLines(), which inserts 10 lines, and the 7th line fails with an unhandled exception. Which records exist afterward, and why?
Show answer
The Order exists and no order lines exist. The two server calls are separate transactions. createOrder() committed when it returned. The exception in createOrderLines() rolls back only that call's work, which is all 10 line inserts (the failure aborts the call, so none of the lines are saved). To make the Order and its lines succeed or fail together, do both inserts in one Apex method.
Exercise
A batch job runs with a scope size of 100 over 450 records. The execute call for the second chunk throws an unhandled exception. How many records' changes are committed, and how many chunks are rolled back?
Show answer
The chunks hold 100, 100, 100, 100, and 50 records. Only chunk 2 is rolled back. The other four chunks are separate transactions that complete normally, so 350 records' changes are committed.