Sub topic 14
Callouts and the uncommitted work pending error
This chapter assumes you can write Apex classes, run DML, and catch a DmlException. It also assumes you know that DML changes stay uncommitted until the transaction ends. Here you will see how that rule limits callouts.
The error
A callout is a request from Apex to an external web service, such as an HTTP call. Apex does not allow a callout while the transaction holds uncommitted DML. If you try, it throws this error:
System.CalloutException: You have uncommitted work pending. Please commit or rollback before calling out.
The reason is that a callout can take a long time and cannot be undone. Salesforce does not want to hold database locks while it waits for an external system.
A failing example
public class StatusSync {
public static void run() {
insert new Account(Name = 'Acme Sync');
HttpRequest req = new HttpRequest();
req.setEndpoint('https://example.com/status');
req.setMethod('GET');
HttpResponse res = new Http().send(req); // CalloutException
System.debug(res.getStatusCode());
}
}The insert is pending work. The send call fails because the transaction has not committed. The endpoint must also be authorized in Remote Site Settings or a Named Credential.
The order matters, not the number of calls. The reverse sequence works: callouts first, then DML.
Fix 1: callout first
If the DML depends on the response, reorder the code so the callout runs before any DML.
public class StatusSync {
public static void run() {
HttpRequest req = new HttpRequest();
req.setEndpoint('https://example.com/status');
req.setMethod('GET');
HttpResponse res = new Http().send(req);
insert new Account(Name = 'Acme Sync', Description = res.getBody());
}
}Fix 2: separate transactions
Sometimes the DML must happen first. In that case, move the callout into asynchronous Apex, which starts a new transaction. A Queueable class must implement Database.AllowsCallouts to make callouts.
public class StatusCallout implements Queueable, Database.AllowsCallouts {
public void execute(QueueableContext ctx) {
HttpRequest req = new HttpRequest();
req.setEndpoint('https://example.com/status');
req.setMethod('GET');
HttpResponse res = new Http().send(req);
System.debug(res.getStatusCode());
}
}Call System.enqueueJob(new StatusCallout()); after your DML. The job runs after the first transaction commits. A @future(callout=true) method does the same job. The next chapter covers asynchronous transactions in more detail.
Common mistakes
- Putting a callout in a trigger. Triggers run inside a DML transaction, so the callout almost always follows uncommitted work.
- Calling a helper method that makes a callout after you have already run DML in the caller.
- Forgetting
Database.AllowsCalloutson a Queueable or Batch class. The result is a different callout error. - Forgetting that tests cannot make real callouts. They need
Test.setMockwith anHttpCalloutMock.
Exercise
A method inserts a Contact and then calls an external API to fetch a credit score. It throws "You have uncommitted work pending." Give two ways to fix it.
Show answer
(1) Make the callout first, then use the response in the insert, so no DML is pending when the callout runs. (2) Insert the Contact, then enqueue a Queueable class that implements Database.AllowsCallouts (or call a @future(callout=true) method) to make the callout in a separate transaction.