Sub topic 3
Setting and reasoning about timeouts
A timeout is the longest time your code will wait for a response before it gives up. In Apex you set it on each request. This chapter assumes you can already write a basic Http callout and know the difference between synchronous and asynchronous Apex. It covers what the timeout value means, how it interacts with the per-transaction limits, how to choose a value, and what you can and cannot conclude when a timeout happens.
What the timeout controls
HttpRequest.setTimeout(Integer) takes a value in milliseconds. It limits how long Apex waits for the remote system to respond. If the wait runs out, Http.send throws a System.CalloutException. Connection failures throw the same exception type, so you tell them apart by reading the message.
| Setting | Value |
|---|---|
| Default timeout | 10,000 ms (10 seconds) |
| Maximum timeout per callout | 120,000 ms (120 seconds) |
| Cumulative callout time per transaction | 120 seconds, across all callouts |
| Callouts per transaction | 100 |
Apex gives you one timeout value per request. You cannot set a separate connect timeout and read timeout. Treat the value as the total time you are willing to wait for this call.
Setting an explicit timeout
The following client sets a 30-second timeout and wraps the exception in a domain-specific type. Callers then handle one exception type for callout failures instead of the platform's general CalloutException.
public with sharing class OrderApiClient {
public class ApiException extends Exception {}
public static HttpResponse send(String path) {
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:Orders_API' + path);
req.setMethod('GET');
req.setTimeout(30000); // milliseconds; the default is 10000
try {
return new Http().send(req);
} catch (System.CalloutException e) {
// Thrown for timeouts and connection failures
throw new ApiException('Callout failed: ' + e.getMessage(), e);
}
}
}Three details are easy to get wrong:
- The unit is milliseconds.
setTimeout(30)gives the server 30 milliseconds, and almost every call will fail. - The value must be between 1 and 120,000. Anything above the maximum is invalid, so do not use a larger number as a way to mean "wait forever".
- The timeout applies per callout. It is not a budget for your whole method.
How the timeout relates to transaction limits
The per-request maximum of 120 seconds is also the cumulative limit for the whole transaction. Every callout in the transaction adds its time to one shared total. One callout with a 120-second timeout can use the entire budget by itself. Two callouts with 60-second timeouts can do the same.
The cumulative limit has a consequence for loops. Suppose a method makes three sequential callouts, each with setTimeout(60000). If the remote system hangs on each one, the worst case is 180 seconds. That exceeds the budget, and the transaction ends with a governor limit failure that your code cannot catch.
Callout time is also separate from CPU time. Waiting for a response does not count toward the CPU limit. A transaction can be well within its CPU budget and still fail on callout time.
There is one more constraint for synchronous work. A callout that runs for more than 5 seconds counts toward a limit on concurrent long-running requests (10 in production orgs). If many users trigger slow synchronous callouts at the same moment, new requests can be rejected before they reach your code. Slow callouts in synchronous Apex affect other users, not just the one who triggered them.
Budgeting the worst case
Plan for the case where every callout uses its full timeout. The worst-case time of a transaction is the sum of the timeouts of the callouts it might make, and that sum must stay under 120,000 ms.
If a method may make several callouts, you can enforce the budget in code. The following helper hands out timeouts from a shared pool and refuses to start a callout when nothing is left. It keeps its own count because Apex has no method that reports consumed callout time.
public with sharing class TimeoutBudget {
public class BudgetException extends Exception {}
private static final Integer TRANSACTION_LIMIT_MS = 120000;
private static Integer reservedMs = 0;
// Returns the timeout to use, or throws if the budget is spent.
public static Integer reserve(Integer requestedMs) {
Integer remaining = TRANSACTION_LIMIT_MS - reservedMs;
if (remaining <= 0) {
throw new BudgetException('No callout time left in this transaction');
}
Integer granted = Math.min(requestedMs, remaining);
reservedMs += granted;
return granted;
}
}Use it when you build each request:
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:Orders_API/orders/42');
req.setMethod('GET');
req.setTimeout(TimeoutBudget.reserve(30000));The helper reserves the full requested time even when the call returns quickly, so it is conservative. That is the right direction to err in. A static variable lasts for one transaction, so the count resets for each new transaction, including each Queueable job.
Choosing a value
Pick the timeout from how the remote system behaves, not from a round number. A workable method:
- Find the typical latency of the endpoint. Use the 95th or 99th percentile from the provider's documentation or your own monitoring, not the average.
- Add a margin for network variation and occasional slow responses. Two to three times the p99 latency is a common starting point.
- Compare the result with the context. A user is waiting on a Lightning page, so a long timeout means a frozen screen. A background job can wait longer.
- Check the sum against the 120-second transaction budget, including any other callouts in the same transaction.
The right answer also depends on what the call does:
| Situation | Direction | Reason |
|---|---|---|
| Interactive page waiting on the result | Shorter (5 to 15 seconds) | The user gives up before a long wait ends, and slow requests use up the concurrent long-running request slots. |
| Background job, order submission | Moderate (20 to 60 seconds) | No user is waiting, and an early timeout creates uncertainty about the outcome (see below). |
| Several callouts in one transaction | Shorter per call | The worst-case sum must fit in 120 seconds. |
| Provider documents a hard server-side limit | Slightly above that limit | You will receive their error response instead of a timeout from your side. |
A timeout that is too short turns healthy but slow responses into failures, and retrying them adds load to an endpoint that is already slow. A timeout that is too long holds transaction budget and, in synchronous code, makes the user wait. Neither is free.
What a timeout does not tell you
A timeout means your code stopped waiting. It does not mean the remote system did nothing. The server may have received the request, completed the work, and sent a response that arrived after your deadline.
This ambiguity matters for the decisions later in this tutorial:
- For a read (
GET), a timeout is harmless. Repeating the call returns the same data. - For a write (
POSTthat creates an order), a blind retry can create a duplicate. - Your code cannot tell "never arrived" from "arrived but the response was lost". The chapter on idempotency covers how to make repeats safe, usually with a key the server uses to detect duplicates.
For now, remember the rule: after a timeout on a write, the outcome is unknown, and your design must handle both possibilities.
Timeouts compared with error responses
A timeout is an exception. A 503 from the server is a normal HttpResponse object, and Http.send does not throw for it. These two paths need different handling, which the next chapters cover in detail. Keep the following in mind when you set the timeout:
- A server that is overloaded may answer quickly with a
503or429. A server that is failing badly may not answer at all, and you only learn about it when your timeout fires. - A shorter timeout makes the second case fail faster. That is usually what you want, as long as the value is longer than the endpoint's normal slow responses.
Common mistakes
- Using the default by omission. The 10-second default may be too short for a report endpoint or too long for an interactive page. Decide, then set it.
- Passing seconds instead of milliseconds.
setTimeout(30)fails almost immediately. - Retrying in a loop inside one transaction. A
forloop that retries a callout three times with a 60-second timeout can consume 180 seconds. Retries belong in a separate asynchronous job, which gets its own transaction and its own budget. - Setting 120,000 for every call "to be safe". One slow endpoint then consumes the whole budget, and every callout after it in the transaction is at risk.
- Treating a timeout as proof of failure on a write. The server may have finished the work.
- Catching only
CalloutExceptionand ignoring the budget. Catching the exception handles one slow call. It does not stop several slow calls from exhausting the transaction limit.
Summary of the working model
- Set
setTimeoutexplicitly, in milliseconds, between 1 and 120,000. - The 120-second cumulative limit is shared by every callout in the transaction, so budget the worst case.
- Base the value on the endpoint's p99 latency plus a margin, and shorten it for interactive code.
- A timeout leaves the result of a write unknown. Design for both outcomes.
- Move retries out of the current transaction, which later chapters show using Queueable Apex.
Exercise
A trigger-initiated Queueable job makes three sequential callouts to a slow partner API. Each request uses setTimeout(60000). The partner's p99 latency is 8 seconds. What is the problem, and what would you change?
Show answer
The worst case is 3 x 60 s = 180 s, which exceeds the 120-second cumulative callout limit for one transaction. If the partner hangs, the transaction fails with a governor limit exception that cannot be caught. The 60-second value is also far above the 8-second p99. Reduce each timeout to a value based on that latency, for example 20 to 25 seconds, so the worst-case sum is about 60 to 75 seconds. Alternatively, use a budget helper such as TimeoutBudget.reserve, or split the callouts across separate Queueable jobs so each has its own budget.
Exercise
An Apex POST to create an order throws a CalloutException with a read timeout message. Can you conclude that no order was created? What does this imply for retrying?
Show answer
No. The server may have received the request and created the order, with the response arriving after the timeout. The outcome is unknown. A blind retry can create a duplicate order, so retries of writes need an idempotency mechanism, such as a key the server uses to detect repeated requests.