Sub topic 1
Transactions and callout limits
A callout from Apex is a request to a system outside Salesforce, such as a REST API or a SOAP service. Before you can decide where a callout may run, you need to know what a transaction is and which limits apply to callouts inside one. This chapter covers both. The next chapter uses them to explain why a trigger cannot call out directly.
Prerequisites
This chapter assumes you already know the following:
- Basic Apex syntax and classes.
- How to write and bulkify an Apex trigger (a trigger that handles up to 200 records per invocation, not one).
- What governor limits are, in general terms.
- What an HTTP request, a response and a JSON body are.
You do not need to have written a callout before. The next chapters include a refresher.
What a transaction is
A transaction is a set of operations that Salesforce treats as one unit of work. Either all of its database changes are saved (committed), or none of them are (rolled back).
A transaction starts when something enters Apex. Typical starting points are a user saving a record, an API call, an anonymous Apex run, or a scheduled job starting. Everything that happens as a result stays in the same transaction. When you insert an Account, the transaction includes:
- the
before inserttriggers, - system and custom validation,
- the
after inserttriggers, - any flows, workflow field updates and processes that run in the same save,
- records those steps update in turn.
Your trigger has no transaction of its own. It runs inside the transaction of the DML statement that fired it, and it shares that transaction's limits and its fate. If any step throws an unhandled exception, Salesforce rolls back the whole transaction, including changes made by code that already finished successfully.
Locks and the commit point
While a transaction runs, it holds locks on the records it has changed. Other transactions that try to update those records have to wait, and they can fail with a lock error. The locks are released at the commit point, which is the very end of the transaction.
This matters for callouts. A callout is a network request whose duration you do not control. If a callout ran in the middle of a save, the transaction would keep its locks and its uncommitted changes for as long as the external server took to answer. Salesforce is a multitenant platform, meaning many customers share the same infrastructure, so it enforces limits to stop one transaction from monopolizing resources.
The following diagram shows where a callout would fall in the life of a save.
Governor limits are per transaction
A governor limit is a cap on a resource that Apex can use. Salesforce counts each limit per transaction, not per org or per class. Code in your trigger, in the classes it calls, and in other triggers fired by the same save all draw from one shared budget.
Some limits that are not about callouts, for comparison:
| Limit | Synchronous transaction | Asynchronous transaction |
|---|---|---|
| SOQL queries | 100 | 200 |
| DML statements | 150 | 150 |
| Heap size | 6 MB | 12 MB |
| CPU time | 10,000 ms | 60,000 ms |
Asynchronous Apex gets its own transaction, started later, with a fresh set of limits. Many of those limits are higher. That is part of why moving work to an async transaction is useful, and later chapters build on it.
The callout limits
Callouts have their own limits. These are the ones you will meet most often.
| Limit | Value |
|---|---|
| Callouts per transaction (HTTP and SOAP combined) | 100 |
| Default timeout of a single callout | 10 seconds |
| Maximum timeout you can set on one callout | 120 seconds |
| Cumulative timeout of all callouts in a transaction | 120 seconds |
| Maximum request or response size | 6 MB (synchronous), 12 MB (asynchronous) |
Salesforce raises and adjusts limits between releases, so check the Apex Developer Guide section on execution governors and limits for the current values.
What the numbers mean in practice
- 100 callouts. Each call to
Http.send()counts as one callout, whatever the status code. A callout that fails with a timeout still counts. When you make the 101st, Apex throwsSystem.LimitException: Too many callouts: 101. You cannot catch aLimitException, so the transaction ends and rolls back. - Timeouts. If you do not set a timeout, each callout waits at most 10 seconds.
HttpRequest.setTimeout(milliseconds)accepts values up to 120000. The 120-second cumulative cap means that ten callouts that each take 15 seconds would exceed the budget, even though each is far under the 100-callout limit. - Waiting is not CPU time. Time spent waiting for the remote server does not count toward the CPU time limit. The callout limits are what bound that time.
- Size. The request body you build and the response body you receive both count against the size limit. A large JSON payload also uses heap, so a big callout can hit the heap limit before it hits the size limit.
Reading your usage at run time
The Limits class tells you how much of each limit you have used and what the maximum is. You can run this in anonymous Apex:
System.debug('Callouts: ' + Limits.getCallouts() + ' of ' + Limits.getLimitCallouts());
System.debug('SOQL queries: ' + Limits.getQueries() + ' of ' + Limits.getLimitQueries());
System.debug('DML statements: ' + Limits.getDmlStatements() + ' of ' + Limits.getLimitDmlStatements());
System.debug('CPU ms: ' + Limits.getCpuTime() + ' of ' + Limits.getLimitCpuTime());In a fresh anonymous Apex run, the callout line reads Callouts: 0 of 100. Checking Limits.getCallouts() against Limits.getLimitCallouts() before sending lets your code stop gracefully instead of failing with an uncatchable exception.
The classic mistake: a callout inside a loop
The most common way to exhaust the callout limit is to make one request per record. This class is valid, but it breaks as soon as it receives more than 100 records:
public class AccountPusher {
public static void pushOneByOne(List<Account> accounts) {
for (Account a : accounts) {
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:Billing_API/accounts');
req.setMethod('POST');
req.setHeader('Content-Type', 'application/json');
req.setBody(JSON.serialize(new Map<String, Object>{ 'id' => a.Id, 'name' => a.Name }));
new Http().send(req);
}
}
}A trigger handles up to 200 records per invocation, and a data load can fire many invocations in one transaction. One request per record fails with Too many callouts: 101, and it can also overrun the 120-second cumulative timeout much earlier. The fix is the same idea as bulkifying SOQL and DML: send one request for the whole batch, with a JSON array as the body. This tutorial uses that approach throughout.
Why this leads to asynchronous Apex
Taken together, these facts explain the design of the rest of the tutorial.
- A save is one transaction. Its record locks and uncommitted changes last until the commit.
- A callout depends on an external system, so its duration is outside your control.
- Limits cap the number, duration and size of callouts per transaction.
- Asynchronous Apex runs later, in a separate transaction, with its own limits. A callout made there does not hold up the user's save.
The next chapter shows how Salesforce enforces the separation between database changes and callouts, and what error you see if you ignore it.
Check your understanding
Exercise
A trigger on Account fires for a bulk insert of 200 records. A helper class it calls sends one HTTP request per account, and each request takes about 2 seconds. Which callout limits does this design break, and what is the fix?
Show answer
It breaks the limit of 100 callouts per transaction, because the 101st request throws an uncatchable System.LimitException ("Too many callouts: 101"). It also breaks the 120-second cumulative timeout, because 200 requests at about 2 seconds each is about 400 seconds. The fix is to bulkify: collect the records and send one request whose body is a JSON array of all of them. Then run that callout in asynchronous Apex, which a later chapter covers.
Exercise
You set req.setTimeout(120000) on every callout in a transaction and make five callouts that each take 40 seconds to answer. What happens, and why?
Show answer
The first three callouts finish after about 120 seconds in total, which uses up the cumulative callout timeout for the transaction. The next callout then fails with a limit exception, even though only a few of the 100 allowed callouts were used. The per-callout timeout and the cumulative timeout are separate limits, and both apply.
Exercise
Why does a synchronous callout in the middle of a save keep other users from updating the same records for longer than they otherwise would be blocked?
Show answer
The transaction holds record locks and uncommitted changes until the commit point at the end. The callout waits for an external system, so it adds the external system's response time to how long the locks are held.