Sub topic 16
Moving Heavy Work to Queueable Apex
This chapter assumes you can write a handler class, that you know how a trigger receives a list of up to 200 records, and that you have used SOQL and DML in bulk. It covers when a trigger should hand work to a Queueable job, and how to do that safely.
Why offload work
A trigger runs inside the transaction that saved the records. That transaction has one set of governor limits, and the user waits for it to finish. Some work does not belong there:
- Callouts to external systems. Callouts are not allowed in a trigger's synchronous context, so they must run in asynchronous Apex.
- Heavy queries or DML that approach the synchronous limits, such as 100 SOQL queries and 150 DML statements.
- Work that is not needed for the record to save, such as syncing data or recalculating related records.
Asynchronous Apex runs in a separate transaction with its own, higher limits. For example, it allows 200 SOQL queries instead of 100, and a heap of 12 MB instead of 6 MB.
Queueable Apex in a trigger
A Queueable class implements the Queueable interface. You pass it the data it needs, then call System.enqueueJob(). The job starts after the current transaction commits.
public with sharing class FollowUpTaskJob implements Queueable {
private Set<Id> opportunityIds;
public FollowUpTaskJob(Set<Id> opportunityIds) {
this.opportunityIds = opportunityIds;
}
public void execute(QueueableContext context) {
List<Opportunity> opps = [
SELECT Id, OwnerId
FROM Opportunity
WHERE Id IN :opportunityIds
];
List<Task> tasks = new List<Task>();
for (Opportunity opp : opps) {
tasks.add(new Task(
Subject = 'Send welcome package',
WhatId = opp.Id,
OwnerId = opp.OwnerId
));
}
if (!tasks.isEmpty()) {
insert tasks;
}
}
}The handler collects the IDs and enqueues one job for the whole batch:
public with sharing class OpportunityAsyncHandler {
public static void enqueueFollowUps(List<Opportunity> newOpps) {
Set<Id> wonIds = new Set<Id>();
for (Opportunity opp : newOpps) {
if (opp.StageName == 'Closed Won') {
wonIds.add(opp.Id);
}
}
if (!wonIds.isEmpty()) {
System.enqueueJob(new FollowUpTaskJob(wonIds));
}
}
}Call this from an after trigger. Record IDs exist only after insert, and the job needs them to query the records.
Bulkify the enqueue itself
Enqueuing is also a limited operation. A synchronous transaction can add at most 50 jobs with System.enqueueJob(). Calling it inside a loop repeats the same mistake as SOQL in a loop. Build one collection, then enqueue one job per transaction.
// Anti-pattern: up to 200 jobs from one trigger invocation
for (Opportunity opp : Trigger.new) {
System.enqueueJob(new FollowUpTaskJob(new Set<Id>{ opp.Id }));
}Common errors
- Passing stale records. The job runs later, so the data may have changed. Pass IDs and re-query inside
execute. - Passing non-serializable members. Queueable state is serialized. Keep members to primitives, sObjects, collections, and Apex classes that are serializable.
- Assuming order or timing. The job runs when system resources allow. Do not write logic that expects it to finish before the user sees the result.
- Chaining without a guard. A job can enqueue another job, but only one child job per
execute. Always have a stop condition. - Hiding failures. Errors in the job do not reach the user who saved the record. Log them, or check results with the
AsyncApexJobobject.
Exercise
A trigger on Opportunity must call an external system for every record that moves to Closed Won. Why is a Queueable job the right choice, and how many jobs should one trigger invocation enqueue?
Show answer
Callouts cannot run in a trigger's synchronous context, and a Queueable job runs in its own transaction where callouts are allowed. The trigger should collect the IDs of all qualifying records in a Set and enqueue a single job, because enqueuing inside a loop risks exceeding the limit of 50 jobs per synchronous transaction. The job should implement Database.AllowsCallouts and re-query the records by ID.