Sub topic 13
Continuations for long-running callouts
This chapter assumes you can already write a synchronous callout with Http, HttpRequest and HttpResponse, and that you know the callout limits from earlier in the tutorial. It covers the one tool in this tutorial that is built for slow external services: the Continuation class.
The problem a Continuation solves
A normal callout holds an Apex thread until the remote server answers. Salesforce limits how many synchronous requests that run longer than five seconds can be active at once. If a user-facing page calls a slow service, a few users can use up that allowance for the whole org, and other requests then fail.
A Continuation changes the order of work:
- Your Apex method builds the requests and returns a
Continuationobject. The Apex transaction ends. - The platform sends the requests and waits for them. Nothing in your org is held while it waits.
- When the responses arrive (or the timeout is reached), the platform starts a new transaction and calls your callback method.
Callouts made this way do not count against the limit on concurrent long-running requests. That makes a Continuation the right choice when a user is waiting on a screen and the service might take many seconds.
When to choose a Continuation
A Continuation is not a general replacement for asynchronous Apex. It only works from an action that a user interface starts.
| Need | Best fit |
|---|---|
| Callout after DML, or from a trigger | Queueable with `Database.AllowsCallouts` |
| Fire-and-forget work with no screen waiting | Queueable or `@future(callout=true)` |
| A Lightning component or Visualforce page waits for a slow service | Continuation |
| Several independent slow calls to run in parallel for one page | Continuation (up to 3 requests) |
Do not try to start a Continuation from a trigger, a Queueable job or a batch job. It needs a user-interface action that can receive the returned Continuation object.
Anatomy of a Continuation
A Continuation involves two methods and a few properties.
new Continuation(timeoutInSeconds)creates the object. The timeout can be at most 120 seconds.continuationMethodis the name of the callback method, as a string.addHttpRequest(req)adds a request and returns a label, a string that identifies that request. You can add up to three requests to one Continuation.stateholds any value you want to carry into the callback. The platform keeps it for you, because static variables do not survive between the two transactions.Continuation.getResponse(label)returns theHttpResponsefor a label inside the callback.
The sequence below shows who does what.
A complete example for Lightning Web Components
The controller below uses the Todo_API Named Credential from earlier chapters. Both methods are static and marked @AuraEnabled. The first one has continuation=true, which tells the platform that it returns a Continuation.
public with sharing class TodoContinuationController {
@AuraEnabled(continuation=true cacheable=true)
public static Object startRequest(Integer todoId) {
Continuation con = new Continuation(40);
con.continuationMethod = 'processResponse';
con.state = todoId;
HttpRequest req = new HttpRequest();
req.setMethod('GET');
req.setEndpoint('callout:Todo_API/todos/' + todoId);
req.setHeader('Accept', 'application/json');
con.addHttpRequest(req);
return con;
}
@AuraEnabled
public static Object processResponse(List<String> labels, Object state) {
HttpResponse res = Continuation.getResponse(labels[0]);
Integer status = res.getStatusCode();
if (status != 200) {
throw new AuraHandledException(
'Todo ' + state + ' failed with status ' + status
);
}
return res.getBody();
}
}Points to notice:
- The return type of
startRequestisObject, notContinuation. The platform needs this signature. - The callback receives
List<String> labelsandObject state. The labels are in the order you added the requests, solabels[0]is the first request. - The callback's return value goes back to the component, as if
startRequesthad returned it. The component never sees theContinuation. cacheable=trueis required on the method that returns the Continuation, so the method must not perform DML.
The component calls the method like any other Apex method.
import { LightningElement } from 'lwc';
import startRequest from '@salesforce/apex/TodoContinuationController.startRequest';
export default class TodoViewer extends LightningElement {
todo;
error;
async handleLoad() {
this.error = undefined;
try {
const body = await startRequest({ todoId: 1 });
this.todo = JSON.parse(body);
} catch (e) {
this.error = e.body ? e.body.message : e.message;
}
}
}Making several calls in parallel
Add more than one request to the same Continuation when the calls do not depend on each other. The platform sends them together, so the wait is about as long as the slowest call, not the sum of all of them.
public with sharing class DashboardController {
@AuraEnabled(continuation=true cacheable=true)
public static Object loadDashboard() {
Continuation con = new Continuation(60);
con.continuationMethod = 'assemble';
HttpRequest todos = new HttpRequest();
todos.setMethod('GET');
todos.setEndpoint('callout:Todo_API/todos?userId=1');
con.addHttpRequest(todos);
HttpRequest users = new HttpRequest();
users.setMethod('GET');
users.setEndpoint('callout:Todo_API/users/1');
con.addHttpRequest(users);
return con;
}
@AuraEnabled
public static Object assemble(List<String> labels, Object state) {
HttpResponse todos = Continuation.getResponse(labels[0]);
HttpResponse users = Continuation.getResponse(labels[1]);
return new Map<String, Object>{
'todosStatus' => todos.getStatusCode(),
'userStatus' => users.getStatusCode()
};
}
}If one call needs the result of another, the Continuation can return a second Continuation from its callback. This is called chaining. A single transaction chain can contain at most three Continuations, so this works for short dependent sequences only.
Errors in a Continuation
A Continuation does not throw CalloutException when the remote service is slow or unreachable. The failure appears in the response you get back from Continuation.getResponse(label). The status code is a platform value in the 2000 range instead of an HTTP status. For example, 2000 means the timeout was reached and 2001 means the connection failed.
Check for these before you read the body.
@AuraEnabled
public static Object processResponse(List<String> labels, Object state) {
HttpResponse res = Continuation.getResponse(labels[0]);
Integer status = res.getStatusCode();
if (status >= 2000) {
throw new AuraHandledException('The service did not respond (code ' + status + ').');
}
if (status < 200 || status > 299) {
throw new AuraHandledException('The service returned HTTP ' + status + '.');
}
return res.getBody();
}Limits to remember
- The timeout is at most 120 seconds. Set it to the longest wait you can accept, not always to the maximum.
- One Continuation holds at most three requests.
- A chain can contain at most three Continuations.
- Each request still counts against the callout limits for the transaction that sends it.
- The Continuation must come from an action method on a Visualforce controller or an Aura-enabled (including LWC) controller. It cannot come from triggers, Queueable jobs, batch jobs or
@futuremethods.
Testing a Continuation
HttpCalloutMock does not apply here, because the platform sends the request and not your code. Instead, you inspect the Continuation your method returns, register a fake response with Test.setContinuationResponse, and run the callback.
@isTest
private class TodoContinuationControllerTest {
@isTest
static void startThenProcess() {
Continuation con = (Continuation) TodoContinuationController.startRequest(1);
Map<String, HttpRequest> requests = con.getRequests();
System.assertEquals(1, requests.size());
String label = new List<String>(requests.keySet())[0];
System.assertEquals('GET', requests.get(label).getMethod());
HttpResponse fake = new HttpResponse();
fake.setStatusCode(200);
fake.setBody('{"id":1,"title":"Write tests"}');
Test.setContinuationResponse(label, fake);
Object result = TodoContinuationController.processResponse(
new List<String>{ label }, 1
);
System.assertEquals('{"id":1,"title":"Write tests"}', result);
}
@isTest
static void failureStatusRaisesError() {
Continuation con = (Continuation) TodoContinuationController.startRequest(1);
String label = new List<String>(con.getRequests().keySet())[0];
HttpResponse fake = new HttpResponse();
fake.setStatusCode(500);
Test.setContinuationResponse(label, fake);
try {
TodoContinuationController.processResponse(new List<String>{ label }, 1);
System.assert(false, 'Expected an exception');
} catch (AuraHandledException e) {
System.assert(true);
}
}
}For controllers that you instantiate, Test.invokeContinuationMethod(controller, continuation) runs the callback for you after the responses are set. Calling the static callback directly, as above, tests the same logic.
Common mistakes
- Returning
Continuationas the declared type. Declare the return type asObject. - Misspelling
continuationMethod. It is a string, so the compiler cannot check it. A wrong name fails at run time. - Relying on static variables. The callback runs in a new transaction. Pass data through
state. - Doing DML in the cacheable method.
cacheable=trueforbids it. Do the DML in the callback or in a separate non-cacheable action. - Treating 2000-range codes as HTTP statuses. Check for them first.
- Using a Continuation for background work. If no screen is waiting, a Queueable job is simpler.
Exercise
A Lightning component must show data from a service that sometimes takes 30 seconds to answer, and it also needs data from a second, independent service. Why is a single Continuation with two requests a better design than two synchronous callouts, and what must the callback check before it reads a body?
Show answer
A Continuation releases the Apex thread while the platform waits, so the slow calls do not count against the limit on concurrent long-running synchronous requests. Adding both requests to one Continuation sends them in parallel, so the wait is about the slowest call and not the sum of both. In the callback, check each response's status code first. Codes in the 2000 range (such as 2000 for a timeout and 2001 for a connection failure) are platform errors, not HTTP statuses, and any HTTP status outside 200 to 299 is a service error. Only then read the body.
Exercise
Your Queueable job needs to call a service that takes 45 seconds. Should you convert it to a Continuation? Explain.
Show answer
No. A Continuation can only be returned from an action method called by a Visualforce page or Aura/LWC component. A Queueable job runs in the background with no screen waiting, so it cannot return a Continuation. Keep the Queueable job with Database.AllowsCallouts and set the request timeout to fit within the 120-second callout limit.