Sub topic 9
Keeping the pattern bulk-safe
This chapter assumes you can write Apex triggers, know that a trigger receives up to 200 records per chunk, and have seen the per-transaction governor limits. It also assumes you have read the earlier chapters on the Queueable callout pattern and on passing Ids into async code.
By now you have a trigger that enqueues a Queueable job, and the job makes an HTTP callout. That works for one record. This chapter covers what happens when a data load, an integration, or a flow inserts hundreds of records, and how to design the pattern so it holds up.
The core rule: one job per transaction, not per record
A trigger runs once per chunk of up to 200 records. Trigger code must treat Trigger.new as a collection. The most common bulk mistake in async callouts is enqueuing work inside a loop:
trigger AccountSyncTrigger on Account (after insert) {
for (Account a : Trigger.new) {
// Wrong: one job per record
System.enqueueJob(new AccountSyncJob(new Set<Id>{ a.Id }));
}
}With 200 records in the chunk, this tries to enqueue 200 jobs. Apex stops it at the 51st with System.LimitException: Too many queueable jobs added to the queue: 51. The whole transaction rolls back, including the records the user was trying to save.
The fix is to enqueue once and pass every Id:
trigger AccountSyncTrigger on Account (after insert) {
System.enqueueJob(new AccountSyncChunkedJob(new List<Id>(Trigger.newMap.keySet())));
}The same rule applies to @future methods. Calling a future method inside a loop uses up the limit of 50 future calls per Apex invocation. Pass a Set<Id> instead.
The limits that shape the design
| Limit | Value |
|---|---|
| Records per trigger chunk | 200 |
| Callouts per transaction | 100 |
| Queueable jobs enqueued from a synchronous transaction | 50 |
| Queueable jobs enqueued from a running Queueable | 1 (a chain) |
| Future method calls per Apex invocation | 50 |
| Total callout time per transaction | 120 seconds |
| Request or response size | 6 MB synchronous, 12 MB asynchronous |
There is also a daily cap on asynchronous Apex executions for the org, shared across future, Queueable, Batch, and scheduled Apex. Check the current Salesforce documentation for exact numbers, because they change between releases.
Two of these limits interact with your payload design:
- Callout count. If you send one request per record, 200 records need 200 callouts. That is over the limit of 100, so the job fails partway through.
- Time. Each callout can take seconds. Twenty slow callouts can approach the 120-second total, even though 20 is far below 100.
The answer to both is the same. Send many records in each request, and cap how many requests one job makes.
Batching records into each request
The job in the earlier chapter already sends all accounts in a single request. That is correct for small volumes. It has two weaknesses at scale:
- The external API may reject or time out on very large bodies. Many APIs accept 100 to 1,000 items per request. Check your provider's documentation.
- A body that grows with the trigger chunk can approach the size limit if each record carries long text fields.
So split the Ids into groups that match the API's limit, and make one callout per group.
A chunked, chained Queueable
The next job handles both concerns. It sends records in groups of RECORDS_PER_CALLOUT and makes at most CALLOUTS_PER_JOB callouts. If Ids remain, it enqueues a single follow-up job with the remainder. A running Queueable may enqueue exactly one child job, so this forms a chain.
public class AccountSyncChunkedJob implements Queueable, Database.AllowsCallouts {
private static final Integer RECORDS_PER_CALLOUT = 100;
private static final Integer CALLOUTS_PER_JOB = 10;
private List<Id> accountIds;
public AccountSyncChunkedJob(List<Id> accountIds) {
this.accountIds = accountIds;
}
public void execute(QueueableContext ctx) {
Integer perJob = RECORDS_PER_CALLOUT * CALLOUTS_PER_JOB;
List<Id> current = new List<Id>();
List<Id> remaining = new List<Id>();
for (Integer i = 0; i < accountIds.size(); i++) {
if (i < perJob) {
current.add(accountIds[i]);
} else {
remaining.add(accountIds[i]);
}
}
// One query for the whole slice. Records deleted since the trigger ran are simply absent.
Map<Id, Account> accounts = new Map<Id, Account>(
[SELECT Id, Name FROM Account WHERE Id IN :current]
);
for (Integer start = 0; start < current.size(); start += RECORDS_PER_CALLOUT) {
List<Map<String, Object>> payload = new List<Map<String, Object>>();
Integer stop = Math.min(start + RECORDS_PER_CALLOUT, current.size());
for (Integer i = start; i < stop; i++) {
Account a = accounts.get(current[i]);
if (a != null) {
payload.add(new Map<String, Object>{ 'id' => a.Id, 'name' => a.Name });
}
}
if (payload.isEmpty()) {
continue;
}
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:Billing_API/accounts');
req.setMethod('POST');
req.setHeader('Content-Type', 'application/json');
req.setTimeout(20000);
req.setBody(JSON.serialize(payload));
HttpResponse res = new Http().send(req);
if (res.getStatusCode() < 200 || res.getStatusCode() >= 300) {
System.debug(LoggingLevel.ERROR,
'Sync failed: ' + res.getStatusCode() + ' ' + res.getBody());
}
}
if (!remaining.isEmpty()) {
System.enqueueJob(new AccountSyncChunkedJob(remaining));
}
}
}Some details to notice:
- The constructor takes a
List<Id>because the job needs stable ordering to slice. ASet<Id>has no index. - The query runs once per job, not once per callout, and it happens before any callout. Queries are not DML, so they do not cause the uncommitted-work error.
- The
nullcheck handles records deleted between the trigger and the job. - With the constants above, one job makes at most 10 callouts and sends at most 1,000 records. That leaves wide margins under the 100-callout and 120-second limits.
- The remainder is enqueued only after the callouts finish. The job passes
remainingforward, so the chain carries the work without any further trigger involvement.
The chain depends on each link finishing before the next starts. If a link fails with an unhandled exception, the chain stops and the remaining Ids are lost. The next chapter shows how a Finalizer can re-enqueue the remainder.
Large loads create many transactions
A Data Loader insert of 10,000 accounts does not run as one transaction. Salesforce splits it into batches, and each batch fires the trigger in its own transaction with its own limits. If the batch size is 200, that gives 50 transactions, and each enqueues one job. Your per-transaction rule (one job per trigger invocation) keeps every one of those transactions far below the limit of 50 enqueues.
This also means 50 jobs can run in the async queue at roughly the same time. They run independently, and the external API sees concurrent requests. If the API has a rate limit, the trigger pattern cannot control that. In that case, consider a different design: write the pending records to a staging object, and let a scheduled or Batch job send them at a controlled pace. The later chapter on Batch Apex covers this.
Bulk-safety checklist
Review each trigger-to-async path against these questions:
- Does the trigger enqueue or call
@futureoutside of any loop? - Does the async code query once for the whole set of Ids, not once per Id?
- Does it send multiple records per request, sized to the API's limit?
- Is there a hard cap on the callouts made in one execution, with a chain for the rest?
- Does it tolerate records that were deleted or changed since the trigger ran?
- Does it avoid DML before a callout in the same execution?
Exercise
A trigger on Contact (after insert) receives 200 records. Each Contact must be sent to an API that accepts at most 50 records per request. The trigger enqueues one Queueable. How many callouts does that job make for the 200 records, and why is that safe? What happens if the same trigger instead enqueued one Queueable per Contact?
Show answer
The job makes 4 callouts (200 divided by 50), well under the limit of 100 callouts per transaction, and it stays far from the 120-second total. If the trigger enqueued one job per Contact, the 51st call to System.enqueueJob would throw a LimitException (too many queueable jobs), and the whole transaction, including the Contact inserts, would roll back.