Sub topic 11
Running callouts asynchronously
This chapter assumes you can already send a request with Http, use a Named Credential, and read the callout limits and the uncommitted work rule from the earlier chapters. It covers moving a callout out of the user's transaction with Queueable Apex or @future(callout=true). It also covers how to design those jobs so they stay inside the limits.
Why callouts move to the background
A synchronous callout blocks the transaction that made it. Two platform rules make that a problem:
- Apex throws
System.CalloutException: You have uncommitted work pendingif you make a callout after DML in the same transaction and before it commits. A trigger always runs inside a DML transaction, so a callout made directly from trigger code fails or leaves the user waiting on a slow service. - The transaction holds a database connection and the user's request while it waits for the remote server. A slow API makes record saves slow.
An asynchronous job runs later in its own transaction. It starts with no uncommitted work, and the user's save has already finished. The job can make callouts as long as it is marked as allowed to.
Queueable Apex with callouts
A Queueable class implements Queueable. To make callouts it must also implement the marker interface Database.AllowsCallouts. Without the marker, the first send() throws a CalloutException.
This job creates a todo in the external API for each new Case. It does all of its callouts first and its DML last, so it never hits the uncommitted work error. It also processes at most 50 Cases per run and chains a new job for the rest.
public class CaseTodoJob implements Queueable, Database.AllowsCallouts {
private static final Integer SLICE_SIZE = 50;
private List<Id> caseIds;
public CaseTodoJob(List<Id> caseIds) {
this.caseIds = caseIds;
}
public void execute(QueueableContext context) {
List<Id> current = new List<Id>();
List<Id> remaining = new List<Id>();
for (Integer i = 0; i < caseIds.size(); i++) {
if (i < SLICE_SIZE) {
current.add(caseIds[i]);
} else {
remaining.add(caseIds[i]);
}
}
List<Case> toUpdate = new List<Case>();
for (Case c : [SELECT Id, Subject FROM Case WHERE Id IN :current]) {
TodoClient.Todo todo = new TodoClient.Todo();
todo.userId = 1;
todo.title = c.Subject;
todo.completed = false;
try {
TodoClient.Todo created = TodoClient.create(todo);
toUpdate.add(new Case(Id = c.Id, Description = 'Todo ' + created.id));
} catch (CalloutException e) {
System.debug(LoggingLevel.ERROR, 'Todo sync failed for ' + c.Id + ': ' + e.getMessage());
}
}
if (!toUpdate.isEmpty()) {
update toUpdate;
}
if (!remaining.isEmpty() && !Test.isRunningTest()) {
System.enqueueJob(new CaseTodoJob(remaining));
}
}
}The trigger stays small. It collects the IDs and enqueues one job per trigger invocation, not one per record:
trigger CaseTrigger on Case (after insert) {
List<Id> ids = new List<Id>(new Map<Id, Case>(Trigger.new).keySet());
System.enqueueJob(new CaseTodoJob(ids));
}Design points
- Pass IDs, not records. The job runs later, and the data may have changed. Re-query inside
executeto get current values. - Constructor state must be serializable. Member variables are saved with the queued job. Primitives, collections, sObjects and your own classes work. Non-serializable members such as
Httpinstances do not, unless you mark themtransient. - One job per transaction, not per record. A synchronous transaction can enqueue up to 50 Queueable jobs. A trigger that handles 200 records and enqueues a job for each fails at the 51st.
- Callouts first, DML last. Inside the job the same uncommitted work rule applies. If you update a record and then call out in a loop, the second iteration fails.
- Catch per record. One failing call should not discard the work for the other 49 records. Here the
catchblock logs and moves on.
Chaining jobs
A running Queueable can enqueue exactly one more job. This is how the example above handles large inputs: each job stays well below the 100-callouts-per-transaction limit, and the chain covers the rest. Chaining is also the way to run steps in order, for example when the second call needs a value returned by the first.
Be careful with chains that never end. If a job always enqueues a successor, for example because a failed record is retried without a counter, the chain runs forever and eats into your daily async execution allowance. Carry a retry count in the constructor and stop at a fixed maximum.
In Apex tests, only the first job of a chain runs, and enqueueing a second job from within a test can throw a stack depth error. The !Test.isRunningTest() guard in the example avoids that. A more targeted alternative is System.AsyncInfo.hasMaxStackDepth().
@future(callout=true)
@future is the older mechanism. The annotation needs callout=true to allow callouts:
public class TodoFuture {
@future(callout=true)
public static void fetch(Integer todoId) {
String body = TodoService.fetchTodo(todoId);
System.debug('Fetched todo: ' + body);
}
}The restrictions are tighter than for Queueable:
- The method must be
staticand returnvoid. - Parameters must be primitives or collections of primitives. You cannot pass an sObject or a custom class, so you pass IDs and re-query.
- You cannot chain. A future method cannot call another future method, and you cannot call one from a Batch job.
- You get no job ID back, so you cannot monitor or abort the call.
- Up to 50 future calls are allowed per transaction.
Choosing between them
| Concern | Queueable | @future(callout=true) |
|---|---|---|
| Marker needed | `Database.AllowsCallouts` | `callout=true` |
| Parameters | Any serializable state | Primitives and collections of primitives |
| Job ID returned | Yes, from `System.enqueueJob` | No |
| Chaining | One child job per execution | Not allowed |
| Limit on calls per transaction | 50 jobs | 50 calls |
| Where a new one is written | New code | Mostly legacy code |
Use Queueable for new work. Keep @future when you maintain existing code that already works and has simple primitive inputs. For very large record sets, Batch Apex with Database.AllowsCallouts on the batch class splits the work into scopes. Each execute has its own callout budget, so it is the better fit for thousands of records.
Handling failures you cannot see
The user is gone by the time the job runs, so there is nobody to show an error to. Plan for that:
- Catch
CalloutExceptionand check the status code per call, as you learned in the error handling chapter. - Record the outcome on the record itself, for example a status field or a log record. This is a separate DML step, done after all callouts.
- Treat 5xx statuses and timeouts as retryable and 4xx statuses as permanent. Re-enqueue only the retryable ones, with a retry counter.
- An uncaught exception ends the job with a failed status in Setup under Apex Jobs. Transaction Finalizers (
System.attachFinalizer) let you run cleanup or re-enqueue logic even after an unhandled exception.
Testing an async callout
Async jobs run in tests when Test.stopTest() is called. Everything enqueued between startTest() and stopTest() executes at that point, so your assertions go after stopTest(). A mock is still required, because tests cannot make real callouts. The next chapter covers mocks in full; this one is the minimum.
@isTest
private class CaseTodoJobTest {
private class CreatedMock implements HttpCalloutMock {
public HttpResponse respond(HttpRequest req) {
HttpResponse res = new HttpResponse();
res.setStatusCode(201);
res.setHeader('Content-Type', 'application/json');
res.setBody('{"id":201,"userId":1,"title":"Printer broken","completed":false}');
return res;
}
}
@isTest
static void jobWritesTodoIdToCase() {
Test.setMock(HttpCalloutMock.class, new CreatedMock());
Test.startTest();
Case c = new Case(Subject = 'Printer broken');
insert c;
Test.stopTest();
Case reloaded = [SELECT Description FROM Case WHERE Id = :c.Id];
System.assertEquals('Todo 201', reloaded.Description);
}
}The insert fires CaseTrigger, which enqueues the job. Test.stopTest() runs it against the mock, and the final query sees the updated Case.
Common mistakes
- Forgetting
Database.AllowsCalloutson a Queueable. The job runs and fails at the firstsend(). - Forgetting
callout=trueon@future. The same failure. - Enqueueing one job per record inside a loop in a trigger. This breaks on bulk loads at the 50-job limit.
- Passing sObjects to a future method. This does not compile, because only primitives are allowed.
- Performing DML inside a loop before the next callout. This brings back the uncommitted work error inside the job.
- Asserting before
Test.stopTest(). The job has not run yet, so the assertion sees the old data.
Exercise
A trigger on Case (after insert) loops over Trigger.new and calls System.enqueueJob(new CaseTodoJob(c.Id)) for each record. A data load inserts 200 Cases in one batch. What happens, and how do you fix it?
Show answer
The transaction enqueues 200 jobs, but a synchronous transaction may enqueue at most 50, so it fails with a limit exception around the 51st call and the whole insert rolls back. Fix it by collecting all the IDs and enqueuing a single job with a List<Id>. The job then processes the IDs in slices and chains a new job for any remainder.
Exercise
A Queueable job updates a Case and then, inside the same loop iteration, calls an external API for the next Case. The first iteration works and the second throws "You have uncommitted work pending". Why, and what is the fix?
Show answer
The update in the first iteration is uncommitted DML, and a callout is not allowed while uncommitted work exists in the transaction. Reorder the code so that all callouts run first and the results are stored in a collection, then run a single DML statement after the loop.