Sub topic 9
Using Future Methods Safely from Triggers
This chapter assumes you can write an Apex trigger, know what Trigger.new contains, and have seen a basic @future method that takes a Set<Id>. It covers how to call a future method from a trigger without hitting limits or unexpected errors.
Why triggers need extra care
A trigger is the most common place to start asynchronous work. For example, when an account is created you may want to call an external system, or update related data without making the user wait.
A trigger is also where bulk behavior is hardest to predict. The same trigger code runs for one record saved from the UI and for thousands of records loaded through the API or an Apex batch. A future call that is fine for one record can fail for the thousandth.
Three rules cover most problems:
- Call the future method once per trigger invocation, with a collection of IDs.
- Check the calling context before you call it.
- Make sure the future method cannot cause the trigger to fire again in a loop.
One call per invocation, not per record
The most common mistake is calling the future method inside the loop over Trigger.new:
trigger AccountTriggerBad on Account (after insert) {
for (Account a : Trigger.new) {
// One future call per record: fails on the 51st record.
AccountService.updateAccountRatings(new Set<Id>{ a.Id });
}
}A single Apex invocation can make at most 50 future calls. The 51st call throws System.LimitException: Too many future calls: 51. Because the exception happens in the trigger, the whole original transaction rolls back, including the records the user saved.
The fix is to collect IDs first and make one call after the loop:
trigger AccountTrigger on Account (after insert) {
Set<Id> ids = new Set<Id>();
for (Account a : Trigger.new) {
ids.add(a.Id);
}
AccountService.updateAccountRatings(ids);
}This trigger uses after insert on purpose. Record IDs do not exist yet in a before insert trigger, so there is nothing to pass to the future method. Use an after event whenever you need IDs.
Trigger chunks and the 50-call limit
Even the corrected trigger can reach the limit. Salesforce runs a trigger on records in chunks of up to 200. If one transaction saves more than 200 records, the trigger runs once per chunk. A single Apex statement such as insert accounts; with 10,000 records runs the trigger 50 times in one transaction. That makes 50 future calls, which is exactly the limit. Any other code in the same transaction that calls a future method will push it over.
Data loaded through the API behaves differently. Each batch of 200 records is its own transaction, so each has its own count of 50.
| Records saved in one Apex statement | Trigger invocations | Future calls (one per invocation) |
|---|---|---|
| 1 to 200 | 1 | 1 |
| 201 to 400 | 2 | 2 |
| 10,000 | 50 | 50 (at the limit) |
If your trigger could see bulk loads of this size, a future method is the wrong tool. Queueable Apex is the usual replacement, and a later chapter covers it.
You can also check the remaining capacity at run time. Limits.getFutureCalls() returns the number of future calls made so far in the transaction. Limits.getLimitFutureCalls() returns the maximum.
Check the calling context
A future method cannot be called from another future method or from a batch Apex method. Doing so throws a System.AsyncException. A trigger can run in either of those contexts. For example, a future method that updates accounts will fire the account triggers, and so will a batch job that updates accounts.
System.isFuture() and System.isBatch() tell you where the code is running. A clean pattern is to keep the real logic in a normal method and make the future method a thin wrapper:
public class AccountService {
@future
public static void updateAccountRatings(Set<Id> accountIds) {
applyRatings(accountIds);
}
public static void applyRatings(Set<Id> accountIds) {
List<Account> accounts = [SELECT Id, Rating FROM Account WHERE Id IN :accountIds];
for (Account a : accounts) {
a.Rating = 'Hot';
}
update accounts;
}
}A small handler class then decides which path to take. Keeping this decision out of the trigger body makes it easy to test:
public class AccountTriggerHandler {
public static void afterInsert(List<Account> newAccounts) {
Set<Id> ids = new Map<Id, Account>(newAccounts).keySet();
if (ids.isEmpty()) {
return;
}
if (System.isFuture() || System.isBatch()) {
// Already asynchronous. Run the work directly.
AccountService.applyRatings(ids);
} else if (Limits.getFutureCalls() < Limits.getLimitFutureCalls()) {
AccountService.updateAccountRatings(ids);
} else {
System.debug(LoggingLevel.WARN,
'Future call limit reached. Skipped ratings for ' + ids.size() + ' accounts.');
}
}
}trigger AccountTrigger on Account (after insert) {
AccountTriggerHandler.afterInsert(Trigger.new);
}The new Map<Id, Account>(newAccounts).keySet() line is a short way to turn a list of records into a set of IDs.
The else branch here only logs a warning, which means the work is silently skipped. In production code you would usually do something more useful, such as flagging the records so a scheduled job can pick them up later.
Running the work directly inside a batch or future context has a cost. It counts against that context's own limits, so a large batch could use up its SOQL or DML allowance. Measure this if the work is heavy.
Keep the future method from re-triggering itself
A future method that updates records fires the triggers for those records. If the same trigger calls the future method again, you get a loop of asynchronous jobs that burns your daily async limit.
The examples in this chapter avoid this because the trigger runs only on after insert, while the future method performs an update. If your trigger also listens to after update, add a condition so the future method is called only when something relevant changed. For example, compare Trigger.oldMap with Trigger.newMap and queue only the records whose field changed. The check System.isFuture() also stops a future method from calling itself through a trigger, but it does not stop a loop that goes through a Queueable job.
What happens at commit
Calling a future method does not run it. It places a request in a queue. That request is saved only if the original transaction commits. If the transaction rolls back, for example because of a validation rule or an unhandled exception later in the save, the future call is discarded.
This has two practical effects:
- The future method never sees data from a transaction that failed, so you do not get side effects for records that were never saved.
- By the time the future method runs, the records may have changed or been deleted. Re-query them by ID, and handle the case where the query returns fewer records than you passed in.
The order of future jobs is not guaranteed. Two calls made one after the other may run in either order, so do not write logic that depends on one finishing before the next.
Testing a trigger that calls a future method
Test the whole path, from the DML statement to the final data. To make the future method run, the DML must happen inside Test.startTest() and Test.stopTest(). Calls queued before startTest() are not guaranteed to finish at stopTest().
The test below inserts 201 accounts. That forces two trigger invocations and so exercises two future calls:
@isTest
private class AccountTriggerTest {
@isTest
static void bulkInsertSetsRatings() {
List<Account> accounts = new List<Account>();
for (Integer i = 0; i < 201; i++) {
accounts.add(new Account(Name = 'Bulk Account ' + i));
}
Test.startTest();
insert accounts;
Test.stopTest();
Integer hotCount = [SELECT COUNT() FROM Account WHERE Rating = 'Hot'];
System.assertEquals(201, hotCount, 'Every inserted account should be rated Hot');
}
}Each future method runs synchronously when Test.stopTest() is called, so the assertions after it see the finished result. A test like this is worth keeping, because it fails if someone later moves the future call inside the loop. The test would then hit the limit once the number of records passes 50.
If your org has existing automation on Account, such as flows or other triggers, it may change Rating too. Filter the query to the records created in your test if that matters.
Common errors
| Error | Cause | Fix |
|---|---|---|
| `Too many future calls: 51` | Future call inside a loop, or more than 50 trigger chunks in one transaction | Collect IDs and call once. Use Queueable for very large loads. |
| `AsyncException: Future method cannot be called from a future or batch method` | Trigger fired from a future or batch context | Check `System.isFuture()` and `System.isBatch()` first. |
| Future method runs but finds no data | Records deleted or rolled back before it ran | Re-query by ID and handle an empty result. |
| Assertions fail in a test | DML ran before `startTest()`, or the test does not call `stopTest()` | Put the DML between `startTest()` and `stopTest()`. |
| Async limit used up quickly | Trigger re-fires itself through the future method | Add change checks and run only on the events you need. |
Exercise
A trigger on Contact (after update) loops over Trigger.new and calls a future method with a single ID for each contact whose Email changed. A user mass-edits 120 contacts in a list view, and the save fails with "Too many future calls: 51". Rewrite the trigger body so it no longer fails, and name one extra check you should add before calling the future method.
Show answer
Collect the IDs of the changed contacts in a Set<Id> inside the loop, comparing Trigger.oldMap.get(c.Id).Email with c.Email. After the loop, if the set is not empty, call the future method once with the whole set. The extra check is the calling context: skip the call, or run the logic directly, when System.isFuture() or System.isBatch() is true. You can also compare Limits.getFutureCalls() with Limits.getLimitFutureCalls() to avoid the limit exception when the transaction has already used many calls.