Sub topic 9
Using future methods safely from triggers
This chapter assumes you can write an Apex trigger, you know the @future rules from earlier chapters (static, void, primitive parameters), and you know that governor limits apply per transaction.
Why triggers need extra care
A trigger runs once per batch of up to 200 records, and one transaction can run many such batches. A future method call inside a trigger therefore multiplies quickly. Three problems come up most often:
- Calling the future method once per record, which exhausts the per-transaction limit.
- Calling it from a context where future methods are not allowed.
- Passing data that is stale by the time the future method runs.
Collect IDs, then call once
Never call a future method inside the loop over Trigger.new. Gather the IDs, then make a single 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);
}
if (!System.isFuture() && !System.isBatch()) {
AccountService.updateAccountRatings(ids);
}
}This sends one future call per trigger invocation, however many records are in the chunk. Use an after trigger so the records already have IDs. The future method then re-queries the records, so it works with current data and not a snapshot taken when the trigger ran.
The limits that matter
| Limit | Value |
|---|---|
| Future calls per Apex invocation | 50 |
| Future calls per 24 hours | The greater of 250,000 or 200 times the number of user licenses (org-wide) |
The per-transaction limit of 50 is easy to reach with bulk loads. Suppose a data load inserts 10,000 accounts. Salesforce splits the load into 50 chunks of 200 records, and each chunk fires the trigger. That is 50 future calls. A load of 10,001 records would need 51 and fail.
If the load runs as one transaction, you can check the remaining capacity before you call:
public class AccountTriggerHandler {
public static void queueRatingUpdate(Set<Id> accountIds) {
if (accountIds.isEmpty()) {
return;
}
if (System.isFuture() || System.isBatch()) {
return;
}
if (Limits.getFutureCalls() >= Limits.getLimitFutureCalls()) {
System.debug(LoggingLevel.WARN, 'Future call limit reached; skipping.');
return;
}
AccountService.updateAccountRatings(accountIds);
}
}Skipping the work silently is rarely acceptable in production. If you can hit this limit, the work probably belongs in Queueable or Batch Apex, covered in a later chapter.
Guarding the calling context
A future method cannot be called from another future method or from a Batch Apex method. If a trigger fires because a future method or a batch job changed records, an unguarded call throws an exception. The two checks handle this:
System.isFuture()istruewhen the current code is running inside a future method.System.isBatch()istruewhen the current code is running inside a batch job.
The decision flow in the trigger looks like this:
Avoid loops
If the future method updates the same object that fired the trigger, the update can fire the trigger again. In the example above the trigger only runs on after insert, so the update does not re-enter it. If you extend the trigger to after update, the future method's own update would fire it again. The System.isFuture() check stops the chain there.
Timing
The future method does not run until the trigger's transaction commits. If the transaction rolls back, for example because a later validation rule fails, the queued future call is discarded. Do not assume the future work has happened by the time the trigger finishes. Code that needs the result immediately must run synchronously.
Exercise
A data load inserts 12,000 Account records in a single transaction, and your after insert trigger calls a future method once per trigger invocation. Does the load succeed? Why or why not?
Show answer
No. The load is split into 60 chunks of 200 records, so the trigger fires 60 times and makes 60 future calls. The limit is 50 future calls per Apex invocation, so the 51st call throws a limit exception. To avoid this, check Limits.getFutureCalls() before calling, or move the work to Queueable or Batch Apex.