Sub topic 5
Request-reply: calling out and waiting for an answer
This chapter covers the request-reply pattern, where Salesforce sends a request to another system and waits for the response. It assumes you can read basic Apex, know HTTP methods and status codes, and have seen a Named Credential. Earlier chapters introduced Named Credentials and the sync/async trade-off. This chapter applies both.
What request-reply means
In request-reply, the caller sends a message and blocks until it gets an answer or gives up. The caller's next step depends on the reply. Typical examples:
- Looking up an invoice status in a billing system when a user opens a record.
- Validating an address or tax ID before saving.
- Asking a pricing engine for a quote during a sales process.
The pattern has three properties:
- Timing: The caller waits. The user, or the running transaction, is held until the reply arrives.
- Coupling: The caller needs the remote system to be up right now. The two systems are tightly coupled in time.
- Failure behavior: Failures show up immediately in the caller as a timeout, an HTTP error, or an exception. The caller must decide what to do next.
The request-reply pattern is a good fit when the user or process needs the answer to continue. It is a poor fit when the remote work is slow, unreliable, or high volume.
Directions of request-reply
Request-reply works in both directions.
- Outbound: Salesforce calls an external system. You use Apex callouts, Flow HTTP Callout actions, or External Services. This chapter focuses on Apex callouts.
- Inbound: An external system calls Salesforce and waits for the answer. You use the REST API, SOAP API, or a custom Apex REST endpoint. The external system carries the waiting cost, but Salesforce API limits still apply.
The anatomy of an Apex callout
An Apex callout builds an HttpRequest, sends it with Http.send, and reads the HttpResponse. The code below reaches the billing system through the Billing_API Named Credential.
public with sharing class InvoiceClient {
public static String fetchInvoiceStatus(String invoiceId) {
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:Billing_API/invoices/' + EncodingUtil.urlEncode(invoiceId, 'UTF-8'));
req.setMethod('GET');
req.setHeader('Accept', 'application/json');
req.setTimeout(10000);
HttpResponse res = new Http().send(req);
if (res.getStatusCode() == 200) {
Map<String, Object> body = (Map<String, Object>) JSON.deserializeUntyped(res.getBody());
return (String) body.get('status');
}
throw new CalloutException('Billing API returned ' + res.getStatusCode());
}
}Each part does a specific job:
callout:Billing_APIis the Named Credential prefix. Salesforce replaces it with the configured base URL and adds the authentication. No host name, token, or password appears in code.EncodingUtil.urlEncodeprotects the URL path from characters in the ID that would change its meaning. Always encode values that you did not write yourself.setTimeout(10000)sets a 10-second wait, in milliseconds. The default is 10 seconds and the maximum is 120 seconds. Choose a value based on what the caller can tolerate, not the maximum.Http.sendblocks the transaction until the response arrives or the timeout expires. A timeout throws aSystem.CalloutException.- The status check matters because
senddoes not throw for 4xx or 5xx responses. A404or500returns normally with that status code. Your code must inspect it.
The call sequence
The diagram shows what happens during a callout and where the waiting occurs.
Where you can and cannot call out
Callouts are restricted by transaction context. These restrictions cause many production errors.
- No callout after uncommitted DML. If a transaction has inserted, updated, or deleted records and has not committed them, a callout fails with
You have uncommitted work pending. Please commit or rollback before calling out.Make the callout first, or move it to a separate transaction. - No synchronous callouts from triggers. A trigger runs inside a DML transaction, so the callout would hold database locks while waiting. Move the callout to asynchronous Apex, such as a Queueable class that implements
Database.AllowsCallouts, or an@future(callout=true)method. - No callouts in tests. Test methods cannot make real callouts. You must register a mock.
A Queueable that wraps the client from above:
public with sharing class InvoiceStatusJob implements Queueable, Database.AllowsCallouts {
private final String invoiceId;
public InvoiceStatusJob(String invoiceId) {
this.invoiceId = invoiceId;
}
public void execute(QueueableContext ctx) {
String status = InvoiceClient.fetchInvoiceStatus(invoiceId);
System.debug('Invoice ' + invoiceId + ' status: ' + status);
}
}Calling System.enqueueJob(new InvoiceStatusJob('INV-1001')) from a trigger works. Note what has changed, though. The trigger no longer waits for the reply, so this is no longer request-reply from the user's point of view. The result arrives later and must be written back to a record, which makes the interaction asynchronous in practice.
Limits that apply to callouts
Callouts consume limited resources, so design around them:
| Limit | Value | Consequence |
|---|---|---|
| Callouts per transaction | 100 | A loop that calls out per record fails on large batches. |
| Timeout per callout | 10 s default, 120 s maximum | Slow endpoints need asynchronous design. |
| Total callout time per transaction | 120 s | Several slow calls add up. |
| Request and response size | 6 MB synchronous, 12 MB asynchronous | Large payloads need paging or Bulk API. |
| Long-running requests | 10 concurrent requests that run longer than 5 s | A slow endpoint can block users org-wide. |
The last limit deserves attention. If the external API takes 8 seconds and users trigger it often, requests pile up. When 10 such requests run at once, further requests fail with a concurrent request limit error. A slow dependency can therefore make part of Salesforce unavailable. Keep synchronous callouts fast, and fall back to asynchronous processing when the endpoint is slow.
Inbound request-reply
When an external system calls Salesforce, the same pattern applies in reverse. The caller sends a request to the REST API and waits for a response. Each call counts against the org's daily API request allocation. You also need to authenticate the caller, usually with OAuth through a connected app or an external client app.
Use inbound calls for small, interactive operations such as reading one record or creating one order. For thousands of records per call, use a batch pattern instead. Bulk API 2.0 is covered in a later chapter.
Handling failure
A request-reply call can fail in several ways, and each needs a different response.
| Failure | Typical signal | Usual response |
|---|---|---|
| Timeout or network error | `CalloutException` | Retry if the operation is safe to repeat, otherwise surface an error. |
| `400`, `422` | Bad request or validation error | Do not retry. Fix the request. |
| `401`, `403` | Authentication or permission failure | Do not retry blindly. Check the credential configuration. |
| `404` | Resource not found | Treat as a business result, not a system failure. |
| `429` | Rate limited | Retry later, honoring `Retry-After` if present. |
| `500`, `502`, `503`, `504` | Server-side failure | Retry with delay, or fail gracefully. |
A timeout is the hardest case. You do not know whether the remote system processed the request before the connection broke. For a GET, repeating it is harmless. For a POST that creates a payment, repeating it could charge the customer twice.
This is why retries need idempotency. An idempotent request has the same effect no matter how many times it is sent. GET, PUT, and DELETE are idempotent by definition. POST is not, unless the remote API supports an idempotency key, which you send in a header so the server can recognize repeats. Later chapters cover this in detail.
Do not retry in a tight loop inside one transaction. Each attempt uses up the callout count and total time limits and holds the user waiting. A better approach for synchronous calls is to fail fast with a clear message. For background work, re-enqueue a Queueable with a delay or record the failure for later replay.
Testing a callout
Apex does not allow real callouts in tests. You provide a class that implements HttpCalloutMock, and register it with Test.setMock.
@IsTest
private class InvoiceClientTest {
private class StatusMock implements HttpCalloutMock {
private final Integer code;
private final String body;
StatusMock(Integer code, String body) {
this.code = code;
this.body = body;
}
public HttpResponse respond(HttpRequest req) {
HttpResponse res = new HttpResponse();
res.setStatusCode(code);
res.setHeader('Content-Type', 'application/json');
res.setBody(body);
return res;
}
}
@IsTest
static void returnsStatusOnSuccess() {
Test.setMock(HttpCalloutMock.class, new StatusMock(200, '{"status":"PAID"}'));
Test.startTest();
String status = InvoiceClient.fetchInvoiceStatus('INV-1001');
Test.stopTest();
System.assertEquals('PAID', status);
}
@IsTest
static void throwsOnServerError() {
Test.setMock(HttpCalloutMock.class, new StatusMock(503, '{}'));
try {
InvoiceClient.fetchInvoiceStatus('INV-1001');
System.assert(false, 'Expected a CalloutException');
} catch (CalloutException e) {
System.assert(e.getMessage().contains('503'));
}
}
}Test both the success path and at least one error status. Error paths are where request-reply code most often breaks in production.
Common mistakes
- Hard-coding the endpoint and credentials in Apex or custom settings instead of using a Named Credential.
- Not checking the status code and treating every response as success.
- Making a callout inside a loop, one per record, and hitting the 100-callout limit.
- Calling out from a trigger and getting the uncommitted work error.
- Setting the timeout to the 120-second maximum "to be safe", which ties up a user and a concurrency slot.
- Retrying non-idempotent
POSTrequests after a timeout. - Parsing a response without handling missing fields, so an unexpected shape produces a
NullPointerExceptionorTypeException.
Exercises
Exercise
An Apex trigger on Order must send each new order to a fulfilment system through an HTTP call. The trigger throws "You have uncommitted work pending" when it makes the call. Explain why this happens, and give one fix.
Show answer
A trigger runs inside a transaction that has uncommitted DML on the Order records, and Salesforce does not allow a callout while such work is pending. Move the callout out of the transaction. For example, enqueue a Queueable class that implements Database.AllowsCallouts from the trigger, and make the callout inside its execute method. The callout then runs in a separate transaction after the data is committed.
Exercise
A synchronous callout to a payment API times out. Is it safe to retry immediately? Name what you need before retrying a POST that creates a charge.
Show answer
Not necessarily. After a timeout you do not know whether the payment API processed the request. Repeating a non-idempotent POST could create a second charge. Before retrying, you need an idempotency mechanism, such as an idempotency key header that the API uses to recognize repeated requests, or a way to look up the earlier result first.