Sub topic 2
Why a trigger cannot call out directly
This chapter assumes you can write a basic Apex trigger, know what a governor limit is, and have seen an HTTP request and a JSON body. You will learn why a callout inside a trigger fails and what the error message means. The fix comes in later chapters.
What happens when you try
Here is a trigger that calls an external service directly. It looks reasonable, but it does not work.
trigger AccountSyncTrigger on Account (after insert) {
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:Billing_API/accounts');
req.setMethod('POST');
req.setHeader('Content-Type', 'application/json');
req.setBody(JSON.serialize(Trigger.new));
HttpResponse res = new Http().send(req);
System.debug('Status: ' + res.getStatusCode());
}When an account is inserted, the callout throws a System.CalloutException:
System.CalloutException: You have uncommitted work pending. Please commit or rollback before calling outThe working model: one open transaction
A trigger runs inside the same database transaction as the DML statement that fired it. In an after insert trigger, the new rows are written to the database, but they are not committed. Salesforce commits only when the whole transaction finishes without an unhandled error. If something fails, it rolls everything back.
A callout is different. It crosses the network to a system that Salesforce does not control. That system may take seconds to answer, and it cannot take part in a rollback.
Salesforce therefore blocks the combination. While a transaction holds uncommitted changes, it cannot start a callout. Two reasons drive this rule:
- Locks. The transaction holds row locks while it waits. A slow external server would keep those locks open and block other users and processes.
- Consistency. If the callout succeeded and the transaction then rolled back, the external system would hold data that no longer exists in Salesforce. Salesforce cannot undo the external call.
Reading the error message
The text "uncommitted work pending" means the current transaction has run DML and has not yet committed. Any DML before the callout can cause it, not only the DML that fired the trigger. Apex enforces the rule at runtime, so the code compiles and fails only when it runs.
The error also appears in these cases:
- A trigger fires on a DML statement, and the callout is in a helper class that the trigger calls.
- A method inserts or updates a record and then makes a callout in the same transaction.
- Code that called out successfully earlier in the transaction is later changed to run DML first.
Doing the callout before any DML in a transaction is allowed. A trigger cannot use that ordering, because the DML that fired it has always happened first.
Why you cannot work around it
Some developers try to avoid the error with a try/catch block or by calling out earlier. A try/catch does not help, because the exception is raised by the platform before the request is sent. Moving the callout to another class does not help either, because the transaction is the same.
The callout must run in a different transaction. That means asynchronous Apex. The trigger records the work that needs doing and returns quickly. After the original transaction commits, Salesforce starts a separate job that is allowed to call out.
Exercise
A developer writes an after update trigger that updates a related Contact with DML and then calls an external API from the same trigger. Why does it fail, and what is the general fix?
Show answer
The trigger runs in a transaction that has uncommitted DML, so Salesforce throws a CalloutException saying there is uncommitted work pending. A try/catch cannot fix it. The general fix is to move the callout into asynchronous Apex, such as a future method or a Queueable job, which runs in a separate transaction after the first one commits.