Sub topic 13
Asynchronous Apex for long-running or high-volume work
This chapter assumes you have read the chapters on governor limits and Apex triggers. You should know what a transaction is, why Apex code must be bulk safe, and how a trigger receives a list of records in Trigger.new. You should also be able to read simple Apex and SOQL.
Why asynchronous Apex exists
Synchronous Apex runs while the user waits. A trigger, a controller action or a flow-invoked Apex action all run inside the transaction that saves the record. That transaction has tight limits: 100 SOQL queries, 150 DML statements and 10 seconds of CPU time. It also has a small heap and a callout time cap.
Asynchronous Apex runs later, in a separate transaction, after the original one has committed. Salesforce queues the work and starts it when resources are free. Each asynchronous job gets its own, usually larger, limits.
The trade-off is timing. You get more room, but the work does not finish before the user sees the saved record. You also cannot assume when it starts.
| Limit | Synchronous | Asynchronous |
|---|---|---|
| SOQL queries per transaction | 100 | 200 |
| Heap size | 6 MB | 12 MB |
| CPU time | 10,000 ms | 60,000 ms |
| DML statements | 150 | 150 |
Check the current Apex Developer Guide for exact numbers, because Salesforce can change them.
Reasons to move work out of the transaction
Reach for asynchronous Apex when one of these is true:
- The work calls an external web service. Callouts are not allowed after uncommitted DML in the same transaction, and they slow the save.
- The work touches more records than a single transaction can safely handle.
- The work is not needed for the user's next step, such as recalculating a rating on related records.
- The work should run at a set time, such as a nightly cleanup.
If the work only changes the record being saved, do not go asynchronous. A before-save flow or a before trigger is faster and simpler, as the first trigger example in this tutorial shows.
The four asynchronous options
| Option | Best for | Key property |
|---|---|---|
| `@future` method | One short fire-and-forget task, such as a callout | Static method, primitive parameters only, no job ID returned |
| Queueable Apex | Most background work | Accepts complex types, returns a job ID, can chain jobs |
| Batch Apex | Very large data sets, up to millions of records | Processes records in chunks, each chunk in its own transaction |
| Scheduled Apex | Work at a fixed time | Runs a class on a cron schedule, often starting a batch |
Queueable Apex is the usual first choice. It does what @future does and adds object parameters, monitoring and chaining.
A Queueable example
The class below recalculates the rating for a list of accounts. It receives only IDs, then runs one query and one DML statement for the whole list.
public class RecalculateRatingJob implements Queueable {
private List<Id> accountIds;
public RecalculateRatingJob(List<Id> accountIds) {
this.accountIds = accountIds;
}
public void execute(QueueableContext context) {
List<Account> accounts = [SELECT Id, AnnualRevenue FROM Account WHERE Id IN :accountIds];
for (Account acc : accounts) {
acc.Rating = (acc.AnnualRevenue != null && acc.AnnualRevenue >= 1000000) ? 'Hot' : 'Warm';
}
update accounts;
}
}
// Enqueue from Apex, for example inside a trigger handler:
// System.enqueueJob(new RecalculateRatingJob(accountIdList));Passing IDs and re-querying inside execute is deliberate. By the time the job runs, the records may have changed. A fresh query gives you current data. It also keeps the serialized job small.
Enqueueing from a trigger
Call System.enqueueJob once per transaction, not once per record. A trigger that enqueues inside a loop hits the limit of 50 jobs per transaction.
trigger AccountRatingTrigger on Account (after update) {
List<Id> changedIds = new List<Id>();
for (Account acc : Trigger.new) {
if (acc.AnnualRevenue != Trigger.oldMap.get(acc.Id).AnnualRevenue) {
changedIds.add(acc.Id);
}
}
if (!changedIds.isEmpty()) {
System.enqueueJob(new RecalculateRatingJob(changedIds));
}
}The trigger collects the IDs in the loop and enqueues a single job after it. It also enqueues only when the revenue actually changed. That check prevents wasted jobs and helps avoid loops, because the job's own update fires the trigger again. Here the job changes Rating, not AnnualRevenue, so the condition stops the cycle.
Job flow
Chaining jobs
A Queueable job can enqueue one more job from its execute method. This is called chaining. Use it when step two depends on step one finishing, or when you want to split work into slices.
In a production org the depth of a chain is not capped, but each link adds a new job to the queue and you can only enqueue one child per execution. In Developer Edition and trial orgs the chain depth is limited to 5. Always give a chain a clear stopping condition, or it will run forever.
Batch Apex for large volumes
Batch Apex splits a large data set into chunks. The default chunk size is 200 records, and each chunk runs in its own transaction with fresh limits. A batch class implements Database.Batchable<SObject> and has three methods:
startreturns the records to process, usually as aDatabase.QueryLocator, which can cover up to 50 million records.executereceives one chunk and does the work.finishruns once at the end, for example to send a summary email or start another job.
public class StaleOpportunityBatch implements Database.Batchable<SObject> {
public Database.QueryLocator start(Database.BatchableContext bc) {
return Database.getQueryLocator(
'SELECT Id, StageName FROM Opportunity ' +
'WHERE IsClosed = false AND LastActivityDate < LAST_N_DAYS:90'
);
}
public void execute(Database.BatchableContext bc, List<Opportunity> scope) {
for (Opportunity opp : scope) {
opp.StageName = 'Closed Lost';
}
update scope;
}
public void finish(Database.BatchableContext bc) {
System.debug('Stale opportunity cleanup finished.');
}
}
// Run it with a chunk size of 200:
// Database.executeBatch(new StaleOpportunityBatch(), 200);If one chunk fails, earlier chunks stay committed. Design batch work so that you can re-run it safely.
Scheduled Apex
Scheduled Apex implements Schedulable and runs on a cron expression. Its execute method usually just starts a batch, because a scheduled class is subject to normal synchronous limits.
public class StaleOpportunitySchedule implements Schedulable {
public void execute(SchedulableContext sc) {
Database.executeBatch(new StaleOpportunityBatch(), 200);
}
}
// Run every day at 2:00 AM:
// System.schedule('Stale opps nightly', '0 0 2 * * ?', new StaleOpportunitySchedule());For simple nightly work on a moderate number of records, a scheduled flow (covered earlier) is often enough and needs no code. Choose scheduled Apex when volume or logic outgrows Flow.
Common errors
- Enqueueing inside a loop. This breaks the limit of 50
enqueueJobcalls per transaction. Collect IDs first. - Assuming order or timing. A job may start seconds or minutes later. Never write code that expects the result to be ready on the next line.
- Enqueueing from a Queueable more than once. A running job can enqueue only one child job.
- Using async to hide a bulk bug. A query inside a loop still fails in a batch chunk or a job. Fix the loop first.
- Trigger recursion. An update in the job fires triggers again. Guard with a changed-field check.
- Ignoring failures. A job that throws an unhandled exception fails quietly from the user's view. Check Apex Jobs in Setup and consider a
Finalizer(System.attachFinalizer) to log or retry failures. - Testing without
Test.startTestandTest.stopTest. Async work runs only whenTest.stopTest()is called, so assertions placed before it see no result.
@isTest
private class RecalculateRatingJobTest {
@isTest
static void setsHotRating() {
Account acc = new Account(Name = 'Big Co', AnnualRevenue = 5000000);
insert acc;
Test.startTest();
System.enqueueJob(new RecalculateRatingJob(new List<Id>{ acc.Id }));
Test.stopTest();
Account result = [SELECT Rating FROM Account WHERE Id = :acc.Id];
System.assertEquals('Hot', result.Rating);
}
}Decision guide
- Does the work only change the record being saved? Use a before-save flow or before trigger, not async.
- Is it a callout, or slow work the user need not wait for? Use Queueable.
- Does it process tens of thousands of records or more? Use Batch.
- Must it run at a set time? Use a scheduled flow for small jobs, or Scheduled Apex that starts a Batch for large ones.
Exercise
An after-update trigger on Account loops over Trigger.new and calls System.enqueueJob(new RecalculateRatingJob(new List<Id>{ acc.Id })) for each account. A user loads 200 accounts through Data Loader and the load fails. Why, and how do you fix it?
Show answer
One transaction can enqueue at most 50 jobs, so the loop fails once it passes that count. Collect the IDs of the changed accounts into one list inside the loop, then call System.enqueueJob once after the loop with the whole list. The job already handles a list in one query and one update.
Exercise
You must update 3 million Contact records every night to set a regional field from a lookup table. Which asynchronous option fits, and what starts it?
Show answer
Batch Apex fits, because it processes records in chunks of up to 200 and each chunk has its own limits, and a QueryLocator can cover millions of records. A Schedulable class started with a cron expression, such as '0 0 2 ?', calls Database.executeBatch to run it every night.