Sub topic 1
Why move work out of the synchronous transaction
Prerequisites
This chapter assumes you can already do the following:
- Read and write basic Apex classes and methods.
- Write SOQL queries and DML statements.
- Name the main governor limits, such as SOQL queries and CPU time.
- Explain how an Apex trigger runs inside a save operation.
- Write a basic Apex unit test.
The synchronous transaction
When a user saves a record, Salesforce runs your trigger code inside one transaction. The user waits until the transaction finishes. If any line throws an uncaught exception, the whole transaction rolls back, including the record the user saved.
Synchronous work therefore has three costs:
- The user waits. Slow code makes the save slow.
- Limits are tighter. Everything in the save shares one set of governor limits.
- Failures spread. An error in secondary work, such as notifying another system, can undo the primary save.
Three reasons to go asynchronous
Asynchronous Apex runs later, in its own transaction, with its own limits. You move work there for these reasons:
- Limits. A synchronous transaction gets 10,000 ms of CPU time and 6 MB of heap. An asynchronous one gets 60,000 ms and 12 MB. The SOQL query limit rises from 100 to 200.
- Callouts. A trigger cannot make an HTTP callout directly. Code that makes a callout after DML in the same transaction also fails with "You have uncommitted work pending." Async code starts with a clean transaction, so it can make the callout.
- Isolation. If the async job fails, the original save is already committed and stays committed.
The next chapter covers the limits in detail.
A worked example
Suppose every new Account must be sent to a partner system. This trigger tries to do it in the save transaction:
trigger AccountTrigger on Account (after insert) {
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:Partner_API/accounts');
req.setMethod('POST');
req.setBody(JSON.serialize(Trigger.new));
HttpResponse res = new Http().send(req); // fails: callouts are not allowed in a trigger
}The callout throws an exception, so the whole save fails. The fix is to hand the work to an async method and let the trigger return quickly:
trigger AccountTrigger on Account (after insert) {
PartnerSync.sendAccountNames(Trigger.newMap.keySet());
}public class PartnerSync {
@future(callout=true)
public static void sendAccountNames(Set<Id> accountIds) {
List<Account> accts = [SELECT Id, Name FROM Account WHERE Id IN :accountIds];
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:Partner_API/accounts');
req.setMethod('POST');
req.setBody(JSON.serialize(accts));
HttpResponse res = new Http().send(req);
System.debug(res.getStatusCode());
}
}The trigger now only queues the work. The user's save finishes first. The callout runs afterward in a new transaction. Note that the method receives record Ids and queries the records itself, so it works with current data when it eventually runs. The @future annotation is explained in the chapter on future methods.
What you give up
Async work is not free. Keep these trade-offs in mind:
- No immediate result. The caller cannot read a return value or use the outcome in the same transaction.
- No guaranteed start time. Jobs wait in a queue, so they may start seconds or minutes later.
- Separate failures. You must log and handle errors yourself, because the user never sees them.
- Org-wide caps. Salesforce limits how many async jobs you can run per day, so moving everything to async does not scale forever.
Keep work synchronous when the user needs the result right away, such as validating input before a save.
The four tools
Salesforce offers four main async tools: @future methods, Queueable Apex, Batch Apex, and Scheduled Apex. Each fits a different kind of work. The rest of this tutorial compares them, starting with the limits that apply in every async context.
Exercise
A trigger on Opportunity must call an external pricing API after the record is inserted. The call currently fails inside the trigger. Name two reasons moving it to async Apex fixes the problem, and one thing you lose.
Show answer
Async Apex runs in a separate transaction, so it can make an HTTP callout without the "uncommitted work pending" error, and it gets higher limits (such as 60,000 ms CPU instead of 10,000 ms). You lose the immediate result, because the trigger cannot use the API response, and you must handle failures yourself because the user's save has already committed.