How do developers configure HTTP callout timeouts to prevent transactions from hanging indefinitely on slow external servers?
Answer
Basics: An HTTP callout waits for an external server. Without a limit, a slow server could tie up your transaction. Apex lets you set a per-request timeout; when it expires you get a CalloutException (typically "Read timed out"). The unit is milliseconds, not seconds.
How it works:
- Build the HttpRequest, set endpoint (preferably a Named Credential), method, headers and body.
- Call req.setTimeout(ms).
- Send with Http.send; catch CalloutException and inspect HttpResponse status for non-timeout errors.
- Decide on retry, queue or fail.
Advanced / deep dive: The default is 10 seconds and the maximum is 120 seconds per callout, and the cumulative time of all callouts in a transaction is also capped at 120 seconds. A transaction may make up to 100 callouts. Long waits also count toward the org's concurrent long-running request limit (requests running over 5 seconds can exhaust the concurrent Apex request limit, with a documented per-org cap; verify the exact number), so set timeouts as short as the business allows. Timeouts in a synchronous UI context block the user; move slow calls to Queueable with Database.AllowsCallouts, or use Continuation for Visualforce/Aura/LWC calls to long APIs, which are non-blocking on the server and do not count the same way. A timeout does not roll back the remote operation, so use idempotency keys and a status field so a retry does not double-create. Retry with backoff only through async jobs (no sleeping in Apex). Also note request and response size limits (6 MB sync, 12 MB async).
Code / config example:
public with sharing class InventoryClient {
String {
();
req.setEndpoint( + EncodingUtil.urlEncode(sku, ));
req.setMethod();
req.setTimeout();
{
().send(req);
(res.getStatusCode() == ) res.getBody();
( + res.getStatusCode());
} (CalloutException e) {
e;
}
}
}