Sub topic 3
Asynchronous Apex and Automation Design
Assume you know Salesforce objects, Flow Builder, basic Apex, and SOQL. This chapter focuses on choosing tools when automation must handle time, volume, or several process steps.
Asynchronous Apex
Asynchronous Apex runs in a separate transaction instead of making the user wait. Queueable Apex is useful for a focused job that needs complex code or callouts. Batch Apex processes very large data sets in chunks. Scheduled Apex starts code at a defined time.
Each asynchronous transaction gets separate governor limits. Governor limits are platform limits on resources such as queries, DML statements, and CPU time.
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 accountRecord : accounts) {
accountRecord.Rating =
accountRecord.AnnualRevenue != null &&
accountRecord.AnnualRevenue >= 1000000
? 'Hot'
: 'Warm';
}
if (!accounts.isEmpty()) {
update accounts;
}
}
}Save Order and Conflicts
When Salesforce saves a record, validation, before-save flows, triggers, after-save flows, assignment or approval actions, and other automation can run in a defined order. A later update can cause the record to enter the cycle again.
Give each object one clear owner for a field or business action. Avoid a Flow updating a field that a trigger also changes. Make entry conditions narrow, consolidate related logic, and test insert, update, bulk, and recursion cases.
> callout note > Asynchronous work cannot immediately change the transaction that queued it. Design for eventual consistency and handle failures visibly.
Multi-User Processes
Flow Orchestrator coordinates stages that involve several users, such as review, approval, and fulfillment. Use it when the process needs assigned work and pauses between steps. Use a normal Flow for simpler automation.
Choosing a Tool
- Use a validation rule, formula, or roll-up when it solves the requirement.
- Use a before-save or after-save record-triggered Flow for routine record automation.
- Use a screen Flow for guided interaction.
- Use an approval process for formal sign-off.
- Use Queueable, Batch, or Scheduled Apex for complex, high-volume, or time-based work.
Testing and Monitoring
Test with realistic data volumes and multiple automation paths. Use Flow Debug, Apex tests, debug logs, and scheduled-job monitoring. Assert both immediate results and later asynchronous results. Log failures with enough context to replay or correct the job.
Exercise
A nightly process must recalculate 20 million records. Which tool is the best starting point?
Show answer
Batch Apex, because it processes records in manageable chunks with separate transactions.