Sub topic 11
Where Future Methods Cannot Be Called
This chapter assumes you can declare and call a basic @future method, as covered earlier in this tutorial. It also assumes you know how Apex triggers fire and what per-transaction governor limits are. Here you will learn the contexts where a future call fails, the errors you see, and patterns that avoid the failures.
The core rule
A future method is a request to run code later, in its own transaction. Salesforce allows that request from most places, but not from code that is already running as a future method or as Batch Apex. The platform does this to stop uncontrolled fan-out. If future methods could call future methods, one call could spawn an unbounded tree of background work.
The runtime error looks like this:
System.AsyncException: Future method cannot be called from a future or batch methodThe error is thrown at the moment you call the method. The compiler cannot catch it, because whether a call is legal depends on the runtime context. A call that works in one code path can fail in another. Tests often miss this, because they usually exercise only one entry point.
Where you can and cannot call
| Calling context | Can it call a future method? | Notes |
|---|---|---|
| Anonymous Apex, REST or SOAP Apex services | Yes | Counts toward the 50 future calls per transaction |
| Trigger fired by a user or API action | Yes | Use one call per trigger invocation |
| Trigger fired by DML inside a future method | No | The trigger runs in future context |
| Trigger fired by DML inside Batch Apex | No | The trigger runs in batch context |
| Future method | No | Throws `AsyncException` |
| Batch Apex methods (`start`, `execute`, `finish`) | No | `System.isBatch()` returns true |
| Queueable `execute` | Yes | Allowed, and often used to hand off work |
| Schedulable `execute` | Yes | Runs in its own scheduled transaction |
| Visualforce getter, setter, or constructor | No | Reserved for side-effect-free code |
The Visualforce restriction exists because the platform can call getters, setters, and constructors many times and in any order during a page request. A future call placed there could be queued repeatedly. Call future methods from action methods instead.
The hidden path: triggers
The most common way to hit this error is indirectly. Take the AccountTrigger from earlier in the tutorial, which calls AccountService.updateAccountRatings after insert. Now suppose a future method inserts Accounts:
public class AccountImporter {
@future
public static void importAccounts(Set<String> names) {
List<Account> toInsert = new List<Account>();
for (String n : names) {
toInsert.add(new Account(Name = n));
}
insert toInsert; // fires AccountTrigger inside future context
}
}The insert fires the trigger. The trigger calls updateAccountRatings, which is a future method. The call chain is now future, then trigger, then future, and the platform throws the AsyncException. The same happens if a Batch Apex execute method inserts Accounts.
Nothing in AccountImporter mentions a second future call, so a code review of that class alone would not show the problem. You have to know every trigger on every object you touch. Any trigger that calls a future method is a hazard for every future method and batch job that performs DML on that object.
Guard the call site
Check the context before calling:
trigger AccountTrigger on Account (after insert) {
Set<Id> ids = new Set<Id>();
for (Account a : Trigger.new) {
ids.add(a.Id);
}
if (!System.isFuture() && !System.isBatch()) {
AccountService.updateAccountRatings(ids);
}
}System.isFuture() returns true when the current code runs inside a future method. System.isBatch() returns true inside Batch Apex. The trigger no longer throws, but the guard has a cost: when the condition is false, the rating update does not happen at all. Records created by AccountImporter never get rated.
Falling back to Queueable
Queueable Apex is not subject to the future restriction in the same way. A future method or a batch job can enqueue a Queueable job, although only one System.enqueueJob call is allowed from those contexts. A common pattern is a single dispatcher method that picks the right mechanism for the current context.
First, a Queueable that does the same work as the future method:
public class RatingJob implements Queueable {
private Set<Id> accountIds;
public RatingJob(Set<Id> accountIds) {
this.accountIds = accountIds;
}
public void execute(QueueableContext ctx) {
List<Account> accounts = [SELECT Id, Rating FROM Account WHERE Id IN :accountIds];
for (Account a : accounts) {
a.Rating = 'Hot';
}
update accounts;
}
}Then the dispatcher:
public class RatingDispatcher {
public static void rate(Set<Id> accountIds) {
if (accountIds == null || accountIds.isEmpty()) {
return;
}
if (System.isFuture() || System.isBatch()) {
if (Limits.getQueueableJobs() < Limits.getLimitQueueableJobs()) {
System.enqueueJob(new RatingJob(accountIds));
} else {
System.debug(LoggingLevel.ERROR, 'No queueable capacity left for rating job');
}
} else if (Limits.getFutureCalls() < Limits.getLimitFutureCalls()) {
AccountService.updateAccountRatings(accountIds);
} else {
System.enqueueJob(new RatingJob(accountIds));
}
}
}The trigger now calls RatingDispatcher.rate(ids) with no guard of its own. The dispatcher covers three cases:
- In future or batch context, it enqueues the Queueable, so the work is deferred but not lost.
- In a normal context with future capacity left, it uses the future method.
- If the transaction has already used its 50 future calls, it falls back to Queueable instead of throwing a limit exception.
The limit checks use Limits.getFutureCalls() and Limits.getLimitFutureCalls(), which return the calls made so far and the maximum allowed.
The cost is duplicated logic: the future method and the Queueable do the same job, so a change to one must be copied to the other. A cleaner design puts the shared logic in a plain service method and has both entry points call it. If you control the whole code base, the simpler option is to use Queueable everywhere and drop the future method.
Other places the restriction shows up
Limits on the number of calls
A single transaction can make at most 50 future calls. This is a separate limit from the rule above, but it fails similarly. Calling a future method inside a loop over records is a classic cause. It can exhaust the limit with one request that carries 51 records. Collect the IDs first and make one call, as the trigger above does.
There is also a daily cap on asynchronous executions across the org. If one transaction generates many future calls, it also consumes that shared allowance.
No return values and no chaining by result
A future method returns void, so a caller cannot wait for its result or pass its output to a second future method. You cannot build a sequence like "run A, then run B with A's result" from future methods. Each future call is independent, and Salesforce does not guarantee execution order. Calls made in one order can run in another. If step B depends on step A, put both steps in one future method, or use Queueable chaining. A Queueable job can enqueue the next job from inside its execute method.
Parameter restrictions apply at the call site
When you call a future method from a context that is allowed, the arguments must still be primitives, arrays of primitives, or collections of primitives. Passing an sObject or a custom class instance fails at compile time. This is why dispatchers pass Set<Id> and not List<Account>.
Detecting the context yourself
Apex gives you several context checks. Use them to write code that adapts instead of failing.
| Check | Returns true when |
|---|---|
| `System.isFuture()` | Running inside a future method |
| `System.isBatch()` | Running inside Batch Apex |
| `System.isQueueable()` | Running inside a Queueable job |
| `System.isScheduled()` | Running inside a scheduled job |
These checks tell you where you are, not where the original request began. A trigger that fires from a Queueable job sees System.isQueueable() as true, and a future call from there is allowed. A trigger that fires from a future method sees System.isFuture() as true, and a future call is blocked.
Testing the restriction
Test the blocked path as well as the allowed path. A test that inserts an Account directly covers only the allowed path. To cover the future-context path, call the future method that performs the DML, and let Test.stopTest() run it.
@isTest
private class AccountImporterTest {
@isTest
static void importDoesNotFailWhenTriggerRunsInFutureContext() {
Test.startTest();
AccountImporter.importAccounts(new Set<String>{ 'Imported One', 'Imported Two' });
Test.stopTest();
Integer count = [SELECT COUNT() FROM Account WHERE Name LIKE 'Imported%'];
System.assertEquals(2, count);
}
}If the trigger still called the future method without a guard or a dispatcher, this test would fail with the AsyncException when Test.stopTest() runs the queued future method. That is the signal you want from a test.
A checklist for avoiding the error
- List every trigger on the objects that your future methods and batch classes write to.
- For each trigger, find any future method calls, including calls made through helper classes.
- Route those calls through a dispatcher, or guard them with
System.isFuture()andSystem.isBatch(). - If skipping the work is not acceptable, give the guarded path a Queueable fallback.
- Add a test that runs the future or batch entry point and performs the DML.
Exercise
A batch class's execute method updates Accounts. An Account trigger calls a future method on update, without any guard. What happens when the batch runs, and what are two ways to fix it?
Show answer
The update fires the trigger inside batch context, and the trigger's future call throws System.AsyncException: Future method cannot be called from a future or batch method. One fix is to guard the call with !System.isFuture() && !System.isBatch(), which skips the future work in those contexts. A second fix is to route the call through a dispatcher that enqueues a Queueable job when System.isBatch() or System.isFuture() is true, so the work still happens.
Exercise
A Visualforce controller calls a future method from its constructor to prefetch data. Why is this not allowed, and where should the call go instead?
Show answer
Constructors, getters, and setters can run many times and in an unpredictable order during a page request, so a future call there could be queued repeatedly. Move the call to an action method that runs once in response to a user action.