Sub topic 8
Callouts and governor limits in actions
This chapter assumes you can write an @InvocableMethod with request and response wrapper classes, and that you know Apex governor limits in general. It covers how callouts and limits affect an action that an agent calls.
Why limits matter more for agent actions
An agent calls your action while a user waits for a reply. A slow or failing action produces a slow or confusing answer. The agent can also call the action many times in one conversation. Plan for both cases.
Each invocation runs in its own Apex transaction, so the standard synchronous limits apply to it.
| Limit | Synchronous value | Typical way an action hits it |
|---|---|---|
| Callouts per transaction | 100 | One callout per request in a large list |
| Total callout time | 120 seconds | Several slow callouts in a row |
| Timeout per callout | 10 seconds by default, 120 maximum | Slow external service |
| SOQL queries | 100 | A query inside a loop |
| CPU time | 10,000 ms | Heavy parsing or nested loops |
Use a Named Credential
Do not hard-code endpoints or secrets in the class. A Named Credential holds the endpoint and authentication. Apex refers to it with the callout: prefix, so the same code works in sandbox and production.
A callout action
The action below looks up a shipment status. It validates input before calling out, checks the callout limit, sets a short timeout, and always returns one response per request.
public with sharing class GetShipmentStatusAction {
public class Request {
@InvocableVariable(
label='Tracking Number'
description='The carrier tracking number of the shipment'
required=true
)
public String trackingNumber;
}
public class Response {
@InvocableVariable(
label='Status'
description='Current shipment status, or a message explaining why it is unavailable'
)
public String status;
}
@InvocableMethod(
label='Get Shipment Status'
description='Looks up the current status of a shipment by tracking number'
category='Service'
)
public static List<Response> getStatus(List<Request> requests) {
List<Response> responses = new List<Response>();
for (Request r : requests) {
Response res = new Response();
if (String.isBlank(r.trackingNumber)) {
res.status = 'A tracking number is required.';
} else if (Limits.getCallouts() >= Limits.getLimitCallouts()) {
res.status = 'Too many lookups at once. Please try again.';
} else {
res.status = fetchStatus(r.trackingNumber);
}
responses.add(res);
}
return responses;
}
private static String fetchStatus(String trackingNumber) {
HttpRequest req = new HttpRequest();
req.setEndpoint(
'callout:Shipping_API/shipments/' + EncodingUtil.urlEncode(trackingNumber, 'UTF-8')
);
req.setMethod('GET');
req.setTimeout(8000);
try {
HttpResponse resp = new Http().send(req);
if (resp.getStatusCode() == 200) {
Map<String, Object> body =
(Map<String, Object>) JSON.deserializeUntyped(resp.getBody());
Object s = body.get('status');
return s == null ? 'Status unavailable.' : String.valueOf(s);
}
if (resp.getStatusCode() == 404) {
return 'No shipment was found for that tracking number.';
}
return 'The shipping service returned an error (HTTP ' + resp.getStatusCode() + ').';
} catch (CalloutException e) {
return 'The shipping service did not respond in time. Please try again later.';
}
}
}The method catches CalloutException and returns text instead of letting it propagate. An unhandled exception gives the agent nothing useful to tell the user.
Rules to remember
- Callouts cannot follow uncommitted DML. If an action inserts a record and then calls out in the same transaction, Salesforce throws a "You have uncommitted work pending" error. Make the callout first, or split the work into separate actions.
- Keep the timeout short. Set it below the 10-second default so the action fails fast with a clear message.
- Do not loop callouts without a ceiling. One callout per request is acceptable only when lists are small. If the external API supports batch lookups, send one request for all tracking numbers.
- Return summaries, not raw payloads. Large response bodies use heap and give the agent text it must filter.
Testing callouts
Apex tests cannot make real callouts. Use an HttpCalloutMock to return a canned response.
@IsTest
private class GetShipmentStatusActionTest {
private class ShippedMock implements HttpCalloutMock {
public HttpResponse respond(HttpRequest req) {
HttpResponse res = new HttpResponse();
res.setStatusCode(200);
res.setBody('{"status":"In transit"}');
return res;
}
}
@IsTest
static void returnsStatusFromService() {
Test.setMock(HttpCalloutMock.class, new ShippedMock());
GetShipmentStatusAction.Request req = new GetShipmentStatusAction.Request();
req.trackingNumber = 'ABC123';
List<GetShipmentStatusAction.Response> results =
GetShipmentStatusAction.getStatus(new List<GetShipmentStatusAction.Request>{ req });
Assert.areEqual('In transit', results[0].status);
}
}Exercise
An action inserts a Case and then calls an external service in the same invocable method. The callout fails with "uncommitted work pending". What are two ways to fix it?
Show answer
Make the callout before the insert, or move the insert into a separate action so the callout runs in a transaction with no pending DML.