Sub topic 2
Callout limits you must plan around
This chapter covers the limits Salesforce places on Apex callouts. It explains what happens when you hit each one and how to design code that stays inside them. It assumes you can read and write basic Apex classes, know HTTP methods and status codes, and have written a simple callout with Http, HttpRequest, and HttpResponse. It also assumes you know that governor limits exist and that synchronous and asynchronous Apex run under different limits.
Why limits matter for resilience
A retry policy is only useful if the retry itself can run. Many callout failures in production are not network problems. They are limit problems: a loop that makes the 101st request, a batch of slow calls whose timeouts add up past the transaction budget, or a response too large to hold in memory. Some of these failures cannot be caught. You have to prevent them by design.
The limits below apply per transaction unless stated otherwise. A transaction is one synchronous request, one Queueable execute, one Batch execute chunk, and so on.
The limits at a glance
| Limit | Value | What happens when exceeded |
|---|---|---|
| Callouts per transaction | 100 | `System.LimitException: Too many callouts: 101`. Not catchable. |
| Timeout of a single callout | Default 10,000 ms. Maximum 120,000 ms. | `System.CalloutException` (for example "Read timed out"). Catchable. |
| Cumulative callout time per transaction | 120 seconds | `System.CalloutException` on the callout that would exceed the budget. Catchable. |
| Request or response size | 6 MB synchronous, 12 MB asynchronous | `System.CalloutException` about the maximum size. Catchable. |
| Heap size | 6 MB synchronous, 12 MB asynchronous | `System.LimitException: Apex heap size too large`. Not catchable. |
| Concurrent long-running requests per org | 10 requests running longer than 5 seconds | The new request is rejected with a concurrency error. |
Check the current "Apex Developer Guide: Execution Governors and Limits" page for your release. The numbers have been stable for years, but Salesforce publishes them as the source of truth.
The distinction between catchable and uncatchable matters most. A CalloutException is an ordinary exception. A LimitException ends the transaction and rolls back its changes, and no catch block can stop that. Plan so the uncatchable ones never fire.
The 100-callout cap
Each call to Http.send counts as one callout, whether it succeeds, fails, or times out. Retrying inside the same transaction also consumes callouts. A loop that calls send up to three times per record against 40 records can reach 120 callouts, and the transaction fails at the 101st.
You can read your position at any time:
Integer used = Limits.getCallouts();
Integer max = Limits.getLimitCallouts();
System.debug('Callouts used: ' + used + ' of ' + max);Never rely on the exception to tell you the cap was hit. Check before you send. If the work does not fit in one transaction, split it. Send what fits now and hand the rest to a Queueable job or a Batch Apex chunk, each of which starts with a fresh set of 100 callouts.
The cumulative timeout budget
Each callout has its own timeout, set with HttpRequest.setTimeout. The valid range is 1 to 120,000 milliseconds, and the default is 10,000. Separately, all callouts in one transaction share a cumulative limit of 120 seconds.
The two limits interact. With a 30-second timeout on each request, a synchronous loop can only afford four calls if all of them hang. A fifth call can exceed the cumulative budget and throw a CalloutException. In practice, most calls return quickly, so you will usually stay within budget. The trouble comes during a partner outage, when every call runs to its full timeout. That is exactly when your retry code runs and you most need headroom.
Apex does not expose the elapsed callout time through the Limits class. If you need to protect the budget, track it yourself. The class below uses worst-case accounting. It reserves the full timeout for each call, as if the call would hang until it timed out.
public class CalloutBudget {
private static final Integer MAX_TOTAL_MS = 120000;
private Integer reservedMs = 0;
public Boolean canAfford(Integer timeoutMs) {
Boolean underCount = Limits.getCallouts() < Limits.getLimitCallouts();
Boolean underTime = reservedMs + timeoutMs <= MAX_TOTAL_MS;
return underCount && underTime;
}
public void reserve(Integer timeoutMs) {
reservedMs += timeoutMs;
}
}Worst-case accounting is conservative. A budget of 120,000 ms with 30,000 ms timeouts admits four calls, even if each would normally take 200 ms. If that is too strict, lower the timeout to match what the service really needs, rather than reserving less than the timeout.
Sending in budgeted slices
This method sends as many requests as the budget allows and returns the paths it could not send. The caller can pass the remainder to a Queueable job. Each path is a GET against a Named Credential called Orders_API, as in the earlier chapters.
public with sharing class BudgetedSender {
private static final Integer TIMEOUT_MS = 20000;
public static List<String> sendWithinBudget(List<String> paths) {
CalloutBudget budget = new CalloutBudget();
List<String> remaining = new List<String>();
for (String path : paths) {
if (!budget.canAfford(TIMEOUT_MS)) {
remaining.add(path);
continue;
}
budget.reserve(TIMEOUT_MS);
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:Orders_API' + path);
req.setMethod('GET');
req.setTimeout(TIMEOUT_MS);
try {
HttpResponse res = new Http().send(req);
System.debug('Status for ' + path + ': ' + res.getStatusCode());
} catch (System.CalloutException e) {
System.debug(LoggingLevel.WARN, 'Failed ' + path + ': ' + e.getMessage());
remaining.add(path);
}
}
return remaining;
}
}With a 20-second timeout, canAfford admits six calls (6 × 20 s = 120 s) and defers the rest. A path that fails with a CalloutException also lands in remaining, so the caller can retry it later. The chapters on classifying errors and on Queueable retries build the full policy. For now, the point is that the method never lets the platform decide which request fails.
Size limits
The 6 MB synchronous and 12 MB asynchronous caps apply to both the request body and the response body. Exceeding them throws a CalloutException, so the failure is catchable. The heap limit is a separate problem. Reading a large response with getBody() copies it into a String, and parsing it into JSON objects can multiply the memory use. A 4 MB response can push you past a 6 MB heap before the size limit itself is involved. The LimitException for heap is not catchable.
Ways to stay safe:
- Ask the remote service for less. Use pagination, field selection, or date filters so each response is small.
- Move large transfers to asynchronous Apex, where both limits double.
- Parse only what you need. Deserialize into a narrow wrapper class instead of
Map<String, Object>for the whole document. - Use
getBodyAsBlob()only when you need binary content, and release large variables by reassigning them tonullonce you are done.
The concurrent long-running request limit
This limit works differently because it is shared across your whole org, not scoped to one transaction. Salesforce allows 10 requests that have been running for more than 5 seconds at the same time. A slow external API can occupy those slots. When it does, unrelated users can see their page loads or API calls rejected with a concurrency error, even though their own code is fine.
Two practical consequences follow:
- Prefer short timeouts for user-facing synchronous callouts. A 120-second timeout on a button click can hold a slot for two minutes.
- Move slow, non-interactive work to Queueable, Batch, or Platform Events. Asynchronous execution does not use the same pool of interactive request slots.
Limits are per transaction, so async resets the budget
Every Queueable execute is its own transaction with its own 100 callouts, 120-second budget, and 12 MB heap. This is why retry-by-re-enqueue works. The retry does not inherit the used-up budget of the transaction that failed. Asynchronous limits are not unlimited, though:
- A synchronous transaction can enqueue up to 50 Queueable jobs. A job running asynchronously can enqueue only one child job, so chains are linear.
System.enqueueJob(job, delayMinutes)accepts a delay of 0 to 10 minutes. The retry design in a later chapter depends on this cap.- The org has a limit on the number of asynchronous Apex executions per 24 hours. Heavy retry traffic spends from that allowance.
Planning flow
Before sending, a well-designed callout path checks these constraints in order. If any check fails, the work moves to a new transaction instead of failing in place.
Common mistakes
- Leaving the default timeout on. The default of 10 seconds is often too short for a slow endpoint and too long for a user-facing page. Set the value on purpose.
- Setting every timeout to 120 seconds. A single hung call then consumes the whole cumulative budget, and nothing else in the transaction can call out.
- Counting only successful calls. Failed and timed-out calls use up the 100-callout cap too.
- Retrying in a loop. See the warning above. Re-enqueue instead.
- Testing with small payloads only. A test with a 200-byte mock response will never show a heap problem that appears with a real 5 MB response.
- Assuming callout time counts toward CPU time. It does not. Time spent waiting for the remote service is not CPU time, so a slow API will not trip the 10,000 ms synchronous CPU limit. The cumulative callout limit is the one that catches it.
Exercise
A synchronous Apex method sends one callout per record with setTimeout(40000). During an outage the remote service hangs on every request. How many calls can the transaction make before the cumulative limit is reached, and what kind of failure does the next call produce? Name one change that lets the method handle 50 records.
Show answer
The cumulative callout limit is 120 seconds, so three calls (3 × 40 s = 120 s) can run to their full timeout. The next call exceeds the budget and throws a catchable System.CalloutException. It is not a LimitException. To handle 50 records, lower the timeout to what the service needs (for example 10 seconds, which gives a worst case of 12 calls), and send the remaining records from Queueable jobs in batches that fit within both the 100-callout and 120-second budgets. Each Queueable execute starts with a fresh budget.
Exercise
Which of these failures can you handle with a try/catch block: (a) the 101st callout in a transaction, (b) a callout whose response is over 6 MB in a synchronous transaction, (c) a heap overflow while parsing a 5 MB response? What does that imply for the design?
Show answer
Only (b) is catchable, because it throws a CalloutException. Cases (a) and (c) throw an uncatchable LimitException that rolls back the transaction. The design must prevent them. Check Limits.getCallouts() against Limits.getLimitCallouts() before each send, and keep responses small by paginating, filtering fields, parsing into narrow wrapper classes, or moving the work to asynchronous Apex, where the heap limit is 12 MB.