Sub topic 5
When a future method runs and in what order
This chapter assumes you can write Apex classes with static methods, run SOQL and DML, and read a debug log. You should also have declared a basic @future method, which the earlier chapters cover. Here the focus is timing: when the queued work starts, what state it sees, and what you can and cannot assume about order.
Calling a future method only queues it
A call to a future method does not run the method. The call puts a request on an asynchronous queue and returns immediately. The calling code keeps running, finishes, and commits. Later, when the platform has capacity, a separate process picks up the request and runs the method in its own transaction.
That gives three consequences:
- The caller cannot get a return value. Future methods must return
void. - The future method runs in a different transaction with its own governor limits and its own debug log.
- Salesforce does not promise when the method starts. It is usually seconds, but a busy org can make it minutes.
Seeing the order in a debug log
The class below makes the sequence visible. It has one future method that writes a debug line, and a method that calls it twice.
public class FutureOrderDemo {
@future
public static void logStep(String label) {
System.debug('Future running: ' + label + ', isFuture=' + System.isFuture());
}
public static void run() {
System.debug('1. before calls');
logStep('first');
logStep('second');
System.debug('2. after calls');
}
}Run FutureOrderDemo.run(); in Execute Anonymous with a debug log open. The first log shows only the lines 1. before calls and 2. after calls. The two Future running lines are not in it. Each future execution writes its own log, which appears a moment later in the Debug Logs list in Setup. In the Developer Console, it appears as a separate log entry.
The two future logs also tell you something about order. The labels first and second could appear in either order, and the two runs could overlap in time.
What is and is not guaranteed
Future methods are best-effort. The table separates what you can rely on from what you cannot.
| Question | Answer |
|---|---|
| Does the future method run after the calling transaction commits? | Yes. The queued request is released only when the calling transaction succeeds. |
| Does it run if the caller throws an unhandled exception? | No. The rollback discards the queued request. |
| Do two future calls run in the order you made them? | Not guaranteed. |
| Can two future calls run at the same time? | Yes. |
| Is there a guaranteed start time? | No. |
| Does it run with its own governor limits? | Yes. It gets the asynchronous limits, which are higher than the synchronous ones for some resources. |
| Do static variables carry over from the caller? | No. Each future execution starts with fresh static state. |
The practical rule is that every future call must stand on its own. It must produce a correct result no matter which other future calls ran before it, after it, or at the same time.
The future method sees committed data, not the caller's snapshot
Because the method runs after the caller commits, it sees the final state of the caller's work, not the state at the moment of the call. The following code makes this concrete.
public class FutureSnapshotDemo {
@future
public static void readName(Id accountId) {
Account a = [SELECT Name FROM Account WHERE Id = :accountId];
System.debug('Future sees name: ' + a.Name);
}
public static void run() {
Account a = new Account(Name = 'Before');
insert a;
readName(a.Id); // queued here
a.Name = 'After';
update a; // still in the same transaction
}
}Run FutureSnapshotDemo.run();. The future log prints Future sees name: After. The call happened while the name was Before, but the method did not run until the transaction had committed.
This is why the previous chapter told you to pass IDs and re-query. If you passed the name as a parameter, the future method would work with the stale value Before. A parameter is a copy taken at call time. A query reads whatever is committed when the method actually runs.
The reverse also holds. The future method cannot see uncommitted changes that the caller has not yet saved, and it never runs while the caller still holds record locks from its own DML, because the caller must commit first.
Rolled-back transactions discard queued calls
A future call is part of the transaction that made it. If that transaction fails, the queued request goes away. Consider this method.
public class FutureRollbackDemo {
@future
public static void neverRuns() {
System.debug('This line should not appear.');
}
public static void run() {
neverRuns();
insert new Account(); // Name is required, so this throws a DmlException
}
}Run FutureRollbackDemo.run();. The insert fails and the exception is uncaught, so the whole transaction rolls back. No future log appears.
If you catch the exception and let the transaction finish, the future call is kept and does run. Catching an exception is therefore a decision about the future call as well as about your own data. If the future method does follow-up work for a record that failed to save, catch carefully, and call the future method only after the DML has succeeded.
Ordering between calls
Suppose a trigger fires twice for the same record, for example once on insert and again after a workflow update. Each firing might queue a future call for that record. You cannot assume the call from the first firing finishes before the second one starts.
Two problems follow from this.
- Lost updates. Two concurrent future executions read the same record, each changes a different field, and the second save overwrites the first change if you write fields you did not mean to change. Update only the fields you own, and query fresh data inside the method.
- Row locks. Two executions that update the same record at the same time can fail with
UNABLE_TO_LOCK_ROW. The same happens if a future execution collides with a user editing the record. Keep the work short, and consider whether a retry design is needed.
If a task needs a strict sequence, a future method is the wrong tool. A Queueable job can start another Queueable job when it finishes, which gives you an ordering that future methods cannot. The final chapter compares them in detail.
Limits that affect timing
Two limits shape how many calls you can make and how fast they drain.
- Per transaction: at most 50 future calls in one Apex invocation. A loop that calls a future method once per record fails when the 51st call runs, with a limit exception that rolls back the whole transaction, including the first 50 queued calls.
- Per 24 hours: the org-wide cap on asynchronous Apex executions is the larger of 250,000 or 200 times the number of user licenses. Future methods count against this shared total, along with Queueable, Batch, and scheduled Apex.
You can check the first limit at run time.
public class FutureGuard {
public static void queueIfRoom(Set<Id> ids) {
if (Limits.getFutureCalls() < Limits.getLimitFutureCalls()) {
AccountService.updateAccountRatings(ids);
} else {
System.debug(LoggingLevel.WARN, 'Future call limit reached; skipping.');
}
}
}Limits.getFutureCalls() returns how many future calls the current transaction has made, and Limits.getLimitFutureCalls() returns the cap. Checking is useful in shared code that other developers call from loops. The better fix is still to pass one set of IDs per transaction instead of one call per record.
When a lot of future requests arrive together, they wait in the shared queue and drain as capacity allows. A large backlog from a data load can delay unrelated future calls from other users. Treat this as another reason not to depend on prompt execution.
The running context
A few details about the environment in which the future method runs:
- It runs as the same user whose transaction queued it, so sharing and permissions behave as they would for that user, subject to your class's
with sharingorwithout sharingdeclaration. System.isFuture()returnstrueinside the method. You can use it to stop code from queueing another future call, which the platform does not allow from a future method.- The method gets the asynchronous governor limits. For example, SOQL queries allow 200 instead of 100, and heap allows 12 MB instead of 6 MB.
- Its debug output goes to its own log, so a test with logging switched on for one user shows several separate entries for one user action.
How tests change the timing
In a test, future methods do not wait in the real queue. Calls made between Test.startTest() and Test.stopTest() are collected, and Test.stopTest() runs them synchronously before it returns. After stopTest() the results are committed and you can query and assert on them. The testing chapter covers this in full. For this chapter, remember that a test shows the final outcome but hides the delay, the possible reordering, and the concurrency you will see in production.
Exercise
A trigger on Account calls notify(a.Name) in a future method for each new record, passing the name as a String. In the same transaction, a workflow rule then renames the record. What name does the future method receive, and what would it see if you passed the ID and queried the name instead?
Show answer
With the String parameter, the method receives the name as it was when notify was called, because parameters are copied at call time. If you pass the ID and re-query, the method sees the name as committed when it actually runs, which includes the workflow rename.
Exercise
A method calls a future method, then runs insert on a record that fails validation. The insert exception is not caught. Does the future method run? Would your answer change if you wrapped the insert in a try/catch that swallows the exception?
Show answer
With the uncaught exception, the transaction rolls back and the queued future call is discarded, so the method does not run. If the catch block swallows the exception, the transaction commits and the future method does run, even though the insert failed.
Exercise
Two future calls, stepOne(id) and stepTwo(id), are made in that order and stepTwo depends on stepOne's result. What is the problem, and what would you use instead?
Show answer
Future methods have no guaranteed order and can run at the same time, so stepTwo may run before stepOne finishes. Use Queueable Apex and start the second job from the first job's execute method, which enforces the sequence.