Sub topic 7
Callouts, DML, and triggers
The previous chapters covered how a single callout can fail. This chapter covers a different problem: the transaction around the callout can make it fail, even when the remote service is healthy. It assumes you know that Apex runs each request as a transaction that commits at the end. It also assumes you know what a trigger is and how Queueable jobs are enqueued.
The rule: no callouts with uncommitted work
Apex does not allow a callout while the current transaction holds uncommitted DML. After an insert, update, delete, or upsert, the changes sit in the transaction and are not committed. If you then call Http.send, Apex throws a System.CalloutException:
You have uncommitted work pending. Please commit or rollback before calling out.The rule exists because a callout can hold a transaction open for as long as the timeout allows. Salesforce does not want database locks held across a network wait.
This class triggers the error:
public with sharing class AccountPusher {
public static void markAndPush(Id accountId) {
update new Account(Id = accountId, Description = 'Sending');
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:Orders_API/accounts');
req.setMethod('POST');
req.setHeader('Content-Type', 'application/json');
req.setBody('{"id":"' + accountId + '"}');
req.setTimeout(30000);
// Throws System.CalloutException: uncommitted work pending
new Http().send(req);
}
}This exception is not a transient failure. It happens on every run, so a retry cannot fix it. Treat it as a design bug, not as something to catch.
The fix: make the callout first and the DML last
DML after a callout is fine. Reorder the work so that all callouts finish first, and write the results to the database at the end:
public with sharing class AccountPusher {
public static void pushThenMark(Id accountId) {
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:Orders_API/accounts');
req.setMethod('POST');
req.setHeader('Content-Type', 'application/json');
req.setBody('{"id":"' + accountId + '"}');
req.setTimeout(30000);
String status;
try {
HttpResponse res = new Http().send(req);
status = (res.getStatusCode() >= 200 && res.getStatusCode() < 300)
? 'Synced'
: 'Sync failed: ' + res.getStatusCode();
} catch (System.CalloutException e) {
status = 'Sync failed: ' + e.getMessage();
}
update new Account(Id = accountId, Description = status);
}
}The callout can now fail in any of the ways covered earlier, and the method still records the outcome. If you have several records, collect the results in a list and run one DML statement after the loop. One DML statement is also kinder to the DML limits.
The table below summarizes what is allowed within one transaction.
| Order of operations | Result |
|---|---|
| Callout, then DML | Works |
| Callout, callout, then DML | Works, subject to the callout limits |
| DML, then callout | `CalloutException` for uncommitted work |
| DML, callout, DML | Fails at the callout |
Why a retry needs a fresh transaction
The rule shapes how you build retries. A retry that runs in the same transaction as earlier DML will fail on the first callout. A retry that runs in a new transaction starts clean, which is why Queueable retries work well. Each job execution is its own transaction. You can do the callout first, write results, and finish. The next attempt is another job in another transaction.
A rollback does not give you a way to retry in place, because a rolled-back transaction would also discard your own work. Put the callout in a different transaction instead.
Triggers cannot make synchronous callouts
A trigger runs inside the transaction that fired it, and by definition that transaction has DML in progress, since the trigger exists because of a DML event. For this reason Apex does not support a synchronous callout from a trigger. The error is:
Callout from triggers are currently not supported.To call an external service because a record changed, start asynchronous work from the trigger. The two usual tools are @future(callout=true) and Queueable with Database.AllowsCallouts. For retries, choose Queueable:
- It accepts a constructor with complex arguments, such as a set of IDs and an attempt counter.
- It can enqueue itself again, with a delay.
- It returns a job ID you can monitor.
An @future method accepts only primitive parameters, and it cannot enqueue itself with a delay. Your retry design would have to live somewhere else.
Enqueueing from a trigger
Keep the trigger thin. It collects the IDs and enqueues one job for the whole batch:
trigger AccountSyncTrigger on Account (after insert) {
System.enqueueJob(new AccountSyncJob(Trigger.newMap.keySet()));
}The job re-queries the records and makes the callouts. It does all its DML after the last callout:
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> accounts = [
SELECT Id, Name FROM Account WHERE Id IN :accountIds
];
List<Account> toUpdate = new List<Account>();
for (Account a : accounts) {
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:Orders_API/accounts');
req.setMethod('POST');
req.setHeader('Content-Type', 'application/json');
req.setHeader('Idempotency-Key', a.Id);
req.setBody(JSON.serialize(
new Map<String, Object>{ 'id' => a.Id, 'name' => a.Name }
));
req.setTimeout(30000);
String status;
try {
HttpResponse res = new Http().send(req);
Integer code = res.getStatusCode();
status = (code >= 200 && code < 300)
? 'Synced'
: 'Sync failed: ' + code;
} catch (System.CalloutException e) {
status = 'Sync failed: ' + e.getMessage();
}
toUpdate.add(new Account(Id = a.Id, Description = status));
}
update toUpdate;
}
}Several design choices in this code come from the transaction rules.
- One job per trigger run. A synchronous transaction may enqueue at most 50
Queueablejobs. A trigger that enqueues one job per record would hit that limit on a bulk load of more than 50 records. Pass the whole set of IDs to one job instead. - IDs, not records. The job runs later, so records captured in the trigger may be stale. Re-querying gives it current data.
- Callouts in a loop, DML once at the end. The loop makes only callouts, so the uncommitted-work rule never applies. The single
updatecomes after the last callout. - A limit on callouts per job. One transaction may make at most 100 callouts. If the set of IDs can be large, split it into chunks and enqueue one job per chunk.
- An idempotency key on each request. The job may run again after a failure, so the receiving service needs a way to recognize repeated requests. The next chapters cover this in detail. The record ID works as a simple key here.
The trigger fires on after insert only. The job's own update therefore does not enqueue another job. If your trigger also runs on after update, guard against re-entry. Otherwise the job's status write can start the job again.
What the enqueue does when the transaction rolls back
System.enqueueJob is transactional. Apex queues the job at the point of the call, but it starts only after the enqueuing transaction commits. This has two consequences.
- If the transaction rolls back, because a later trigger throws or a validation rule fails, the job never runs. You will not call the external service about a record that does not exist.
- The job always sees the committed data. The
SELECTinexecutefinds the new records.
Compare this with a synchronous callout made before the DML. The callout side effect happens at once, and the later DML can still fail. The remote system then holds data your org never saved. With enqueue-from-trigger, the external call follows the commit, so that mismatch does not occur.
The reverse mismatch is still possible. The local save commits, and the external call then fails for good. That is what retries and exhausted-retry handling address.
The flow in one picture
Other places the rule appears
Uncommitted work can appear in unexpected places.
- Earlier code in the same transaction. Your callout class may be correct, but a caller can run DML before calling it. The error then surfaces in code that looks fine. Document that the method must be called before any DML, or move the callout into its own job.
- Test methods. Setup DML in a test method, such as inserting records, counts as uncommitted work. A callout later in the same test context throws the same exception. Put the callout inside
Test.startTest()andTest.stopTest(). The block gets a fresh set of limits, and queued jobs run whenstopTestis called. - Chained jobs. If a job updates records and then enqueues the next attempt, that is fine. The enqueue is not a callout. The next job starts its own transaction after the current one commits.
Testing the trigger path
A test for this design inserts the record inside the test block, then checks the result after stopTest:
@IsTest
private class AccountSyncJobTest {
private class OkMock implements HttpCalloutMock {
public HttpResponse respond(HttpRequest req) {
HttpResponse res = new HttpResponse();
res.setStatusCode(200);
res.setBody('{}');
return res;
}
}
@IsTest
static void insertingAccountSyncsAfterCommit() {
Test.setMock(HttpCalloutMock.class, new OkMock());
Test.startTest();
insert new Account(Name = 'Acme');
Test.stopTest();
Account a = [SELECT Description FROM Account LIMIT 1];
Assert.areEqual('Synced', a.Description);
}
}The insert fires the trigger, which enqueues the job. At Test.stopTest() the job runs in its own transaction, so the callout does not conflict with the insert. To test the failure path, swap in a mock that returns a 503 or throws CalloutException, and assert on the Sync failed text.
Common mistakes
- Writing a "Sending" status before the callout. It looks like good bookkeeping, but it breaks the callout. Write the status after, or keep it in memory until the end.
- Enqueueing one job per record in a trigger. It works in a single-record test and fails at 51 records in a bulk operation.
- Passing stale
sObjectvalues to the job. Pass IDs and re-query. - Using
@futurewhen retries are needed.@futurecannot carry an attempt counter or delay itself. - Assuming a rolled-back transaction has run the callout. Enqueued jobs do not run on rollback, but a synchronous callout made earlier has already left the org.
Exercise
A developer's before update trigger on Opportunity calls a helper that does Http.send. In production it fails with "Callout from triggers are currently not supported." The developer proposes wrapping the call in try/catch and ignoring the error. What should they do instead, and what should the replacement job avoid?
Show answer
Move the callout out of the trigger into a Queueable job that implements Database.AllowsCallouts. The trigger should collect the Opportunity IDs and call System.enqueueJob once with the whole set. Ignoring the error is wrong because the failure happens on every run, so the callout would never be made. The job should re-query the records, make all callouts first, and perform DML only once, after the last callout. It should not do DML before a callout, and it should not enqueue one job per record, because a synchronous transaction allows at most 50 enqueued jobs.
Exercise
A Queueable job's execute method updates a record's Status__c to 'Processing', then calls an external API, and throws "You have uncommitted work pending." Rewrite the order of operations so that it works, and say what must happen to the status update.
Show answer
Make the callout first, and then perform the update after it. The status can be set once, after the callout, to reflect the result, such as 'Synced' or 'Failed'. If a 'Processing' marker is truly needed, set it in the code that enqueues the job, before the enqueue, so that the job starts in a fresh transaction after the commit. Inside the job, no DML may run before the last callout.