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.
- Explain governor limits at a high level (Apex caps on queries, DML, CPU time and memory).
- Understand Apex triggers and the transaction they run in.
- Write a basic Apex unit test.
You don't need any prior knowledge of @future, Queueable, Batch, or Scheduled Apex. This chapter explains why those tools exist. The rest of the tutorial covers how each one works.
The synchronous transaction
Most Apex runs synchronously. A user clicks Save, a trigger fires, a controller method runs, or a REST endpoint is called. The platform runs your code inside one transaction and the caller waits until it finishes. If any part throws an unhandled exception, the whole transaction rolls back.
That model is simple and predictable. It also has three costs:
- The user waits. Every millisecond your code uses is a millisecond the page spins or the API caller blocks.
- Limits are tight. The synchronous governor limits are the strictest ones Apex has.
- Some operations are not allowed or not safe. Examples are callouts from a trigger and certain combinations of DML.
Moving work to asynchronous Apex means you ask the platform to run it later, in its own transaction, with its own limits. The original transaction commits and returns to the user without waiting.
Reason 1: Governor limits
Governor limits protect the shared multitenant platform. In a synchronous transaction, these are the limits that most often cause trouble. The async column shows the higher values that apply to future, Queueable, and Batch execution.
| Limit | Synchronous | Asynchronous |
|---|---|---|
| SOQL queries | 100 | 200 |
| DML statements | 150 | 150 |
| Rows returned by SOQL | 50,000 | 50,000 |
| Rows processed by DML | 10,000 | 10,000 |
| CPU time | 10,000 ms | 60,000 ms |
| Heap size | 6 MB | 12 MB |
| Callouts | 100 | 100 |
Two things stand out. CPU time is six times higher in async, and heap is doubled. The row limits are the same, so async alone does not let you update a million records in one transaction. Batch Apex solves that differently, by splitting the work across many transactions. The next chapter covers async limits in detail.
Check the current Apex Developer Guide for exact numbers. Salesforce adjusts limits over time, and some are per-transaction while others are org-wide.
Reason 2: User experience
Imagine a trigger on Account that recalculates a score by querying all related Opportunities, Contacts, and Cases, then updates several child records. In a sandbox with ten records it takes half a second. In production, a user imports 200 accounts through Data Loader and the transaction takes 40 seconds, or hits the CPU limit and fails.
If the user doesn't need the result of that work before the save completes, it doesn't belong in the save. Typical candidates:
- Recalculating derived data on related records.
- Sending data to an external system.
- Cleaning up or archiving records.
- Generating documents or notifications.
The test is simple: does the next screen, or the caller's next step, depend on this work being finished? If not, consider moving it out.
Reason 3: Operations that need a separate transaction
Some restrictions only go away when the work runs in its own transaction.
Callouts from triggers
A trigger cannot make a synchronous HTTP callout. The platform blocks it because the transaction holds database locks while the external system responds, and an external call has no guaranteed duration. Salesforce rejects trigger callouts at runtime with an error. The usual solution is to hand the callout to an async job.
Here is a trigger that delegates the callout, and the future method it calls. The next chapter explains the @future rules. Here the example only shows the pattern.
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());
}
}trigger AccountSyncTrigger on Account (after insert) {
// Pass only the Ids. The async method re-queries the current data.
PartnerSync.sendAccountNames(Trigger.newMap.keySet());
}The trigger finishes immediately. The callout happens afterward, in a transaction that has no locks held on behalf of the user's save.
Uncommitted work and callouts
A related rule applies outside triggers. If you perform DML and then try a callout in the same transaction, Apex throws a CalloutException with the message "You have uncommitted work pending. Please commit or rollback before calling out." The platform doesn't allow an open database transaction to wait on an external call. Moving either the DML or the callout into a separate async transaction removes the conflict.
Mixed DML
Salesforce separates setup objects from non-setup objects. Setup objects configure the org, and User, Group, and PermissionSetAssignment are examples. Non-setup objects hold business data, such as Account and Contact. You can't insert a User and an Account in the same transaction. The platform raises MIXED_DML_OPERATION. Running one of the two operations in an async job puts them in different transactions, which avoids the error.
Reason 4: Work that is bigger than one transaction
Some jobs are inherently large: archive every Lead untouched for a year, recalculate a field on millions of records, or run a nightly integration. No single transaction can handle that, even with async limits, because the row and DML caps still apply. For that work you need a tool that splits the job into many transactions (Batch Apex), and often one that starts it at a fixed time (Scheduled Apex).
Reason 5: Work that isn't triggered by a user at all
Some work has no user action behind it. It should happen at 02:00 every night, or every hour. A synchronous transaction needs a trigger event, a page request, or an API call to start it. Asynchronous Apex includes a scheduler, so code can start itself on a timetable.
What you give up
Async is not free. Before moving work out, accept these trade-offs:
- No guaranteed timing. The platform queues async work and runs it when resources allow. It usually starts within seconds, but it can wait minutes under load.
- No direct return value. You can't call an async job and use its result on the next line. Results arrive later, through saved data, a platform event, or a notification.
- Separate rollback. If the async job fails, the original transaction has already committed. You need your own error handling, retry, or logging to deal with that.
- Ordering is not guaranteed between independent async jobs. Don't assume a job you requested first will finish first.
- Org-wide caps. The org has a ceiling on how many async executions it can run per 24 hours and how many jobs can wait in the queue. Treating async as unlimited is a common mistake.
- Harder debugging and testing. The work runs outside the original request, in its own debug log. Tests need
Test.startTest()andTest.stopTest()to run it.
A quick sanity check before you go async
Ask these questions in order:
- Is the work needed to produce the response the user or caller sees? If yes, keep it synchronous.
- Is it blocked by a platform rule, such as a trigger callout or mixed DML? If yes, go async.
- Is it likely to approach a synchronous limit as data grows? If yes, go async, or redesign the query or logic first.
- Is it large enough to need many transactions, or does it need to run on a timetable? If yes, you need Batch or Scheduled Apex.
The four tools at a glance
The remaining chapters compare these four tools in depth. This table is only a map.
| Tool | Best known for |
|---|---|
| `@future` method | Simple fire-and-forget work, such as a callout from a trigger |
| Queueable Apex | Future-style work that needs richer parameters, job Ids, or chaining |
| Batch Apex | Processing large data sets in many separate transactions |
| Scheduled Apex | Starting code at a fixed time, often to launch a batch or queueable job |
Summary
Run work synchronously when the caller needs the result right away. Move it to async when it is slow, restricted by a platform rule such as trigger callouts or mixed DML, too large for one transaction, or should start on a schedule. In exchange, you accept delayed execution, no direct return value, separate failure handling, and org-wide async caps.
Exercise
A trigger on Opportunity updates the Opportunity and then must POST its data to an external billing system. The save currently fails with an error. Name two platform rules that could cause this, and say what moving the callout to an async job changes.
Show answer
First, triggers cannot make synchronous HTTP callouts. Second, if the code does DML and then makes a callout in the same transaction, Apex raises the "uncommitted work pending" CalloutException. An async job runs the callout in its own transaction after the save has committed. That removes both problems, but the callout then happens later, and the user doesn't see its result.
Exercise
A developer says, "I'll make this process asynchronous so it can update 500,000 records in one job, since async limits are higher." What is wrong with this reasoning?
Show answer
Async raises CPU time, heap, and SOQL query limits, but the row limits stay the same. A single async transaction can still process only 10,000 DML rows and retrieve 50,000 query rows. To handle 500,000 records, the work must be split across many transactions, which is what Batch Apex does.