Sub topic 10
Uncommitted Work and Callouts from Triggers
This chapter assumes you can write Apex classes and triggers, know the basics of governor limits, and have a working callout like the TodoService.fetchTodo method from earlier chapters. It explains one rule that surprises many developers: you cannot make a callout while a transaction holds uncommitted changes.
The uncommitted work pending error
Apex runs each transaction as one unit. Records you insert, update or delete stay uncommitted until the transaction finishes successfully. If you then make a callout in the same transaction, Salesforce throws this error:
System.CalloutException: You have uncommitted work pending. Please commit or rollback before calling out.The platform enforces this rule because a callout can take a long time. Holding database locks open while waiting for an external server would hurt every other user. The rule also stops you from leaving your data and the external system in a state that can't be rolled back cleanly.
The rule applies to any DML before the callout. A callout before the DML is fine.
public with sharing class OrderSync {
// Fails: DML first, then callout
public static void broken(Account acc) {
insert acc;
TodoService.fetchTodo(1); // CalloutException
}
// Works: callout first, then DML
public static void working(Account acc) {
String body = TodoService.fetchTodo(1);
acc.Description = body;
insert acc;
}
}Reordering is the simplest fix when you control the whole flow. Make every callout first, collect the results, then do all DML at the end.
Why triggers make this harder
A trigger runs inside the transaction that saved the record. By the time an after insert trigger fires, the insert is uncommitted. A callout from that trigger therefore fails, even if your trigger code does no other DML.
Triggers have a second problem. Callouts also are not allowed from a trigger's synchronous code path unless they run in an asynchronous context. A single bulk save can fire a trigger for up to 200 records at a time, and one callout per record would quickly reach the limit of 100 callouts per transaction.
Moving the callout out of the transaction
The standard solution is to let the transaction commit first, then run the callout in a separate asynchronous transaction. A Queueable job that implements Database.AllowsCallouts does this. The TodoSyncJob class from the earlier chapter is one example.
trigger AccountTrigger on Account (after insert) {
for (Account a : Trigger.new) {
System.enqueueJob(new TodoSyncJob(1));
}
}The job is queued during the transaction but runs only after it commits. Because it starts as a new transaction, it begins with no pending work and can call out freely.
The loop above is a poor pattern, though. Each System.enqueueJob call counts against the limit of 50 jobs per transaction. A better design passes the whole set of IDs to one job:
public class AccountSyncJob implements Queueable, Database.AllowsCallouts {
private List<Id> accountIds;
public AccountSyncJob(List<Id> accountIds) {
this.accountIds = accountIds;
}
public void execute(QueueableContext context) {
for (Id accountId : accountIds) {
TodoService.fetchTodo(1);
}
}
}trigger AccountTrigger on Account (after insert) {
System.enqueueJob(new AccountSyncJob(new List<Id>(Trigger.newMap.keySet())));
}Keep the total callouts in one job under 100. For larger sets, split the IDs into chunks and chain jobs.
Common mistakes
- Doing DML, then calling out in the same method. Reorder, or move the callout to a Queueable job.
- Calling
Database.setSavepoint()and then calling out. A savepoint counts as uncommitted work in a way that triggers the same error in practice, so avoid it before a callout. - Enqueuing one job per record in a trigger. Batch the IDs into one job.
- Forgetting
Database.AllowsCallouts. Without it, the job fails when it calls out. - Assuming the job has run when the trigger returns. It runs later, so don't depend on its result in the same transaction.
Exercise
An after insert trigger on Contact updates a related Account with DML and then calls TodoService.fetchTodo(5). The callout throws "You have uncommitted work pending". Name two ways to fix it.
Show answer
Either move the callout before the DML, so no uncommitted work exists when it runs, or move the callout into a Queueable class that implements Database.AllowsCallouts and enqueue it from the trigger, so it runs in a new transaction after the first one commits.