Sub topic 11
Running callouts asynchronously
This chapter assumes you can write basic Apex classes and triggers, know what a governor limit is, and have already built a request with Http, HttpRequest and HttpResponse. Here you will move a callout out of the current transaction and into asynchronous Apex.
Why callouts move to async
Two rules push callouts out of the main transaction:
- A callout is not allowed after uncommitted DML in the same transaction. Salesforce raises "You have uncommitted work pending."
- Callouts are not allowed directly from a trigger, because the trigger runs synchronously while the user waits.
Asynchronous Apex solves both problems. The platform runs your code later in a new transaction, after the original work is committed. That new transaction can make the callout.
Queueable Apex with Database.AllowsCallouts
A Queueable class runs asynchronously. To make callouts, it must also implement Database.AllowsCallouts. Without that marker interface, the callout fails at runtime.
public class TodoSyncJob implements Queueable, Database.AllowsCallouts {
private Integer todoId;
public TodoSyncJob(Integer todoId) {
this.todoId = todoId;
}
public void execute(QueueableContext context) {
String body = TodoService.fetchTodo(todoId);
System.debug('Fetched todo: ' + body);
}
}
// Enqueue from a trigger handler or other synchronous code:
// System.enqueueJob(new TodoSyncJob(1));The constructor carries the input. Queueable classes can hold member variables, including sObjects and custom types, so you can pass whatever the callout needs. The job calls TodoService.fetchTodo, which uses the Named Credential and checks the status code.
The @future alternative
An older option is a static method annotated @future(callout=true).
public class TodoFuture {
@future(callout=true)
public static void syncTodo(Integer todoId) {
String body = TodoService.fetchTodo(todoId);
System.debug('Fetched todo: ' + body);
}
}Future methods have tighter rules. They must be static and return void. Their parameters must be primitives or collections of primitives, not sObjects or custom classes. You also cannot chain one future method from another.
| Feature | Queueable | @future |
|---|---|---|
| Callout support | Implement `Database.AllowsCallouts` | `callout=true` |
| Parameter types | Any, including objects | Primitives and collections of primitives |
| Job Id returned | Yes, from `System.enqueueJob` | No |
| Chaining | Yes, from `execute` | No |
Prefer Queueable for new code. Use @future when its simplicity is enough and you only need to pass an Id or a string.
Things to watch
- No guaranteed timing. The job runs when the platform has capacity. Do not write code that expects the result immediately.
- Callout limits still apply. Each asynchronous transaction has its own limit of 100 callouts, but the cumulative timeout rules still apply.
- Chaining. A Queueable can enqueue one more job from
execute. This is useful for processing a list one item at a time, but each job should stay within limits. - Failures are silent to the user. An uncaught exception ends the job and shows up in Apex Jobs and debug logs. Catch errors in
executeand record them, for example in a custom log object. - Tests. Callouts in async code still need a mock. Call
Test.setMock, then run the code betweenTest.startTest()andTest.stopTest(). The job runs whenTest.stopTest()is called.
Exercise
A trigger on Account must call an external service after each insert. Calling the service directly in the trigger fails. Which approach works, and what must the class include for callouts to be allowed?
Show answer
Enqueue a Queueable job from the trigger handler with System.enqueueJob. The Queueable class must implement Database.AllowsCallouts in addition to Queueable. The job then runs in a new transaction after the insert is committed, so the callout is allowed.
Exercise
You need to pass a list of custom Todo objects to an asynchronous callout. Why is @future(callout=true) a poor fit, and what do you use instead?
Show answer
Future methods accept only primitives and collections of primitives as parameters, so you cannot pass custom objects. Use a Queueable class that stores the objects in member variables set through its constructor.