Sub topic 1
Why Asynchronous Apex: Separate Transactions and Fresh Limits
Prerequisites
This chapter assumes you already know the following:
- Basic Apex syntax and classes.
- What a transaction is in Apex, and that governor limits apply to each transaction.
- SOQL queries and DML statements (
insert,update). - How to write a simple test with
@IsTest.
You do not need to know anything about queueable jobs yet. This chapter explains the idea behind asynchronous Apex. The later chapters build on it.
What "asynchronous" means in Apex
Most Apex runs synchronously. A user saves a record, a trigger fires, and the user waits until all the code finishes. Everything happens in one transaction, and the transaction either commits or rolls back as a unit.
Asynchronous Apex works differently. Your code asks the platform to run some work later. The request returns immediately, and the current transaction carries on and finishes. The platform starts the deferred work in its own transaction when resources are available.
That gives you two properties that the rest of this tutorial depends on:
- A separate transaction. The deferred work commits or fails on its own. A failure in the job does not roll back the transaction that requested it, and the reverse is also true.
- A fresh set of governor limits. The job does not share the requester's counters. It starts with zero queries, zero DML statements, and zero CPU time used.
Apex has four main asynchronous features: future methods, Queueable Apex, Batch Apex, and Scheduled Apex. This tutorial focuses on Queueable Apex. It is the most flexible of the four for everyday work. A later chapter compares them.
Separate transactions
When you call System.enqueueJob, the platform records the request and returns a job ID. It does not run the job inline. The job starts after your current code has finished its work, in a new transaction.
Three practical consequences follow.
You cannot rely on timing. The job might start a second later or several minutes later, depending on platform load. Do not write code that assumes the job has finished by the time the next line runs.
You cannot return a result directly. enqueueJob returns only an ID. The job's output must go somewhere durable, such as a record update, a log object, or a platform event. The caller cannot read a return value.
Errors are isolated. If the job throws an unhandled exception, the user who triggered it does not see that exception. The original transaction is already committed. This is useful for work that should not block the user. It also means failures are easy to miss unless you plan for them. Transaction finalizers, covered later, exist for this purpose.
Problems that a separate transaction solves
Some operations are awkward or impossible inside one synchronous transaction. Moving them to a job is a common fix.
- Mixed DML. Apex does not allow DML on setup objects, such as
Userin many cases, and on non-setup objects, such asAccount, in the same transaction. Splitting the work into two transactions avoids the error. - Callouts after DML. A transaction that has made uncommitted changes cannot make a callout. A job runs in a clean transaction, so the callout can happen there. Making callouts from a job needs one extra interface, which a later chapter covers.
- Slow work behind a fast action. A trigger should finish quickly. Heavy processing can move to a job so the user does not wait for it.
Fresh governor limits
Governor limits protect the shared multitenant platform. Each transaction gets its own budget. Because a job is its own transaction, it gets a new budget, and for some limits the budget is larger than the synchronous one.
| Limit (per transaction) | Synchronous | Asynchronous |
|---|---|---|
| SOQL queries issued | 100 | 200 |
| DML statements | 150 | 150 |
| Records returned by SOQL | 50,000 | 50,000 |
| Heap size | 6 MB | 12 MB |
| CPU time | 10,000 ms | 60,000 ms |
| Callouts | 100 | 100 |
Check the current Apex Developer Guide before you depend on an exact number. Salesforce can change limits between releases. The pattern is stable: the query, heap, and CPU budgets are larger in asynchronous contexts, and several others stay the same.
The key point is that the numbers reset. If a synchronous transaction has used 90 of its 100 queries, a job it enqueues still starts with 200 available. Splitting work across several jobs multiplies your total capacity, but each job still has to fit within its own limits.
Seeing the difference yourself
The Limits class reports both the limit and the amount used so far. You can run the following in Anonymous Apex, using the Developer Console or the VS Code Execute Anonymous command.
public class LimitsProbeJob implements Queueable {
public void execute(QueueableContext context) {
System.debug('ASYNC SOQL limit: ' + Limits.getLimitQueries());
System.debug('ASYNC SOQL used: ' + Limits.getQueries());
System.debug('ASYNC heap limit: ' + Limits.getLimitHeapSize());
System.debug('ASYNC CPU limit: ' + Limits.getLimitCpuTime());
}
}Save that class in your org. Then run this in Anonymous Apex:
System.debug('SYNC SOQL limit: ' + Limits.getLimitQueries());
System.debug('SYNC heap limit: ' + Limits.getLimitHeapSize());
System.debug('SYNC CPU limit: ' + Limits.getLimitCpuTime());
Id jobId = System.enqueueJob(new LimitsProbeJob());
System.debug('Enqueued job: ' + jobId);
System.debug('Queueable jobs used so far: ' + Limits.getQueueableJobs());The first three lines print the synchronous limits (100 queries, 6,000,000 bytes of heap, 10,000 ms of CPU). The job writes its own lines to the debug log a little later, with the larger asynchronous values. Open the debug log for the job's own execution, not the one for your Anonymous Apex run. The last line prints 1, because the current transaction has used one of its allowed enqueues.
Limits on the asynchronous mechanism itself
Asynchronous work has its own limits, separate from the per-transaction ones above. You will meet them in detail later, but you should know they exist.
- Enqueue limit. A synchronous transaction can enqueue up to 50 queueable jobs. A job that is already running asynchronously can enqueue only one child job in the standard setup. This is why chaining works one link at a time.
- Daily asynchronous execution limit. The org has a rolling 24-hour allowance for asynchronous Apex executions. It is based on the license counts in the org, with a minimum value. High-volume designs must account for it.
- Platform queue. Jobs wait in a shared queue. Your job competes with other work, so latency varies.
What a job does not inherit
Because a job is a new transaction, it does not carry over any state from the requester automatically.
- Static variables. They are reset. Each transaction gets its own copy of the static state.
- Local variables and the call stack. They are gone. Only what you pass in explicitly reaches the job.
- Uncommitted data. The job sees only committed data. Records the requester inserted but has not yet committed are not visible if the job runs before the commit. In practice you enqueue from within the transaction and the job starts afterward, but you should not depend on the job reading values that the requester changed in memory.
- User and sharing context. A job runs as the user who enqueued it, and it follows the sharing declaration of the class (
with sharing,without sharing, or inherited). Check this when a job needs to read or write records the user cannot normally see.
The next chapters show how to pass data in through member variables, which is the standard answer to the first two points.
When asynchronous is the wrong answer
Moving work to a job has costs. Weigh them before you do it.
- The user cannot see the result right away. If the screen must show the outcome of the work, keep it synchronous or have the page refresh from the job's output.
- Debugging is harder. The failure appears in a different debug log from the action that caused it.
- Total platform throughput is limited. Enqueueing a job for every record in a bulk load can hit the enqueue limit or fill the queue.
- Ordering is not guaranteed between independent jobs. If step B must follow step A, chain B from A. Do not enqueue both from the same place and hope.
A good rule is to use asynchronous Apex when the work is slow, needs more room than a synchronous transaction allows, needs a clean transaction, or does not need to finish before the user gets a response.
Where this chapter leads
The rest of the tutorial follows from the two properties above. A separate transaction is why a job needs its state passed in, why failures need special handling, and why chaining is the way to continue work. Fresh limits are why chaining can process a large data set one slice at a time. Next, you write your first Queueable class.
Exercise
A trigger has already run 95 SOQL queries when it calls System.enqueueJob. The enqueued job needs to run 150 queries. Will the job succeed on the query limit, and why?
Show answer
Yes. The job runs in its own transaction with fresh limits, and the asynchronous SOQL limit is 200, so 150 queries fit. The 95 queries the trigger used do not count against the job. The job would fail only if it exceeded 200 queries in its own run.
Exercise
Name two reasons an unhandled exception in a queueable job is easy to miss, and one thing that separates it from an exception in a trigger.
Show answer
The job runs after the requesting transaction has committed, so the user never sees the exception, and the failure is logged in a different debug log from the action that caused it. Unlike a trigger exception, it does not roll back the requesting transaction, because the two are separate transactions.
Exercise
You need to insert a User and then an Account from one button click, and the combined DML fails with a mixed DML error. How can asynchronous Apex fix this?
Show answer
Do one of the two inserts in a queueable job. The job runs in a separate transaction, so the setup object DML and the non-setup object DML are no longer in the same transaction.