Sub topic 7
Calling out with Queueable Apex
This chapter assumes you can write Apex classes and triggers, know the basic governor limits, and understand HTTP requests and JSON. You have seen why a trigger cannot call out directly. Here you will move the callout into a Queueable job, which is usually the best default for trigger callouts.
What a Queueable job is
Queueable Apex is a class that implements the Queueable interface. You create an instance and pass it to System.enqueueJob. Salesforce runs the execute method later, in its own transaction, as soon as resources are available.
Because the job runs in a separate transaction, the trigger's database work is already committed or finished when the callout happens. The "uncommitted work pending" error does not occur. The job must also opt in to callouts by implementing Database.AllowsCallouts. Without that marker interface, the first Http.send fails with a callout exception.
Compared with a future method, a Queueable job has these advantages:
- It accepts non-primitive members, such as a
Set<Id>, a list of wrapper objects, or custom classes. System.enqueueJobreturns a job Id that you can query inAsyncApexJob.- You can chain another job from inside
execute. - You can attach a Finalizer to handle failures.
The trigger
The trigger stays small. It does no callout and runs no query. It passes the Ids of the inserted accounts to one job.
trigger AccountSyncTrigger on Account (after insert) {
System.enqueueJob(new AccountSyncJob(Trigger.newMap.keySet()));
}The trigger runs after insert, so Trigger.newMap is available and every record already has an Id. In a before insert trigger the records have no Id yet, so there would be nothing to pass.
The trigger enqueues one job per batch, not one per record. A single transaction can enqueue only 50 Queueable jobs, so enqueueing inside a loop would fail on a large data load.
The job
public class AccountSyncJob implements Queueable, Database.AllowsCallouts {
private Set<Id> accountIds;
public AccountSyncJob(Set<Id> accountIds) {
this.accountIds = accountIds;
}
public void execute(QueueableContext ctx) {
System.attachFinalizer(new AccountSyncFinalizer());
List<Account> accounts = [SELECT Id, Name FROM Account WHERE Id IN :accountIds];
List<Map<String, Object>> payload = new List<Map<String, Object>>();
for (Account a : accounts) {
payload.add(new Map<String, Object>{ 'id' => a.Id, 'name' => a.Name });
}
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:Billing_API/accounts');
req.setMethod('POST');
req.setHeader('Content-Type', 'application/json');
req.setTimeout(20000);
req.setBody(JSON.serialize(payload));
HttpResponse res = new Http().send(req);
if (res.getStatusCode() < 200 || res.getStatusCode() >= 300) {
System.debug(LoggingLevel.ERROR, 'Sync failed: ' + res.getStatusCode() + ' ' + res.getBody());
}
}
}Walk through it in order:
- Class declaration.
Queueableprovidesexecute.Database.AllowsCalloutspermits the HTTP request. - Constructor. The job stores the Ids as instance state. Salesforce serializes this state when the job is queued and restores it when the job runs.
- Finalizer.
System.attachFinalizerregisters cleanup code for the end of the job. It must be called once, inexecute, and ideally before anything that can fail. - Re-query. The job reads current field values from the database. It does not trust data captured when the trigger fired.
- Payload. One list of maps becomes one JSON array. The job makes one request for the whole batch.
- Request. The endpoint
callout:Billing_API/accountsuses a Named Credential. Salesforce supplies the base URL and the authentication, so no secrets appear in code.setTimeout(20000)allows 20 seconds. The default is 10 seconds and the maximum is 120. - Status check.
Http.senddoes not throw on a 4xx or 5xx response. The job must read the status code itself.
Limits that apply
The job runs under asynchronous governor limits, which are higher than synchronous ones in some areas.
| Limit | Value |
|---|---|
| Callouts per transaction | 100 |
| Cumulative callout time per transaction | 120 seconds |
| Queueable jobs enqueued from a synchronous transaction | 50 |
| Queueable jobs enqueued from a running Queueable | 1 |
| SOQL queries (asynchronous) | 200 |
| Heap size (asynchronous) | 12 MB |
Check the current Apex Developer Guide for exact figures, because Salesforce adjusts limits between releases. Two limits matter most here. The 100-callout cap means you must batch records into few requests instead of one request per record. The one-child-job rule means a chain is strictly linear: each job may enqueue only one successor.
Common errors
- Missing
Database.AllowsCallouts. The job runs, but the callout throws aSystem.CalloutExceptionsaying callouts are not allowed from this context. Add the interface. - DML before the callout. Inside the job, a DML statement followed by a callout in the same transaction raises the "uncommitted work pending" error again. Do the callout first, then the DML. If you must update records based on the response, do it after
sendreturns. - Enqueueing in a loop. Calling
System.enqueueJobper record hits the 50-job limit on bulk loads. Collect Ids and enqueue once. - Passing sObjects from
Trigger.new. The job may run seconds or minutes later, and by then the saved copy is stale. Pass Ids and re-query, as the example does. - Ignoring the status code. A 500 response does not throw. Without a check, the job finishes as "Completed" even though the sync failed.
- Forgetting the callout limit. A loop that calls
sendonce per account fails past 100 records. Build one payload instead.
Handling failure with a Finalizer
An unhandled exception inside execute ends the job as failed, and nothing else runs. A Finalizer is code that runs after the job ends, whether it succeeded or failed.
public class AccountSyncFinalizer implements Finalizer {
public void execute(FinalizerContext ctx) {
if (ctx.getResult() == ParentJobResult.UNHANDLED_EXCEPTION) {
System.debug(LoggingLevel.ERROR, 'Queueable failed: ' + ctx.getException().getMessage());
}
}
}ctx.getResult() returns SUCCESS or UNHANDLED_EXCEPTION. On failure, ctx.getException() gives the exception. The Finalizer can log the error, write a record to an error object, or enqueue a retry. A Finalizer runs in its own transaction, so it can make a callout only if it also implements Database.AllowsCallouts. Keep retry logic bounded, for example by counting attempts, so a permanent failure does not retry forever.
Avoiding job loops
If the job writes the response back to the same object, an update trigger could enqueue the job again, which updates the records again. Prevent this by limiting what starts the job. In an after update trigger, enqueue only when a field that matters has changed, and never when only the sync-result fields changed. A static Boolean flag also works within one transaction, but each Queueable runs in a new transaction, so the flag resets. Comparing old and new values is the more reliable guard.
Testing the job
Tests cannot make real callouts. You supply a fake response with Test.setMock. Queued jobs run when Test.stopTest() is called, so the assertion belongs after it.
@IsTest
private class AccountSyncJobTest {
private class MockOk implements HttpCalloutMock {
public HttpResponse respond(HttpRequest req) {
HttpResponse res = new HttpResponse();
res.setStatusCode(200);
res.setBody('{}');
return res;
}
}
@IsTest
static void enqueuesAndRunsJobAfterInsert() {
Test.setMock(HttpCalloutMock.class, new MockOk());
Test.startTest();
insert new Account(Name = 'Acme');
Test.stopTest();
Integer completed = [
SELECT COUNT() FROM AsyncApexJob
WHERE JobType = 'Queueable' AND ApexClass.Name = 'AccountSyncJob' AND Status = 'Completed'
];
System.assertEquals(1, completed, 'The Queueable job should have run');
}
}Test.startTest() gives the code under test a fresh set of limits. Test.stopTest() forces all queued asynchronous work to finish. If you forget Test.setMock, the job fails with "Methods defined as TestMethod do not support Web service callouts". Add a second mock returning status 500 to cover the failure path.
Exercise
A developer's Queueable job updates Account records and then calls an external service. The job fails with "You have uncommitted work pending". What is the cause, and how do you fix it?
Show answer
The job performed DML before the callout in the same transaction, and Salesforce does not allow a callout while uncommitted changes exist. Reorder the code so the callout happens first and the DML runs after the response is received. If the order cannot change, move the DML into a separate Queueable job.
Exercise
Why does the trigger pass Trigger.newMap.keySet() to the job instead of Trigger.new, and why does it enqueue the job once instead of once per record?
Show answer
Ids are small, and the job re-queries them, so it sees current data instead of a stale copy taken when the trigger fired. Enqueueing once avoids the limit of 50 jobs per synchronous transaction and lets the job send one bulk request.