Sub topic 1
Transactions and Callout Limits
This chapter assumes you know basic Apex classes, bulkified triggers, governor limits, HTTP, and JSON.
Prerequisites
You should understand that one trigger execution runs inside a Salesforce database transaction. The transaction groups related work so Salesforce can commit it together or roll it back.
Transactions and callout limits
Salesforce limits work per transaction. These governor limits include SOQL queries, DML statements, HTTP callouts, and asynchronous jobs. A transaction can make at most 100 callouts, but other limits also affect the design.
An HTTP callout waits for an external server. If the external server is slow or unavailable, the Salesforce transaction must wait. Holding a database transaction open during that wait can cause locking and consistency problems.
Why a trigger cannot call out directly
A trigger runs synchronously as part of the transaction that inserts or updates records. Salesforce therefore does not allow a trigger to make a synchronous callout directly. Move the callout into asynchronous Apex instead.
The related error, uncommitted work pending, usually means that DML has occurred in the current transaction before code tried to call out. Salesforce cannot safely perform that callout while earlier database changes remain uncommitted.
A quick HTTP callout refresher
HttpRequest describes the request. Http sends it. HttpResponse contains the remote server's result.
HttpRequest request = new HttpRequest();
request.setEndpoint('callout:Billing_API/accounts');
request.setMethod('POST');
request.setHeader('Content-Type', 'application/json');
request.setBody('{"name":"Acme"}');
HttpResponse response = new Http().send(request);
if (response.getStatusCode() < 200 ||
response.getStatusCode() >= 300) {
System.debug(LoggingLevel.ERROR, 'Callout failed');
}Using Named Credentials for the endpoint
A Named Credential stores an endpoint and authentication settings in Salesforce configuration. The callout: prefix lets Apex reference it without embedding a URL, username, or secret in code. Here, Billing_API is the Named Credential name.
Your asynchronous options
- A future method is simple, static, returns
void, and accepts only primitive values or collections of primitives. - Queueable Apex supports a class, a constructor, better monitoring, and finalizers. It is usually the flexible default.
- Batch Apex processes large data sets in separate batches and can perform callouts when it implements
Database.AllowsCallouts.
Exercise
Which asynchronous option is usually the best starting point for a trigger that sends one bulk HTTP request?
Show answer
Queueable Apex, because it supports structured data, monitoring, and callouts with Database.AllowsCallouts.