Sub topic 2
Why a Trigger Cannot Call Out Directly
This chapter assumes you can write and bulkify Apex triggers, know the basic governor limits, and understand HTTP requests and JSON. It explains the rule that stops a trigger from calling an external service, the error you see when you break it, and the shape of the fix. The later chapters build the fix in detail.
The problem in one example
Suppose you want to send each new account to a billing system. The obvious first attempt is a callout inside the trigger.
trigger AccountSyncTrigger on Account (after insert) {
for (Account a : Trigger.new) {
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:Billing_API/accounts');
req.setMethod('POST');
req.setHeader('Content-Type', 'application/json');
req.setBody(JSON.serialize(new Map<String, Object>{ 'id' => a.Id, 'name' => a.Name }));
HttpResponse res = new Http().send(req);
}
}This code does not work. It fails in one of two ways, and both come from the way Salesforce runs a transaction.
What a transaction is
A transaction is one unit of work that Salesforce either saves completely or undoes completely. When a user saves a record, the platform starts a transaction. It runs your before triggers, validation rules, after triggers, workflow and flow automation, and then commits the changes to the database. If any step throws an unhandled exception, everything is rolled back.
While the transaction runs, the database holds locks on the rows it has changed. Other users and processes that want to change those rows must wait until the transaction ends.
What a callout is
A callout is a request your Apex code sends to a system outside Salesforce, usually over HTTP. A callout has three properties that matter here:
- It takes an unpredictable amount of time. The remote server may answer in 100 milliseconds or fail to answer at all.
- It cannot be rolled back. If the remote system accepted your request, Salesforce cannot undo that.
- It happens outside the transaction's control. The remote server could be slow, down, or overloaded.
Why the two do not mix
Put the two together and the rule becomes clear. If a trigger could make a callout, Salesforce would have to keep the database locks open for as long as the remote server takes to answer. A slow server would block every user who needs those rows. Many such transactions at once could exhaust the platform's resources.
There is also a consistency problem. Suppose the trigger calls the billing system, the billing system accepts the account, and then a later trigger throws an exception. Salesforce rolls back the account, but the billing system still has it. The two systems now disagree, and Salesforce has no way to fix that.
Salesforce prevents both problems with one rule: a callout cannot be made while the transaction has uncommitted work pending. In practice, this means you cannot make a callout after a DML statement in the same transaction, until the transaction ends.
The error you will see
You can break the rule in two ways.
- A callout after DML. Your code inserts or updates a record and then makes a callout in the same transaction. Salesforce throws a
System.CalloutExceptionwith the messageYou have uncommitted work pending. Please commit or rollback before calling out. - A callout inside a trigger context. A trigger always runs as part of a DML operation. By the time your trigger code runs, the platform has uncommitted work, so the same error appears. In some cases the trigger fails to save instead, and the error is reported on the record.
The following snippet shows the first case outside a trigger. It is easy to reproduce in anonymous Apex.
insert new Account(Name = 'Acme');
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:Billing_API/accounts');
req.setMethod('GET');
HttpResponse res = new Http().send(req); // throws CalloutExceptionThe order matters. A callout followed by DML is allowed, because at the time of the callout nothing is pending. DML followed by a callout is not.
| Order in one transaction | Allowed? | Reason |
|---|---|---|
| Callout, then DML | Yes | Nothing is uncommitted when the callout runs. |
| DML, then callout | No | Uncommitted work is pending at the callout. |
| Callout inside a trigger | No | A trigger always runs inside a DML operation. |
Limits that apply to callouts
Even where a callout is allowed, it is subject to limits. These are per transaction.
| Limit | Value |
|---|---|
| Callouts per transaction | 100 |
| Timeout per callout (default) | 10 seconds |
| Timeout per callout (maximum) | 120 seconds |
| Cumulative timeout for all callouts | 120 seconds |
| Request or response size | 6 MB synchronous, 12 MB asynchronous |
The 100-callout limit matters for bulk work. A trigger can receive up to 200 records at once. If you made one callout per record, you would hit the limit at record 101. The cumulative timeout also matters: 100 callouts that each take two seconds would exceed it. Two points follow for design. Send many records in one request where the remote API supports it, and set an explicit timeout with setTimeout so a slow server does not use your whole budget.
Check the current values in the Salesforce documentation before you rely on them, since limits can change between releases.
Why you cannot just "reorder" in a trigger
A common idea is to make the callout first and do the DML afterward. This does not help in a trigger, because the trigger itself runs after the platform has begun the DML that fired it. You do not control the order. There is also no supported way to commit early in the middle of a transaction.
Another idea is to catch the exception and carry on. That hides the error but the callout still does not happen, so the integration silently does nothing.
The fix: move the callout out of the transaction
The approach is to let the trigger finish its transaction and run the callout later, in a separate transaction. This is asynchronous Apex. The trigger only schedules the work. Salesforce runs the work afterward, in a new transaction with a clean slate, where a callout is allowed.
The trigger from the spine of this tutorial does exactly that. It does no callout. It enqueues one job for the whole batch and passes only the record Ids.
trigger AccountSyncTrigger on Account (after insert) {
System.enqueueJob(new AccountSyncJob(Trigger.newMap.keySet()));
}The job runs after the first transaction commits. In its own transaction, it can query the records and call the external service.
This design has consequences you should plan for:
- The user does not wait. The save returns as soon as the first transaction commits.
- The result is not available to the trigger. The trigger cannot read the response or add an error to the record based on it. If the callout fails, the record is already saved.
- Failures need their own handling. Because the callout runs separately, you must log failures, retry, or notify someone. Later chapters cover this.
- The data may have changed. Between the commit and the job running, someone could edit the record. This is why you pass Ids and query fresh data.
Common mistakes
- Calling out from a before trigger and assuming it is safe. A before trigger also runs inside a DML operation. Do not make callouts there either.
- Wrapping the callout in a helper class. Moving the code to another class does not change the transaction. The restriction applies to the whole transaction, not to the file.
- Testing with a real endpoint. Tests cannot make real callouts. You will need a mock, which a later chapter covers.
- One async job per record. This hits the limit on jobs a transaction can enqueue. Enqueue one job per trigger invocation and handle all records in it.
What comes next
You now know why the callout must leave the trigger transaction. The next chapters review the HTTP callout classes, set up a Named Credential, and then compare the async tools you can use: future methods, Queueable Apex and Batch Apex.
Exercise
A developer's after-update trigger calls new Http().send(req) for each record. The developer then moves the callout into a helper class that the trigger calls, and the same error appears. Why does moving the code not help, and what should the developer do instead?
Show answer
The restriction applies to the transaction, not to a particular class. The trigger runs inside a DML operation, so uncommitted work is pending whichever class makes the callout, and Salesforce throws a CalloutException ("You have uncommitted work pending"). The developer should have the trigger enqueue one asynchronous job (for example a Queueable that implements Database.AllowsCallouts) and pass the record Ids. The job runs in a new transaction after the first one commits, and it makes the callout there.
Exercise
In a single transaction, code makes a callout to a pricing service, then inserts a record. A second block of code inserts a record, then makes a callout. Which one fails, and why?
Show answer
The second one fails. In the first block nothing is uncommitted when the callout runs, so it is allowed. In the second block the insert leaves uncommitted work pending, so the callout throws a CalloutException.