Sub topic 9
Keeping the pattern bulk-safe
This chapter assumes you can write a trigger and know the basic governor limits. It also assumes you have read the earlier chapters on Queueable callouts and on passing Ids into async code.
Why bulk safety matters here
A trigger runs once for each chunk of up to 200 records. A single transaction can contain many chunks. If each record starts its own async job, you reach the limits quickly. Two limits matter most:
| Limit | Value |
|---|---|
| Queueable jobs enqueued in one synchronous transaction | 50 |
| `@future` calls in one transaction | 50 |
| Callouts in one transaction (sync or async) | 100 |
| Queueable jobs enqueued from a running Queueable | 1 |
The anti-pattern
This trigger enqueues one job per record:
trigger AccountSyncTrigger on Account (after insert) {
for (Account a : Trigger.new) {
// Fails on the 51st record with a LimitException
System.enqueueJob(new AccountSyncJob(new Set<Id>{ a.Id }));
}
}Inserting 200 accounts throws "Too many queueable jobs added to the queue: 51". A @future method called inside the loop fails the same way.
The fix: one job per trigger invocation
Enqueue once, outside any loop, and pass all the Ids. This is the pattern from the earlier chapters.
trigger AccountSyncTrigger on Account (after insert) {
System.enqueueJob(new AccountSyncJob(Trigger.newMap.keySet()));
}The job re-queries the records and sends them in one bulk request. This costs one enqueue and one callout for up to 200 records.
When one request is not enough
Some APIs cap the number of items per request. Your payload may also approach the heap limit, which is 12 MB in async code. In both cases, split the Ids into chunks. Handle one chunk per job and chain the next job from inside execute. A Queueable can enqueue only one child job, so chaining fits this limit.
public class AccountChunkSyncJob implements Queueable, Database.AllowsCallouts {
private static final Integer CHUNK_SIZE = 100;
private List<Id> pending;
public AccountChunkSyncJob(List<Id> pending) {
this.pending = pending;
}
public void execute(QueueableContext ctx) {
List<Id> current = new List<Id>();
List<Id> rest = new List<Id>();
for (Integer i = 0; i < pending.size(); i++) {
if (i < CHUNK_SIZE) {
current.add(pending[i]);
} else {
rest.add(pending[i]);
}
}
List<Account> accounts = [SELECT Id, Name FROM Account WHERE Id IN :current];
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:Billing_API/accounts');
req.setMethod('POST');
req.setHeader('Content-Type', 'application/json');
req.setBody(JSON.serialize(accounts));
HttpResponse res = new Http().send(req);
if (res.getStatusCode() < 200 || res.getStatusCode() >= 300) {
System.debug(LoggingLevel.ERROR, 'Sync failed: ' + res.getStatusCode());
}
if (!rest.isEmpty() && !Test.isRunningTest()) {
System.enqueueJob(new AccountChunkSyncJob(rest));
}
}
}The Test.isRunningTest() check is there because Apex does not allow chained Queueables in tests.
Common mistakes
- Enqueueing inside a
forloop overTrigger.new. - Calling a
@futuremethod from a Queueable, a batch job or another future method. This is not allowed. - Making one callout per record inside the job. A 200-record chunk would then need 200 callouts, and the limit is 100.
- Passing sObjects instead of Ids. The records may be stale by the time the job runs.
Exercise
A trigger on Contact (after insert) calls System.enqueueJob inside a loop over Trigger.new. A user imports 120 contacts in one transaction. What happens, and how do you fix it?
Show answer
The 51st enqueueJob call throws a LimitException because a synchronous transaction can enqueue only 50 Queueable jobs. Move System.enqueueJob outside the loop and pass all the Contact Ids to one job. Inside the job, re-query the contacts and send them in one bulk request, or in chunks that respect the 100-callout limit.