Sub topic 9
Callout limits and timeouts
This chapter covers the limits Salesforce puts on outbound HTTP calls and how to design code that stays inside them. It assumes you can already build and send a request with Http, HttpRequest and HttpResponse. It also assumes you know the governor limits model (per-transaction ceilings enforced by the platform) and how Apex exceptions work.
Why callouts have their own limits
Apex runs on shared infrastructure. A callout holds a platform thread while it waits for a server you don't control, so Salesforce caps how many callouts a transaction can make and how long each one may wait. These caps are separate from the SOQL, DML and CPU limits. They apply to every callout, whether it goes through a Named Credential or a Remote Site Setting.
A transaction is one unit of Apex execution: a trigger, a REST endpoint call, a Queueable execute, one execute of a Batch Apex job, and so on. Most limits reset at the start of each transaction.
The limits that matter
| Limit | Value | Notes |
|---|---|---|
| Callouts per transaction | 100 | Counts every `Http.send` and web service call. |
| Default timeout per callout | 10 seconds | Applies when you don't call `setTimeout`. |
| Maximum timeout per callout | 120 seconds | `setTimeout` takes milliseconds, 1 to 120000. |
| Cumulative timeout per transaction | 120 seconds | Added up across all callouts in the transaction. |
| Request or response size | Bound by heap | 6 MB synchronous, 12 MB asynchronous. |
Check these numbers against the current "Apex Developer Guide: Execution Governors and Limits" page before you rely on them, because Salesforce adjusts limits between releases.
Two points are easy to miss:
- The 100-callout limit counts calls, not successful calls. A callout that fails with a 500 status or a timeout still uses one.
- The time a thread spends waiting for the remote server does not count toward the CPU time limit. The time you spend parsing a large response does, and the response also takes heap space.
Timeouts
Setting a timeout
Use HttpRequest.setTimeout(Integer milliseconds). The value is milliseconds, not seconds. A common mistake is writing setTimeout(20) and getting a 20 ms timeout.
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:Todo_API/todos/1');
req.setMethod('GET');
req.setTimeout(20000); // 20 secondsIf you omit the call, the timeout is 10 seconds. Named Credentials do not change this default, so set the timeout on the request.
The cumulative budget
Each request has its own timeout, but the transaction has a shared budget of 120 seconds. Suppose you make six sequential callouts, each with a 30-second timeout, and the remote server hangs on every one. The first four use up the full 120 seconds. The fifth fails because the transaction has no time budget left, even though its own timeout is only 30 seconds.
This means a long per-request timeout is not free. In a loop, a slow server drains the shared budget for every call after it.
What a timeout looks like
When the server does not answer in time, Http.send throws a System.CalloutException with a message such as Read timed out. You can catch it. The request may still have reached the server and been processed, so a retry of a non-idempotent POST can create a duplicate record. Design the remote API or your payload with an idempotency key if that matters.
public with sharing class TimeoutAwareClient {
public static HttpResponse sendWithTimeout(HttpRequest req, Integer timeoutMs) {
req.setTimeout(timeoutMs);
try {
return new Http().send(req);
} catch (CalloutException e) {
if (e.getMessage() != null && e.getMessage().containsIgnoreCase('timed out')) {
// Log it, then surface a clear error to the caller.
throw new CalloutException('Remote service did not respond within ' + timeoutMs + ' ms');
}
throw e;
}
}
}The check on the message text is fragile because Salesforce does not document the exact wording as a contract. If you rely on it, keep the fallback branch that rethrows the original exception.
The 100-callout limit
What happens when you exceed it
On the 101st callout the platform throws System.LimitException: Too many callouts: 101. A LimitException cannot be caught with try/catch. The transaction stops and rolls back. Unlike a timeout, you cannot recover from it at runtime, so you have to prevent it.
Checking the budget with the Limits class
The Limits class reports usage, so you can stop early or hand work to another transaction.
public with sharing class CalloutBudget {
public static Boolean hasCalloutsLeft(Integer needed) {
return (Limits.getLimitCallouts() - Limits.getCallouts()) >= needed;
}
public static void logUsage() {
System.debug('Callouts used: ' + Limits.getCallouts()
+ ' of ' + Limits.getLimitCallouts());
}
}Limits.getCallouts() returns how many callouts the current transaction has made. Limits.getLimitCallouts() returns the maximum, which is 100 in a synchronous or asynchronous transaction.
The usual cause: callouts inside loops
The typical way to hit this limit is a loop that makes one callout per record.
// Anti-pattern: one callout per record
for (Account a : accounts) {
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:Todo_API/todos/' + a.Id);
req.setMethod('GET');
new Http().send(req); // fails on the 101st record
}Triggers receive up to 200 records per batch, so this code works in a demo with five records and fails when someone loads a data file. There are three ways to avoid it:
- Batch on the remote side. If the API accepts a list, send one request containing many items. This is the best option when it exists.
- Chunk across transactions. Process a slice of records per transaction using Queueable Apex or Batch Apex. Each
executegets its own 100 callouts. - Reduce the work. Cache results you have already fetched, and skip records that have not changed.
Batch Apex is a good fit for this. Declare Database.AllowsCallouts on the class and pick a scope size that stays below 100 callouts per execute.
public class TodoBatch implements Database.Batchable<Integer>, Database.AllowsCallouts {
private List<Integer> ids;
public TodoBatch(List<Integer> ids) {
this.ids = ids;
}
public Iterable<Integer> start(Database.BatchableContext bc) {
return ids;
}
public void execute(Database.BatchableContext bc, List<Integer> scope) {
// Scope size is chosen by the caller: Database.executeBatch(job, 50)
for (Integer id : scope) {
if (!CalloutBudget.hasCalloutsLeft(1)) {
break;
}
TodoService.fetchTodo(id);
}
}
public void finish(Database.BatchableContext bc) {}
}TodoService.fetchTodo is the GET method from the earlier chapters. To run the job with 50 items per execute, call Database.executeBatch(new TodoBatch(idList), 50).
The break here is a safety net. If it fires, the remaining items in that scope are silently skipped. In real code, a smaller scope size is the cleaner guarantee, and you may want to log or requeue any skipped items.
Size and heap limits
Request and response bodies are Apex strings or blobs, so they count against the heap limit: 6 MB synchronously and 12 MB asynchronously. A 5 MB JSON response can fail in synchronous code once you also deserialize it, because the string and the resulting objects exist at the same time.
Ways to reduce the pressure:
- Ask the remote API for fewer fields or a smaller page with query parameters.
- Page through results and process one page per transaction.
- Run the callout asynchronously to get the larger 12 MB heap.
- Use
res.getBodyAsBlob()only when you need binary data, and avoid holding both the blob and a string copy.
How the checks fit together
Picking a timeout value
A sensible timeout comes from the work, not from a default. Use this process:
- Find out the remote service's typical and worst-case response times.
- Set the timeout slightly above the worst case you are willing to wait for.
- Multiply by the number of callouts the transaction could make in the worst case. If the result goes above 120 seconds, shorten the timeout or reduce the number of calls.
- If a user is waiting on the page, stay well below those numbers. A user-facing request that waits 60 seconds is usually a bad design, whatever the limits allow.
For example, a Queueable job that makes at most 10 callouts to a service with a 5-second worst case can safely use a 10-second timeout: 10 × 10 = 100 seconds, which leaves a margin under 120.
Limits and other rules that interact with callouts
- Uncommitted work. If a transaction has performed DML and not yet committed, a callout throws
You have uncommitted work pending. Please commit or rollback before calling out. The next chapter covers this and how to order work to avoid it. - Triggers. A trigger cannot make a synchronous callout. Move the callout to an asynchronous job that declares
Database.AllowsCalloutsor to an@future(callout=true)method. - Long-running calls. The platform limits how many synchronous requests can run for a long time at once. Slow callouts in user-facing code can contribute to that pool filling up. Continuations, covered later, exist for this case.
- Governor limits are shared. The same transaction also has SOQL, DML, CPU and heap limits. A transaction that parses big responses for 100 callouts is more likely to hit CPU or heap before it hits the callout limit.
Common mistakes
| Mistake | Symptom | Fix |
|---|---|---|
| `setTimeout(20)` meaning 20 seconds | Immediate timeouts | Use milliseconds: `20000`. |
| Callout per record in a trigger | `Too many callouts: 101`, or a callout-in-trigger error | Batch the request or go asynchronous. |
| Catching `Exception` and assuming it covers limits | Transaction still dies | Check `Limits` before the call. |
| Retrying a POST after a timeout | Duplicate remote records | Use an idempotency key or check before retrying. |
| Very large responses in synchronous code | `Apex heap size too large` | Page the data or move to async. |
Exercise
A trigger handler loops over up to 200 Contact records and sends one callout per record, each with setTimeout(30000). Name two separate limits this design can break, and describe one change that fixes both.
Show answer
It can break the 100-callouts-per-transaction limit (the 101st call throws an uncatchable LimitException) and the 120-second cumulative timeout (four slow 30-second calls use the whole budget). Making the callouts in a Queueable or Batch job with a small scope, such as 20 to 50 records per execute, gives each chunk its own transaction with a fresh count and time budget. Sending one request with a list of records, if the API supports it, also fixes both.
Exercise
What does req.setTimeout(5) do, and what exception do you expect when the server takes one second to answer?
Show answer
It sets the timeout to 5 milliseconds because the argument is in milliseconds. A server that takes one second will cause a System.CalloutException with a message like Read timed out. To wait 5 seconds, use req.setTimeout(5000).