Sub topic 8
Limits that shape your design
This chapter assumes you know basic Apex (triggers, SOQL, DML), the Salesforce REST API, and the callout and event examples from the earlier chapters. Salesforce is a multitenant platform, so it caps how much work one transaction, one user, or one org can do. Those caps decide which pattern is feasible, so read them as design input.
Documented limits change between releases and vary by edition. The numbers here are the commonly documented ones at the time of writing. Confirm them in the Salesforce documentation and, for your own org, in Setup or the /limits REST resource.
Three families of limits
Integration limits fall into three groups. Each group fails in its own way and calls for its own response.
| Family | Scope | Example | What happens on breach |
|---|---|---|---|
| Per-transaction governor limits | One Apex transaction | 100 callouts, 150 DML statements | An uncatchable `System.LimitException` rolls back the transaction |
| Org-wide allocations | Rolling 24 hours or per hour | API requests, async Apex executions, event delivery | Requests are rejected, for example `REQUEST_LIMIT_EXCEEDED` |
| Concurrency and size limits | Simultaneous work or payload size | Long-running requests, 6 MB response bodies | The request is rejected or fails |
Limits also apply to the remote system. A billing API that allows 50 requests per second will throttle you with HTTP 429 long before Salesforce stops you.
Request-reply: limits on outbound callouts
Request-reply from Apex is bound by these limits:
- 100 callouts per transaction. Each
Http.send()counts as one. - 120 seconds of cumulative callout time per transaction. A single callout can have a timeout of up to 120 seconds, and the default is 10 seconds. The sum across all callouts in the transaction cannot exceed 120 seconds.
- Request and response size. The response limit is 6 MB in synchronous Apex and 12 MB in asynchronous Apex.
- Concurrent long-running requests. An org can run only about 10 synchronous Apex requests that last longer than 5 seconds at the same time. Further requests fail. A slow external API therefore limits your concurrency as well as your response time.
A user waiting on a page layout or a Lightning component does not tolerate a 30-second callout, and a few such users can fill the concurrency limit.
Callouts and uncommitted work
Salesforce rejects a callout if the transaction has pending DML. You get System.CalloutException: You have uncommitted work pending. Please commit or rollback before calling out. The cause is that Salesforce will not hold a database transaction open while it waits on an external system.
Two rules follow:
- Make the callout before any DML in the same transaction.
- If the callout must follow a data change, such as a trigger reacting to a saved record, move it to a separate transaction.
You cannot call out synchronously from a trigger context that already has DML. Use a Queueable job that implements Database.AllowsCallouts. The job starts in a new transaction with fresh limits.
Sending many records in one callout
Calling out once per record in a loop runs into the 100-callout limit on the 101st record. It also multiplies latency. Prefer one request that carries many records, as long as the remote API accepts it:
public with sharing class InvoiceSyncJob implements Queueable, Database.AllowsCallouts {
private static final Integer CHUNK_SIZE = 200;
private List<Id> accountIds;
public InvoiceSyncJob(List<Id> accountIds) {
this.accountIds = accountIds;
}
public void execute(QueueableContext ctx) {
List<Account> accounts = [
SELECT Id, Name, AccountNumber
FROM Account
WHERE Id IN :accountIds
];
for (Integer i = 0; i < accounts.size(); i += CHUNK_SIZE) {
if (Limits.getCallouts() >= Limits.getLimitCallouts()) {
// Hand the remaining records to a new job instead of failing.
List<Id> remaining = new List<Id>();
for (Integer j = i; j < accounts.size(); j++) {
remaining.add(accounts[j].Id);
}
System.enqueueJob(new InvoiceSyncJob(remaining));
return;
}
List<Map<String, Object>> payload = new List<Map<String, Object>>();
for (Integer k = i; k < Math.min(i + CHUNK_SIZE, accounts.size()); k++) {
payload.add(new Map<String, Object>{
'salesforceId' => accounts[k].Id,
'name' => accounts[k].Name,
'accountNumber' => accounts[k].AccountNumber
});
}
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:Billing_API/accounts/bulk');
req.setMethod('POST');
req.setHeader('Content-Type', 'application/json');
req.setTimeout(30000);
req.setBody(JSON.serialize(payload));
HttpResponse res = new Http().send(req);
if (res.getStatusCode() >= 300) {
throw new CalloutException('Billing API returned ' + res.getStatusCode());
}
}
}
}The job sends 200 records per callout. It checks Limits.getCallouts() against Limits.getLimitCallouts() before each call, and it enqueues a continuation job when the budget is spent. Enqueue it from a trigger or other code with System.enqueueJob(new InvoiceSyncJob(ids)).
Chaining has limits too. A Queueable job can enqueue only one child job, and a transaction can enqueue up to 50 jobs. An unbounded chain of jobs still uses up your daily async allocation.
Inbound calls: API request limits
When an external system calls Salesforce through the REST or SOAP APIs, org-wide allocations apply:
- Total API requests per rolling 24 hours. The allocation depends on edition and licenses. A
Developer Editionorg has a small allocation, so a load test there can exhaust it quickly. - Concurrent long-running requests. About 25 API requests that run longer than 20 seconds can be active at the same time in production. Beyond that, callers get errors.
Every response from the REST API includes a Sforce-Limit-Info header, such as api-usage=18/100000. The /limits resource returns all current allocations and what remains:
GET /services/data/v60.0/limits
Authorization: Bearer <access_token>An integration that reads this header can slow down before it hits the ceiling.
You can reduce the number of requests by batching them:
| Mechanism | What it batches | Typical cap |
|---|---|---|
| sObject Collections | Create, update, upsert, or delete records of mixed types | 200 records per request |
| Composite API | Dependent subrequests that can reference earlier results | 25 subrequests |
| Composite Batch | Independent subrequests | 25 subrequests |
These mechanisms reduce HTTP round trips. They do not remove per-record work, so the transaction governor limits still apply to the records inside.
Fire-and-forget: limits on events
Fire-and-forget moves the cost off the publisher's critical path, but it has its own limits:
- Publishing counts as DML.
EventBus.publish()uses a DML statement and counts rows against the DML limits. Publishing events one at a time in a loop consumes statements quickly. Pass a list of events in one call instead. - Publishing allocations. Orgs have an hourly limit on events published. High-volume platform events have a higher ceiling than standard-volume ones.
- Delivery allocations. The number of events delivered to external subscribers (CometD or Pub/Sub API clients) in 24 hours is also capped. Apex trigger subscribers are not counted against this.
- Retention. Events stay available for replay for 72 hours. A subscriber that is offline longer than that cannot recover the missed events from the bus.
- Subscriber limits. An Apex trigger on a platform event is a normal Apex transaction with the usual governor limits. It receives events in batches of up to 2,000 records by default. A trigger that makes a callout for each event therefore breaks the 100-callout limit.
Change Data Capture events use the same event allocations. A busy object with many field updates can generate more change events than you expect, particularly during a data load.
The publisher gets a result from EventBus.publish(), as in the earlier example. That result shows only that Salesforce accepted the event. It tells you nothing about whether any subscriber processed it.
Batch sync: limits on bulk movement
Bulk API 2.0 is designed to avoid per-request overhead. Even so:
- Records per 24 hours. A rolling allocation caps the number of records processed through Bulk API 2.0 jobs. Check the current figure for your edition.
- Upload size. Each job accepts a limited amount of CSV data, so very large loads must be split across jobs.
- Not one call per record. A bulk job costs a handful of API requests (create, upload, close, poll), not one request per record.
- Processing happens in batches under the covers. Triggers, flows, and validation rules fire for each record, in chunks. A trigger that is not bulkified will fail even when the integration is well designed. Lock contention also occurs when parallel jobs update records that share a parent.
For an upsert job like the one in the earlier chapter, plan around these steps: size each CSV below the upload limit, avoid running two jobs that touch the same parent records, and poll the job state sparingly because each poll is an API request.
Techniques that follow from the limits
- Bulkify everything. Send lists, not single records. This applies to callouts, event publishes, DML, and SOQL.
- Move slow work off the user's transaction. Use Queueable Apex, Batch Apex with
Database.AllowsCallouts, or events. - Keep callouts before DML, or put them in a separate async transaction.
- Set realistic timeouts. A 120-second timeout on one callout uses the whole transaction budget.
- Watch the headroom. Read
Sforce-Limit-Info, call/limits, and useLimitsmethods in Apex. - Respect the remote system's limits. Honor
429responses and theRetry-Afterheader with a backoff. The next chapter covers retries in more detail. - Choose a pattern that fits the volume. Use Bulk API 2.0 for large loads instead of looping REST calls, and use events when a burst of messages should not block the sender.
Common mistakes
- Making one callout per record inside a trigger loop.
- Calling out after an
insertorupdatein the same transaction. - Setting a 120-second timeout and forgetting that the total per transaction is also 120 seconds.
- Treating
EventBus.publish()as free. It uses a DML statement. - Assuming events live forever. After 72 hours, a missed event cannot be replayed.
- Running a large Bulk API job during business hours, while users edit the same parent records.
- Testing in a sandbox or Developer Edition with different allocations from production.
Exercise
A trigger on Order publishes an event for each order, and an Apex trigger on that event makes one callout per event to a shipping API. During a data load of 1,000 orders, the subscriber fails. Name the limit that most likely causes the failure, and describe two changes that fix it.
Show answer
The subscriber trigger receives events in a batch and makes one callout per event, so it exceeds the 100-callouts-per-transaction limit once a batch has more than 100 events. Fix 1: collect the event payloads and send them in one or a few callouts with chunked bodies, if the shipping API accepts a list. Fix 2: have the trigger enqueue a Queueable job that implements Database.AllowsCallouts and processes the events in chunks, passing the remainder to a new job when the callout budget runs low. Also check that the publisher passes a list of events to EventBus.publish() so it does not use one DML statement per order.
Exercise
Why does Salesforce throw "You have uncommitted work pending" when you make a callout after an insert, and how do you avoid it?
Show answer
Salesforce will not keep a database transaction open while waiting for an external system. To avoid the error, make the callout before any DML in the transaction, or run the callout in a separate asynchronous transaction such as a Queueable job with Database.AllowsCallouts.