Sub topic 1
Why Run Code Asynchronously
This chapter explains why Apex has asynchronous processing and which problems it solves. It also shows where future methods fit. Later chapters cover the syntax and rules in detail.
Prerequisites
This chapter assumes you already know the following:
- Basic Apex syntax: classes, static methods, and collections such as
List,Set, andMap. - SOQL and DML basics: how to query records and how to use
insert,update, anddelete. - What an Apex trigger is and when it runs.
- That Salesforce enforces governor limits, which are per-transaction caps on resources such as queries, DML statements, and CPU time.
You do not need to have written any asynchronous Apex yet.
Synchronous code and its limits
Most Apex you write runs synchronously. A user saves a record, a trigger fires, and your code runs inside that same transaction. The user waits until all of it finishes. If any part throws an unhandled exception, the whole transaction rolls back.
This model is simple and predictable, but it has costs:
- The user waits. Slow work in a trigger makes the save feel slow.
- Limits are tight. Synchronous transactions get the smaller set of governor limits. For example, the synchronous CPU limit is 10,000 ms, and the total heap size is 6 MB.
- Some operations are not allowed. A transaction cannot always mix certain kinds of work, and a callout cannot happen in every context.
- Failures spread. An error in secondary work can roll back the primary work the user cared about.
Asynchronous Apex addresses these costs by moving work out of the current transaction.
What asynchronous means in Apex
Asynchronous code is queued to run later, in its own transaction. The original transaction finishes first. The platform then starts the queued work when resources are available.
The key idea is that the two pieces of work are separate transactions. Each has its own governor limits, and each commits or rolls back independently.
Problems that asynchronous processing solves
Slow work that the user should not wait for
Suppose a trigger must recalculate values on many related records after each save. If you do it inline, every save pays for it. Queueing the work lets the save return quickly and the follow-up happen in the background.
Higher limits
Asynchronous transactions generally get larger limits than synchronous ones. Two examples are shown in the table. Treat the numbers as a guide and check the current Salesforce documentation, because limits change between releases.
| Limit | Synchronous | Asynchronous |
|---|---|---|
| Total heap size | 6 MB | 12 MB |
| CPU time | 10,000 ms | 60,000 ms |
| SOQL queries issued | 100 | 200 |
Many limits, such as DML statements (150) and the number of records returned by SOQL (50,000), are the same in both modes.
Callouts from contexts that cannot make them
A callout is a request from Apex to an external web service. You cannot make a callout from a trigger directly, because the transaction would hold database locks while it waited for the remote system. Moving the callout into asynchronous code solves this. A future method with callout=true is the simplest way to do it, and a later chapter covers it.
Mixed DML errors
Salesforce separates setup objects, such as User and UserRole, from non-setup objects, such as Account. In many cases you cannot change both kinds in one transaction. Doing so raises a MIXED_DML_OPERATION error. If you run one of the operations in a separate transaction, the error goes away. Future methods are a common fix, and a later chapter walks through it.
Isolation of failures
Because the asynchronous work is a different transaction, an exception in it does not roll back the original save. The user's record is already committed. This is useful for optional follow-up work, but it also means you must handle failures yourself, since the user will not see the error.
Kinds of asynchronous Apex
Apex offers several ways to run work asynchronously. They differ in what they accept, how much they can do, and how much control you get.
| Mechanism | Typical use | Notes |
|---|---|---|
| Future method | Short, one-off background work and callouts | Static, returns `void`, primitive parameters only |
| Queueable Apex | Work that needs complex parameters or chaining | A class that implements `Queueable` |
| Batch Apex | Processing very large data sets in chunks | A class that implements `Database.Batchable` |
| Scheduled Apex | Work that runs at a set time | A class that implements `Schedulable` |
This tutorial focuses on future methods. The final chapter compares them with Queueable and Batch Apex so that you can choose between them.
A first look at a future method
A future method is a static method marked with the @future annotation. The next example is a minimal one. It takes a set of record IDs and updates the matching accounts.
public class AccountService {
@future
public static void updateAccountRatings(Set<Id> accountIds) {
List<Account> accounts = [SELECT Id, Rating FROM Account WHERE Id IN :accountIds];
for (Account a : accounts) {
a.Rating = 'Hot';
}
update accounts;
}
}Calling AccountService.updateAccountRatings(ids) does not run the body immediately. It adds a request to a queue and returns. The body runs later, in its own transaction.
Notice three things that you will study in the next chapters:
- The method is
staticand returnsvoid. - The parameter is a collection of IDs, not a collection of
Accountrecords. - The method queries the accounts again, so it works on current data and not on a stale copy.
What you give up
Asynchronous processing has trade-offs. Weigh them before you reach for it.
- No guaranteed timing. The platform decides when the work starts. It might run in a second or after a delay.
- No guaranteed order. Two queued future methods might not run in the order you called them.
- No direct result. A future method returns
void, so the caller cannot receive a value from it. - Harder to debug and test. The work is separated from the request that caused it. Tests need special handling, covered in a later chapter.
- Shared capacity. The org has limits on how many asynchronous requests it can queue and run. Overusing them can delay other work.
- Stale data risk. The data may change between the time you queue the work and the time it runs.
If the user needs the result right away, or if later code depends on the work being finished, keep the work synchronous.
A decision checklist
Before you make something asynchronous, ask these questions:
- Does the user need the result in the same request? If yes, stay synchronous.
- Is the work slow, limit-heavy, or dependent on an external system? If yes, asynchronous processing may help.
- Does it need a callout from a trigger, or does it hit a mixed DML error? If yes, a future method is a strong candidate.
- Can you pass what the work needs as primitives or IDs? If not, consider Queueable Apex.
- Will you process very large volumes of records? If yes, consider Batch Apex.
Common mistakes at this stage
- Treating asynchronous code as faster. It does not make the work run faster. It moves the work out of the user's wait time and into a separate transaction.
- Assuming the work has finished. After you call a future method, the work has only been queued. Code that follows it in the same transaction cannot rely on its results.
- Using it for every operation. Each queued request counts against org-wide and per-transaction limits. Use it where it solves a real problem.
- Ignoring errors. A failure in the background transaction does not reach the user. You need logging or monitoring, which a later chapter covers.
What comes next
The next chapter shows how to declare a future method and call it correctly. After that, you will learn which parameters it accepts, why you pass IDs, and how to handle callouts, mixed DML, limits, triggers, tests, and monitoring.
Exercise
A trigger on Account must send the new account to an external billing system when the account is created. Why does a direct callout in the trigger fail, and how does asynchronous processing fix it?
Show answer
A trigger runs inside a synchronous transaction that holds database locks, and Apex does not allow a callout there. If the code waited on a remote system, those locks would stay open. Moving the callout into a future method with callout=true runs it later in a separate transaction. That transaction is allowed to make the callout, and the original save commits without waiting.
Exercise
A developer queues a future method in a trigger and then, on the next line, queries the record expecting to see the future method's changes. Why does this not work?
Show answer
Calling a future method only adds a request to a queue. The method body runs later in a different transaction, after the current one finishes. The query in the original transaction runs before that happens, so it sees the old data.
Exercise
Name two reasons why you might choose to keep a piece of work synchronous instead of making it asynchronous.
Show answer
Any two of these: the user needs the result in the same request; later code in the transaction depends on the work being complete; you need a guaranteed order or timing; you need a return value; or you want errors to roll back the original save.