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 read the earlier chapters on building requests and reading responses. It covers one rule that causes many callout bugs: you cannot make a callout while the transaction holds uncommitted work.
The uncommitted work rule
A callout can take seconds. During that time, Salesforce would have to hold database locks on every record you changed. To avoid long-held locks, the platform enforces this rule:
- If a transaction has performed DML and has not yet committed, any callout in that transaction fails.
The failure is a System.CalloutException with this message:
You have uncommitted work pending. Please commit or rollback before calling outThe rule is about order, not about the amount of DML. A callout that runs first is allowed. A callout that runs after any DML is not.
What counts as uncommitted work
The check is triggered by DML on records and by a few other operations:
insert,update,upsert,deleteandundelete, including theDatabaseclass equivalents.- Publishing platform events with
EventBus.publishwhen the event is set to publish after commit, in some configurations. - Calling
Savepointrollbacks does not reset the state for a callout in every case, so do not rely on it as a workaround.
Reads do not count. A SOQL query before a callout is always safe. The transaction only becomes "dirty" when it writes.
Order matters
Compare these two methods. The first works. The second throws.
public with sharing class OrderOfOperations {
// Works: callout first, DML second.
public static void calloutThenDml(Integer todoId, Account acc) {
String body = TodoService.fetchTodo(todoId);
acc.Description = body;
update acc;
}
// Fails: DML first, callout second.
public static void dmlThenCallout(Integer todoId, Account acc) {
update acc;
String body = TodoService.fetchTodo(todoId); // CalloutException
}
}The simplest fix, when you control the flow, is to reorder: make every callout first, keep the results in variables, and perform all DML at the end.
The diagram below shows the same sequence as a timeline of one transaction.
Why reordering is not always possible
Reordering works when one method owns the whole flow. It often does not, because:
- A trigger runs after the user's DML has already started, so the transaction already has uncommitted work by the time your trigger code executes.
- Several classes may take part in one transaction. A callout in one class can run after DML in another.
- A flow, process, or validation rule may have done DML earlier in the same transaction.
In these cases, move the callout out of the transaction. That means running it asynchronously.
Callouts from triggers
Synchronous callouts are not allowed from triggers at all. Even if no earlier DML occurred, the trigger itself runs inside the transaction that is saving records. The platform stops the callout, and the failure message is the same uncommitted work error or a related callout error.
The standard pattern is:
- The trigger collects the IDs (or the small amount of data) that the callout needs.
- The trigger enqueues an asynchronous job.
- The job runs in a separate transaction, after the original one commits, and makes the callout there.
A trigger that enqueues a Queueable
The job below implements Database.AllowsCallouts. Without that interface, callouts inside a Queueable fail.
public class AccountSyncJob implements Queueable, Database.AllowsCallouts {
private Set<Id> accountIds;
public AccountSyncJob(Set<Id> accountIds) {
this.accountIds = accountIds;
}
public void execute(QueueableContext context) {
List<Account> accounts = [
SELECT Id, Name
FROM Account
WHERE Id IN :accountIds
WITH USER_MODE
];
for (Account acc : accounts) {
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:Todo_API/todos');
req.setMethod('POST');
req.setHeader('Content-Type', 'application/json');
req.setBody(JSON.serialize(new Map<String, Object>{
'title' => acc.Name,
'completed' => false
}));
HttpResponse res = new Http().send(req);
if (res.getStatusCode() != 201) {
System.debug(LoggingLevel.ERROR,
'Sync failed for ' + acc.Id + ': ' + res.getStatusCode());
}
}
}
}trigger AccountTrigger on Account (after insert) {
Set<Id> ids = new Map<Id, Account>(Trigger.new).keySet();
System.enqueueJob(new AccountSyncJob(ids));
}Three design points in this code:
- The job receives IDs, not full records. It re-queries, so it sees committed data and any changes made after the trigger ran.
- The trigger uses
after insertbecause record IDs exist only after the insert. Enqueueing in abeforetrigger would passnullIDs. - The trigger does no callout and no DML before enqueueing, so it never risks the uncommitted work error.
Keep triggers thin
Put the enqueue logic in a handler class, as you would for any trigger. Also guard against repeated enqueueing. A trigger can fire more than once in one transaction, for example when a workflow field update causes a second pass. Each System.enqueueJob call counts against limits.
Limits that shape this design
Asynchronous callouts still obey limits. These matter most here:
| Limit | Value | Consequence |
|---|---|---|
| Callouts per transaction | 100 | A job looping over many records can reach it. |
| Queueable jobs enqueued per synchronous transaction | 50 | Enqueue one job with many IDs, not one job per record. |
| Queueable jobs enqueued from a running Queueable | 1 | Chain jobs one at a time. |
| Cumulative timeout per transaction | 120 seconds | Many slow calls in one job can exceed it. |
Because of the 100 callout cap, a job that handles many records should process a batch of them, then enqueue itself again with the rest.
public class BatchedSyncJob implements Queueable, Database.AllowsCallouts {
private List<Id> pendingIds;
private static final Integer CHUNK = 50;
public BatchedSyncJob(List<Id> pendingIds) {
this.pendingIds = pendingIds;
}
public void execute(QueueableContext context) {
Integer end = Math.min(CHUNK, pendingIds.size());
for (Integer i = 0; i < end; i++) {
// one callout per id, at most CHUNK per run
TodoService.fetchTodo(1);
}
if (pendingIds.size() > end) {
List<Id> rest = new List<Id>();
for (Integer i = end; i < pendingIds.size(); i++) {
rest.add(pendingIds[i]);
}
System.enqueueJob(new BatchedSyncJob(rest));
}
}
}Doing DML after a callout in the same job
Inside a Queueable, the same ordering rule applies. A job may call out and then do DML, which is fine. It may not do DML and then call out. If you must write after each call, collect results in a list and do one DML statement at the end of execute.
public class TodoImportJob implements Queueable, Database.AllowsCallouts {
public void execute(QueueableContext context) {
List<Task> toInsert = new List<Task>();
for (Integer i = 1; i <= 5; i++) {
String body = TodoService.fetchTodo(i);
Map<String, Object> parsed =
(Map<String, Object>) JSON.deserializeUntyped(body);
toInsert.add(new Task(Subject = (String) parsed.get('title')));
}
insert toInsert; // one DML at the end, after all callouts
}
}Other ways around the rule
@future(callout=true): a static method that runs later in its own transaction. It takes only primitive parameters, so pass IDs. Prefer Queueable for new code because it accepts richer data and can be chained.- Platform events: the trigger publishes an event, and a separate subscriber trigger makes the call asynchronously. This decouples the two sides but adds setup.
- Batch Apex with
Database.AllowsCallouts: use it when you must process large volumes.
Common mistakes
- Making a callout in a trigger "because there is no DML before it". The trigger context still blocks it.
- Forgetting
Database.AllowsCalloutson the Queueable or Batch class. - Passing full sObjects into a job and using stale field values.
- Catching
CalloutExceptionand ignoring it. The data silently fails to sync. - Enqueueing one job per record in a bulk update of 200 records.
Exercise
A trigger on Contact (after update) calls TodoService.fetchTodo(1) directly. Name the problem and describe the fix in terms of the Queueable pattern.
Show answer
A synchronous callout from a trigger runs inside the transaction that is saving records, which has uncommitted work, so it fails. The fix is to have the trigger collect the Contact IDs and call System.enqueueJob with a Queueable that implements Database.AllowsCallouts. The job re-queries the records and makes the callout in its own transaction after the original one commits.
Exercise
A Queueable's execute method updates an Account and then calls an external service for each of ten Accounts. How can you rewrite it so it does not throw the uncommitted work error?
Show answer
Do all ten callouts first and hold the results in variables or a list, then run one DML statement at the end of execute. This keeps every callout ahead of any uncommitted work.