Sub topic 14
Callouts and the Uncommitted Work Pending Error
This chapter assumes you know how Apex groups DML into a transaction, and how a caught exception differs from an unhandled one. It also assumes you have made an HTTP callout from Apex before. The chapter covers why a callout fails after DML, how to restructure code to avoid the failure, and how to test the fix.
The error
Apex holds database changes open until the transaction ends. If your code makes a callout after DML, Apex rejects it with this exception:
System.CalloutException: You have uncommitted work pending. Please commit or rollback before calling out.A callout is a request to a system outside Salesforce. That includes an HTTP request through Http.send, a SOAP web service call, and a call through a named credential. The error appears at the callout, not at the DML. The DML itself succeeded in the sense that it did not throw. The platform refuses to open the outbound connection while changes are still uncommitted.
This is a transaction-boundary rule. It follows from what you learned about boundaries: nothing is committed until the transaction finishes, and Apex cannot undo a callout once it has been sent.
Why the platform blocks it
A transaction can be rolled back, but an external system cannot. Suppose Apex inserted an Account, called a billing service, and then hit an unhandled exception. Salesforce would roll back the Account. The billing service would still have processed the request, and the two systems would disagree.
Blocking callouts while changes are pending also keeps database locks short. A callout can take seconds. Holding row locks for that long would make other transactions wait.
The restriction is one-directional:
| Order of operations | Result |
|---|---|
| Callout, then DML | Allowed |
| DML, then callout | `CalloutException` |
| Callout, DML, then another callout | The second callout fails |
| Several callouts, then several DML statements | Allowed |
So the rule is not "callouts and DML cannot share a transaction." The rule is that once any DML has run, no more callouts are allowed in that transaction.
A failing example
This method inserts a record and then calls an external service. The endpoint uses a named credential called Billing, which you would need to define in your org.
public class BadAccountSync {
public static void createAndNotify() {
insert new Account(Name = 'Acme');
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:Billing/accounts');
req.setMethod('POST');
req.setBody('{"name":"Acme"}');
// Throws System.CalloutException: uncommitted work pending
HttpResponse res = new Http().send(req);
}
}The bug is often less visible than this. The DML may happen in a trigger, a flow, or a helper method several calls earlier. The callout may sit in a service class that looks harmless. Any DML earlier in the same transaction counts, so when you see this error, trace back through everything that ran before the callout.
Fix 1: Make the callout first
If the callout does not depend on the DML, reorder the code so the callout runs before any DML.
public class GoodAccountSync {
public static void notifyAndCreate() {
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:Billing/accounts');
req.setMethod('POST');
req.setBody('{"name":"Acme"}');
HttpResponse res = new Http().send(req);
if (res.getStatusCode() == 200) {
insert new Account(Name = 'Acme');
}
}
}This works when you need the external response before you save. It fits poorly when the callout needs data that DML produces, such as a new record Id.
Fix 2: Move the callout to asynchronous Apex
When the callout needs the saved record, split the work into two transactions. The first saves the data. The second runs later and makes the callout. Queueable Apex is the usual choice. The class must implement Database.AllowsCallouts, or the callout is rejected.
public class BillingSync implements Queueable, Database.AllowsCallouts {
private Id accountId;
public BillingSync(Id accountId) {
this.accountId = accountId;
}
public void execute(QueueableContext ctx) {
Account a = [SELECT Id, Name FROM Account WHERE Id = :accountId];
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:Billing/accounts');
req.setMethod('POST');
req.setBody(JSON.serialize(new Map<String, Object>{
'id' => a.Id,
'name' => a.Name
}));
HttpResponse res = new Http().send(req);
if (res.getStatusCode() == 200) {
a.Description = 'Synced to billing';
update a; // DML after the callout is allowed
}
}
}The caller then saves first and enqueues the job:
Account a = new Account(Name = 'Acme');
insert a;
System.enqueueJob(new BillingSync(a.Id));The queued job starts in a new transaction after the first one commits. That has two consequences you should plan for:
- If the first transaction rolls back, the job is not enqueued. Enqueuing is part of the transaction. This is the behavior you want, because the external system is never told about a record that does not exist.
- If the callout fails, the
Accountis already committed. You need your own retry or error-recording logic. A rollback in the original transaction cannot help.
Other asynchronous options
| Option | How it allows callouts | Notes |
|---|---|---|
| Queueable | Implement `Database.AllowsCallouts` | Can pass sObjects and other complex types |
| `@future` | Annotate with `@future(callout=true)` | Parameters must be primitives or collections of primitives |
| Batch Apex | Implement `Database.AllowsCallouts` on the batch class | Each `execute` call is its own transaction |
Batch Apex has a trap of its own. Each execute call is a separate transaction, so DML followed by a callout inside the same execute fails in the same way. Do the callouts at the start of execute, or put them in a different job.
What about savepoints and rollback?
The error message says "commit or rollback," which suggests that Database.rollback might clear the pending state. Do not build a design around that. A rollback discards your DML, so any record you needed the callout to see no longer exists. Reordering the work or moving the callout to a separate transaction is clearer and does not depend on platform details.
A related point: the callout itself is not undone by a rollback. If you make a callout and then roll back, the external system still received the request. Treat the callout as the last irreversible step. Put validation and local DML work first where you can, and design the external call to be safe to repeat, for example by sending an idempotency key.
Diagnosing the error
Work through these questions when you see the exception:
- Which statement made the callout? The stack trace points to it.
- What DML ran earlier in this transaction? Check the call stack, triggers on the object you saved, and any flows or processes that fire on the same save.
- Can the callout move before the DML? If so, do that.
- If the callout needs the saved data, can it run in a queueable job or a
@future(callout=true)method?
Testing the fix
Tests cannot make real callouts. You must register a mock that implements HttpCalloutMock.
@IsTest
private class BillingCalloutMock implements HttpCalloutMock {
public HttpResponse respond(HttpRequest req) {
HttpResponse res = new HttpResponse();
res.setStatusCode(200);
res.setBody('{"ok":true}');
return res;
}
}Asynchronous jobs only run inside a test when you wrap them in Test.startTest() and Test.stopTest(). The job runs when stopTest is called.
@IsTest
private class BillingSyncTest {
@IsTest
static void syncMarksAccount() {
Account a = new Account(Name = 'Acme');
insert a;
Test.setMock(HttpCalloutMock.class, new BillingCalloutMock());
Test.startTest();
System.enqueueJob(new BillingSync(a.Id));
Test.stopTest();
Account result = [SELECT Description FROM Account WHERE Id = :a.Id];
System.assertEquals('Synced to billing', result.Description);
}
}Test setup DML followed by a callout in the same test method can also trigger the pending-work error. Doing the callout inside the startTest/stopTest block, as above, avoids it, because the queued job runs in its own transaction.
Summary of the rules
- DML followed by a callout in one transaction throws
CalloutException. - Callouts before DML are allowed, and several callouts in a row are allowed.
- Rollback does not recall a callout that was already sent.
- Use queueable,
@future(callout=true), or batch withDatabase.AllowsCalloutsto separate the two. - An async job enqueued in a transaction that rolls back is never enqueued.
Exercise
A trigger on Opportunity updates a related Account. Later in the same transaction, a service class that the trigger calls makes an HTTP callout, and it fails with "You have uncommitted work pending." The callout needs the Opportunity Id, which exists before the trigger runs. Name two ways to fix this, and say which one risks leaving the external system out of sync if the Opportunity save later fails.
Show answer
Fix 1: make the callout earlier, before any DML in the transaction. The Opportunity Id is already known, so the callout can run first. This risks the external system being out of sync, because the callout is sent and cannot be undone if the Opportunity save fails later. Fix 2: enqueue a Queueable that implements Database.AllowsCallouts, so the callout runs in a new transaction after commit. The job is not enqueued if the original transaction rolls back, so this keeps the two systems in step.
Exercise
A batch class's execute method inserts a log record and then calls an external service. Why does it fail, and what is the smallest change that fixes it?
Show answer
Each execute call is one transaction, so the insert leaves uncommitted work and the callout then throws a CalloutException. The smallest fix is to make the callout before the insert inside execute. The class must also implement Database.AllowsCallouts so callouts are permitted at all.