Sub topic 16
Moving Heavy Work to Queueable Apex
This chapter assumes you can write a handler-based trigger, bulkify SOQL and DML with Sets and Maps, and read the basic governor limits. Bulkifying keeps a trigger within the limits for one transaction. Some work is still too slow, too large, or not allowed in a synchronous transaction. Queueable Apex lets the trigger hand that work to a separate transaction.
When bulkification is not enough
Some work does not fit in the triggering transaction even after bulkifying:
- Callouts. A trigger cannot make an HTTP callout synchronously. The callout must run in asynchronous code.
- CPU-heavy logic. Large calculations can exceed the 10,000 ms synchronous CPU limit.
- Long-running follow-up work. Recalculating related records is slow, and the user does not need to wait for it.
Asynchronous Apex runs after the triggering transaction finishes, in its own transaction with its own limits. Some of those limits are higher:
| Limit | Synchronous | Asynchronous |
|---|---|---|
| SOQL queries | 100 | 200 |
| DML statements | 150 | 150 |
| CPU time | 10,000 ms | 60,000 ms |
| Heap size | 6 MB | 12 MB |
Queueable Apex is the usual choice for trigger offloading. It accepts non-primitive members such as Sets and Lists. It returns a job ID you can monitor. It can chain to a follow-up job.
How the pieces fit together
The trigger collects IDs, the handler enqueues one job, and the job does the work later.
A Queueable for a rollup
The example uses standard fields only. When an opportunity moves to Closed Won, the job writes a summary of won opportunities onto the parent account.
public with sharing class AccountRollupJob implements Queueable {
private final Set<Id> accountIds;
public AccountRollupJob(Set<Id> accountIds) {
this.accountIds = accountIds;
}
public void execute(QueueableContext context) {
List<Account> toUpdate = new List<Account>();
for (AggregateResult ar : [
SELECT AccountId acct, COUNT(Id) won, SUM(Amount) total
FROM Opportunity
WHERE AccountId IN :accountIds AND StageName = 'Closed Won'
GROUP BY AccountId
]) {
toUpdate.add(new Account(
Id = (Id) ar.get('acct'),
Description = 'Won opportunities: ' + ar.get('won')
+ ', total: ' + ar.get('total')
));
}
if (!toUpdate.isEmpty()) {
update toUpdate;
}
}
}The job follows the same bulk rules as any other Apex. It makes one query and one DML statement for the whole set of accounts.
Enqueueing from the handler
The trigger stays thin:
trigger OpportunityRollupTrigger on Opportunity (after insert, after update) {
OpportunityRollupHandler.enqueueRollup(Trigger.new, Trigger.oldMap);
}The handler decides which records qualify, gathers their account IDs, and enqueues a single job:
public with sharing class OpportunityRollupHandler {
public static void enqueueRollup(
List<Opportunity> newOpps,
Map<Id, Opportunity> oldMap
) {
Set<Id> accountIds = new Set<Id>();
for (Opportunity opp : newOpps) {
Boolean isWon = opp.StageName == 'Closed Won';
Boolean wasWon = oldMap != null
&& oldMap.get(opp.Id).StageName == 'Closed Won';
if (isWon && !wasWon && opp.AccountId != null) {
accountIds.add(opp.AccountId);
}
}
if (!accountIds.isEmpty()) {
System.enqueueJob(new AccountRollupJob(accountIds));
}
}
}The handler uses an after trigger because the opportunities are already saved and have IDs when the job later queries them. It compares new and old stage values, as in the change-detection chapter, so only newly won opportunities cause work. The handler also null-checks oldMap, which is null on insert.
Rules that keep the offload safe
Enqueue once per transaction, not once per record
System.enqueueJob inside a loop is the same anti-pattern as SOQL in a loop. A synchronous transaction can enqueue at most 50 jobs. A batch of 200 records would fail on the 51st call.
The limit is also shared across everything in the transaction. Another trigger, a flow, or a package may already have enqueued jobs. When you are unsure, check the headroom first:
if (Limits.getQueueableJobs() < Limits.getLimitQueueableJobs()) {
System.enqueueJob(new AccountRollupJob(accountIds));
}A job that runs asynchronously can enqueue only one more job. This is the chaining limit, and it matters if your trigger fires from inside a Queueable or batch job. A loop of enqueues fails there on the second call.
Pass IDs, not stale records
The job runs later, so any sObject you pass in may be out of date by then. Pass IDs and re-query in execute, as the example does. This also keeps the serialized job small.
Do not rely on timing or order
Salesforce starts the job after the original transaction commits, but it does not promise when. Two jobs enqueued close together may run in either order. The user who saved the record may see the old summary for a few seconds. Design the feature so that a short delay is acceptable.
Think about errors differently
An uncaught exception in the job does not roll back the opportunity save, because that transaction has already committed. The user never sees the error. You need your own reporting, such as logging to a custom object or checking AsyncApexJob records:
List<AsyncApexJob> failed = [
SELECT Id, Status, ExtendedStatus
FROM AsyncApexJob
WHERE JobType = 'Queueable' AND Status = 'Failed'
ORDER BY CreatedDate DESC
LIMIT 10
];Watch for new trigger runs
The job updates accounts, so any account triggers fire again. Make sure the job's DML cannot loop back to the code that enqueued it. If it can, use the recursion guard from the previous chapter, remembering that static variables reset in each transaction. A guard in the trigger transaction does not protect the job's transaction.
Callouts need an explicit opt-in
To make an HTTP callout from the job, implement Database.AllowsCallouts alongside Queueable:
public with sharing class SyncJob implements Queueable, Database.AllowsCallouts {
public void execute(QueueableContext context) {
// HTTP callouts are allowed here, but not in the trigger itself.
}
}Choosing between async options
| Option | Best for | Main constraint |
|---|---|---|
| Queueable | Moderate work started from a trigger, chaining, non-primitive inputs | 50 enqueues per synchronous transaction |
| Future method | Simple fire-and-forget with primitive arguments | No job ID, no chaining |
| Batch Apex | Very large data volumes processed in chunks | More setup, runs in scheduled slices |
For a trigger that handles at most 200 records per invocation, Queueable is usually the simplest choice. Move to Batch Apex when the work spans many thousands of records.
Testing the async path
Asynchronous work only runs in tests when you wrap the triggering DML in Test.startTest() and Test.stopTest(). At stopTest, queued jobs run synchronously, so you can assert on their results afterward.
@IsTest
private class AccountRollupJobTest {
@IsTest
static void rollsUpWonOpportunitiesInBulk() {
List<Account> accounts = new List<Account>();
for (Integer i = 0; i < 200; i++) {
accounts.add(new Account(Name = 'Rollup ' + i));
}
insert accounts;
List<Opportunity> opps = new List<Opportunity>();
for (Account a : accounts) {
opps.add(new Opportunity(
Name = 'Opp for ' + a.Name,
AccountId = a.Id,
StageName = 'Prospecting',
CloseDate = Date.today().addDays(30),
Amount = 100
));
}
insert opps;
for (Opportunity o : opps) {
o.StageName = 'Closed Won';
}
Test.startTest();
update opps;
Test.stopTest();
Integer updated = [
SELECT COUNT() FROM Account
WHERE Id IN :accounts
AND Description LIKE 'Won opportunities: 1,%'
];
System.assertEquals(200, updated, 'Every account should have a rollup');
}
}This test updates 200 opportunities at once. If the handler enqueued a job per record, the update would fail on the 51st enqueue.
Summary of trade-offs
Offloading gives you higher limits and permits callouts. In exchange you accept delayed results, errors the user cannot see, and no ordering guarantees. Keep in the trigger anything the user must see immediately, such as validation with addError. Move only the slow or callout-dependent work into the job.
Exercise
A trigger on Contact loops over Trigger.new and calls System.enqueueJob(new ContactSyncJob(c.Id)) for each contact. A data load of 200 contacts fails. Why does it fail, and how do you fix it?
Show answer
A synchronous transaction can enqueue at most 50 jobs, so the 51st call throws a limit exception. Collect the contact IDs into a Set<Id> inside the loop, then call System.enqueueJob once with a job that accepts the whole set and processes it with one query and one DML statement. Optionally check Limits.getQueueableJobs() against Limits.getLimitQueueableJobs() before enqueueing.
Exercise
A Queueable job enqueued from an Opportunity trigger throws an unhandled exception after the opportunity has been saved. What happens to the opportunity, and where can you find the failure?
Show answer
The opportunity stays saved, because the triggering transaction committed before the job ran. The user sees no error. The failure appears on the AsyncApexJob record for the job (Status = 'Failed', with details in ExtendedStatus), so you can query it or add your own logging in execute.