Sub topic 13
Continuations for long-running callouts
A Continuation lets an Apex method hand a slow external call to the platform and finish. The platform makes the call, then invokes a callback method when the response arrives. This chapter assumes you know the Http classes, Named Credentials, and the synchronous callout limits from earlier chapters. It also assumes you have used @AuraEnabled methods or Visualforce controllers.
Why a Continuation exists
A synchronous callout holds its Apex request thread until the response comes back. Salesforce limits how many synchronous callouts that run longer than five seconds can be active in an org at once. A slow service can exhaust that limit and cause errors for other users.
A Continuation avoids the problem. Your method returns, and its thread is released. The callout runs outside the Apex request, and a second method handles the result. Continuation callouts do not count toward the long-running request limit.
How the flow works
A Continuation in a Lightning controller
public with sharing class SlowTodoController {
@AuraEnabled(continuation=true cacheable=true)
public static Object startRequest() {
Continuation con = new Continuation(40);
con.continuationMethod = 'processResponse';
con.state = 'todo-1';
HttpRequest req = new HttpRequest();
req.setMethod('GET');
req.setEndpoint('callout:Todo_API/todos/1');
con.addHttpRequest(req);
return con;
}
@AuraEnabled(cacheable=true)
public static Object processResponse(List<String> labels, Object state) {
HttpResponse res = Continuation.getResponse(labels[0]);
if (res.getStatusCode() == 200) {
return res.getBody();
}
throw new AuraHandledException('Callout failed with status ' + res.getStatusCode());
}
}The pieces to notice:
new Continuation(40)sets the timeout in seconds. The maximum is 120.continuationMethodnames the callback. It is a string, so a typo fails at run time, not at compile time.addHttpRequestqueues a request and returns a label. A single Continuation can hold up to three requests. The callback receives the labels as aList<String>.stateis any value you want passed to the callback unchanged.Continuation.getResponse(label)returns theHttpResponsefor that label.- The
continuation=trueattribute on@AuraEnabledmarks the start method as one that returns a Continuation. Its declared return type isObject.
The Named Credential still handles authorization, so the callout: prefix works as usual.
Errors inside a callback
Check the status code before you read the body, as in a synchronous call. Continuations add their own status codes for failures that never reached the service:
| Status code | Meaning |
|---|---|
| 2000 | The request timed out. |
| 2001 | The connection failed. |
| 2002 | The response was too large. |
Treat these as errors in your callback, not as valid responses.
Where Continuations do not work
Continuations are tied to a user-facing request. You can start one from a Visualforce controller or a Lightning component Apex method. You cannot start one from a trigger, a Queueable job, a batch job, or a scheduled job. Those contexts already run asynchronously, so use Database.AllowsCallouts there.
Other limits to remember:
- A callback response can be at most 1 MB.
- Up to three callouts per Continuation.
- You cannot perform DML before returning the Continuation, because that would leave uncommitted work.
When to choose one
Use a Continuation when a person is waiting on a screen and the external service takes many seconds. Stay with a plain synchronous callout when the service answers quickly. Use Queueable Apex when nobody is waiting for the result.
Testing
Tests cannot make real callouts, and HttpCalloutMock does not apply to Continuations. Instead, call Test.setContinuationResponse(label, response) with a fake HttpResponse, then call Test.invokeContinuationMethod(controller, continuation) to run the callback.
Exercise
A trigger on Case needs to call a slow external service. A teammate suggests returning a Continuation from the trigger handler. Why won't this work, and what should you use instead?
Show answer
Continuations can only be started from user-facing contexts such as Visualforce controllers and Lightning component Apex methods. A trigger cannot return one. Enqueue a Queueable job that implements Database.AllowsCallouts (or use @future(callout=true)) and make the callout there.
Exercise
In a continuation callback, getStatusCode() returns 2000. What happened, and how should the callback treat it?
Show answer
The request timed out before the service answered. The callback should treat it as an error, for example by throwing an AuraHandledException, and not read the response body as data.