Sub topic 15
Transactions in Batch, Queueable, and Future Methods
This chapter assumes you know how an Apex transaction commits or rolls back, how Database.setSavepoint and Database.rollback work, and the basic shape of @future, Queueable, and Database.Batchable classes. It covers how those three kinds of asynchronous Apex divide work into transactions, and what that means for rollback.
Each Async Execution Is Its Own Transaction
Code that runs asynchronously does not share a transaction with the code that requested it. The requesting transaction ends first. The platform then runs the async work later in a new transaction with its own governor limits and its own commit or rollback.
Three consequences follow:
- An unhandled exception in async code rolls back only that async transaction. It cannot undo what the caller already committed.
- A rollback in the caller cannot reach into async work that has already started.
- Static variables do not carry over, because each transaction starts with fresh statics.
Future Methods
A @future method is a static method that returns void and takes only primitives or collections of primitives. It runs as a single transaction.
public class AccountSync {
@future
public static void markReviewed(Set<Id> accountIds) {
Savepoint sp = Database.setSavepoint();
try {
List<Account> accts = [SELECT Id FROM Account WHERE Id IN :accountIds];
for (Account a : accts) {
a.Description = 'Reviewed';
}
update accts;
} catch (DmlException e) {
Database.rollback(sp);
System.debug('Future work rolled back: ' + e.getMessage());
}
}
}Points to remember:
- The caller does not wait for the result and gets no return value. If the future method fails, the caller's committed records stay committed.
- A future method cannot be called from another future method or from a batch
execute. This blocks chaining, so you cannot run follow-up work that way. - An unhandled exception rolls back the future transaction and is reported as a failed async job. No code in the caller can catch it.
Queueable Jobs
A Queueable class is a more flexible async option. Its execute method is one transaction. It can take sObjects and other complex types, and it can enqueue another job.
public class ContactFollowUp implements Queueable {
private List<Contact> contacts;
public ContactFollowUp(List<Contact> contacts) {
this.contacts = contacts;
}
public void execute(QueueableContext ctx) {
for (Contact c : contacts) {
c.Description = 'Follow-up scheduled';
}
update contacts;
// A chained job starts its own transaction after this one finishes.
// System.enqueueJob(new NextStep());
}
}Chaining does not create one large transaction. If the second job in a chain fails, the first job's work stays committed. Design each link so that it can be retried safely, or so that a failure leaves data in a valid state.
If you need cleanup or logging after a job, attach a finalizer with System.attachFinalizer. A finalizer implements System.Finalizer and runs in its own transaction after the job finishes, including when the job failed. That makes it the right place to record a failure. The failed job's own DML has already rolled back, so the finalizer cannot write that data in the job's transaction.
Enqueue Last
Enqueue async work after your DML has succeeded, not before. Do not rely on a rollback to cancel a job that has already been enqueued. Keep the enqueue call at the end of the method and outside any block that you might roll back:
public static void saveAndNotify(List<Account> accts) {
insert accts;
// Only reached if the insert succeeded.
System.enqueueJob(new AccountFollowUp(accts));
}Batch Apex: One Transaction per Chunk
Batch Apex divides a large set of records into chunks (scopes). Each of the following runs as its own transaction:
start- each call to
execute finish
This is the most important rule for batch rollback. If execute throws an unhandled exception for chunk 3, only chunk 3 rolls back. Chunks 1 and 2 stay committed. The job continues with the later chunks.
State Across Chunks
Because every execute call is a separate transaction, instance variables are not kept between calls unless the class implements Database.Stateful. Static variables are never kept. Use Database.Stateful to carry counters or error lists from one chunk to the next and into finish.
public class AccountCleanupBatch implements Database.Batchable<SObject>, Database.Stateful {
public Integer updated = 0;
public List<String> errors = new List<String>();
public Database.QueryLocator start(Database.BatchableContext bc) {
return Database.getQueryLocator(
'SELECT Id, Description FROM Account WHERE Description = null'
);
}
public void execute(Database.BatchableContext bc, List<Account> scope) {
for (Account a : scope) {
a.Description = 'Reviewed';
}
Database.SaveResult[] results = Database.update(scope, false);
for (Integer i = 0; i < results.size(); i++) {
if (results[i].isSuccess()) {
updated++;
} else {
errors.add(scope[i].Id + ': ' + results[i].getErrors()[0].getMessage());
}
}
}
public void finish(Database.BatchableContext bc) {
System.debug('Updated ' + updated + ' accounts, ' + errors.size() + ' failures');
}
}This batch uses Database.update(scope, false), so one bad record does not roll back the other records in its chunk. Without false, a single failure would make the whole chunk fail, and every record in it would be rolled back.
Choosing Between Chunk-Level and Record-Level Failure
| Approach | What rolls back on a failure | Use when |
|---|---|---|
| `update scope;` | The whole chunk | Records in a chunk must succeed or fail together |
| `Database.update(scope, false)` | Only the failed records | Records are independent and you want maximum progress |
| Savepoint plus `Database.rollback` inside `execute` | Everything after the savepoint | A chunk includes several related DML statements that must stay consistent |
Savepoints work inside execute, but they only cover that one chunk. You cannot roll back to undo chunks that already committed. If a job needs an all-or-nothing result across every record, batch Apex cannot give you that on its own. You would need a compensating job that reverses the earlier changes, or a different design.
Chunk Size Affects Rollback
The scope size you pass to Database.executeBatch(job, size) sets how many records are lost together when a chunk fails. A large size is efficient but widens the blast radius. A small size gives finer-grained recovery but uses more transactions. The default is 200.
Comparing the Three
| Row | Future | Queueable | Batch |
|---|---|---|---|
| Transactions per run | 1 | 1 per job in a chain | 1 for `start`, 1 per `execute`, 1 for `finish` |
| Failure rolls back | The method | The job | The failing chunk only |
| Earlier work on failure | Caller unaffected | Earlier jobs in chain stay committed | Earlier chunks stay committed |
| Can carry state | Primitive arguments | Member variables set in the constructor | `Database.Stateful` |
| Savepoint scope | That method | That job | That `execute` call |
Testing Async Transactions
Async code in tests does not run until you force it. Wrap the call in Test.startTest() and Test.stopTest(). When stopTest is reached, the platform runs the queued async work synchronously, and you can then assert on the results.
@IsTest
private class AccountCleanupBatchTest {
@IsTest
static void updatesAccountsWithoutDescription() {
insert new List<Account>{
new Account(Name = 'One'),
new Account(Name = 'Two')
};
Test.startTest();
Database.executeBatch(new AccountCleanupBatch(), 200);
Test.stopTest();
Integer remaining = [SELECT COUNT() FROM Account WHERE Description = null];
System.assertEquals(0, remaining);
}
}In a test, executeBatch runs only one execute call, so keep test data within a single chunk. To test chunk-level rollback, create data that makes one chunk fail and assert that the records from the other chunks changed.
Exercise
A batch job runs with a scope size of 100 and processes 300 records using update scope; (all-or-none). The second chunk throws an unhandled DmlException. Which records are updated when the job ends, and how would you change the code so that only the individual bad records are left unchanged?
Show answer
The records in chunks 1 and 3 are updated, because each execute call is its own transaction. Chunk 2 rolls back entirely, so none of its 100 records are updated. To leave only the bad records unchanged, use Database.update(scope, false) and inspect each Database.SaveResult for failures. Use Database.Stateful if you want to collect the errors for finish.