Sub topic 7
Callouts, DML, and triggers
This chapter assumes you can write a basic Apex callout, know the governor limits, and have used Queueable Apex. It covers how callouts interact with database writes, and why triggers need special handling.
The uncommitted work rule
Salesforce holds a database transaction open until the request finishes. It does not allow a callout while that transaction has uncommitted changes. The reason is that a slow external call would keep database locks held for its whole duration.
After any DML statement (insert, update, delete, Database.insert, and so on), the transaction has "uncommitted work pending". A later callout in the same transaction throws a System.CalloutException:
You have uncommitted work pending. Please commit or rollback before calling out.SOQL queries do not count as DML. You can query, call out, and then write.
The rule applies for the rest of the transaction. A loop that calls out and then updates a record on each pass fails on the second iteration:
// Fails on the second pass: the update from pass one blocks the next callout
for (Account a : accounts) {
HttpResponse res = new Http().send(buildRequest(a));
a.Description = 'Synced';
update a;
}The fix: callouts first, DML last
Collect the results while you make the calls. Then write everything in one DML statement at the end.
List<Account> toUpdate = new List<Account>();
for (Account a : accounts) {
HttpResponse res = new Http().send(buildRequest(a));
if (res.getStatusCode() >= 200 && res.getStatusCode() < 300) {
toUpdate.add(new Account(Id = a.Id, Description = 'Synced'));
}
}
update toUpdate; // one DML statement, after every calloutThis also uses fewer DML statements, which helps with the 150-statement limit.
Triggers cannot call out synchronously
A trigger runs in the middle of a DML operation, so the transaction is open and a synchronous callout is not allowed. Apex also does not support callouts made directly from trigger code. The standard pattern is for the trigger to hand the work to asynchronous Apex.
trigger AccountSync on Account (after insert) {
System.enqueueJob(new AccountSyncJob(new Map<Id, Account>(Trigger.new).keySet()));
}The trigger enqueues one job for the whole batch of records. It passes only record IDs, not sObjects, so the job reads current data when it runs. The job runs after the original transaction commits, in a new transaction with its own limits.
public class AccountSyncJob implements Queueable, Database.AllowsCallouts {
private final Set<Id> accountIds;
public AccountSyncJob(Set<Id> accountIds) {
this.accountIds = accountIds;
}
public void execute(QueueableContext ctx) {
List<Account> toUpdate = new List<Account>();
for (Account a : [SELECT Id, Name FROM Account WHERE Id IN :accountIds]) {
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:Orders_API/accounts');
req.setMethod('POST');
req.setHeader('Content-Type', 'application/json');
req.setBody(JSON.serialize(new Map<String, Object>{
'id' => a.Id, 'name' => a.Name
}));
req.setTimeout(30000);
try {
HttpResponse res = new Http().send(req);
if (res.getStatusCode() >= 200 && res.getStatusCode() < 300) {
toUpdate.add(new Account(Id = a.Id, Description = 'Synced'));
}
} catch (System.CalloutException e) {
System.debug(LoggingLevel.WARN, 'Callout failed for ' + a.Id + ': ' + e.getMessage());
}
}
update toUpdate;
}
}The class must implement Database.AllowsCallouts. Without it, the callout fails even though the job is asynchronous.
Limits to keep in mind
- A transaction allows 100 callouts, so a job that loops over IDs needs a cap on the batch size. Split large sets across several jobs.
- A transaction can enqueue at most 50 jobs. Enqueue once per trigger invocation, never once per record.
- A Queueable job can enqueue only one child job, so retry jobs chain one after another.
- In tests, enqueued jobs run when
Test.stopTest()is called.
Why this matters for retries
A retry is another transaction. Because the job makes its callouts first and writes last, a failed attempt leaves no half-finished database changes. The retry can start clean. The next chapters build on this structure.
Exercise
A developer's Queueable job loops over 20 orders. For each order it calls an API and then runs update order;. The first order succeeds and the second throws a CalloutException about uncommitted work. What is the cause, and how should the code change?
Show answer
The update on the first order leaves uncommitted work pending, so the next callout in the same transaction is rejected. Make all callouts first, collect the changed records in a list, and run a single update after the loop. Keep the number of orders per job under the 100-callout limit.