Sub topic 15
Transactions in Batch, Queueable, and Future Methods
This chapter assumes you know how an Apex transaction starts and ends. It also assumes you know that an unhandled exception rolls back DML, and that a caught exception does not. Here we apply those rules to asynchronous Apex.
Each async job is its own transaction
Asynchronous Apex runs later, in a separate transaction from the code that requested it. The requesting transaction can finish, commit, or roll back without affecting the job's own work. The job gets its own set of governor limits and its own commit or rollback.
| Async type | What forms one transaction |
|---|---|
| Future method | One call to the `@future` method |
| Queueable | One run of `execute` |
| Batch | Each call to `execute`, plus `start` and `finish` separately |
The rollback rules from earlier chapters apply inside each of these transactions. An unhandled exception rolls back that transaction's DML. A caught exception does not.
Batch: one transaction per chunk
A batch job splits its records into chunks. Each call to execute is a separate transaction. If execute throws an unhandled exception, only that chunk's DML is rolled back. Chunks that already finished stay committed, and later chunks still run.
This means a batch job is not atomic as a whole. If you need all-or-nothing behavior across every record, a batch job is the wrong tool.
Use Database.Stateful if you need to count failures across chunks. Instance variables are reset between chunks unless the class implements it.
public class AccountCleanup implements Database.Batchable<SObject>, Database.Stateful {
public Integer failedRows = 0;
public Database.QueryLocator start(Database.BatchableContext bc) {
return Database.getQueryLocator('SELECT Id, Name FROM Account');
}
public void execute(Database.BatchableContext bc, List<Account> scope) {
for (Account a : scope) {
a.Description = 'Reviewed';
}
Database.SaveResult[] results = Database.update(scope, false);
for (Database.SaveResult sr : results) {
if (!sr.isSuccess()) {
failedRows++;
}
}
}
public void finish(Database.BatchableContext bc) {
System.debug('Failed rows: ' + failedRows);
}
}Here Database.update(scope, false) lets good records save inside a chunk. Failures are counted instead of rolling back the whole chunk.
Queueable and future
A queueable job runs execute in one transaction. An unhandled exception rolls back its DML. A caught exception commits whatever succeeded before it. A future method behaves the same way.
Savepoints work inside these methods. Set the savepoint inside the async method, because a savepoint from the requesting transaction does not exist in the job's transaction.
public class ContactLoader implements Queueable {
public void execute(QueueableContext ctx) {
Savepoint sp = Database.setSavepoint();
try {
Account a = new Account(Name = 'Async Co');
insert a;
insert new Contact(LastName = 'Lee', AccountId = a.Id);
} catch (DmlException e) {
Database.rollback(sp);
}
}
}A common mistake
Enqueuing a job is not part of the job's work. If the requesting transaction rolls back, the queued job is not run, because the enqueue is undone with it. Do not rely on a job running after the code that enqueued it has failed.
Exercise
A batch job has three chunks. The second call to execute throws an unhandled exception. What happens to the DML from chunk one and chunk three?
Show answer
Chunk one stays committed because it finished in its own transaction. Chunk three runs in its own transaction and commits if it succeeds. Only chunk two's DML is rolled back.