Skip to content

AfterUpdate.RecursionGuard ​

Cap how many times a Writer or Dispatcher acts on the same record in one transaction.

Signature

apex
public interface RecursionGuard {
    Integer maxRunsPerRecordOnAfterUpdate();
}
  • maxRunsPerRecordOnAfterUpdate(): called once per chunk, when the handler list is built. Returns how many times one record may qualify for this handler in the transaction.

Example

apex
public with sharing class ContactWriter implements AfterUpdate.Writer, AfterUpdate.RecursionGuard {
    public Integer maxRunsPerRecordOnAfterUpdate() {
        return 1;
    }

    public Boolean writeOnAfterUpdateWhen(TriggerTypes.UpdateRecord record) {
        return record.isChanged(Contact.AccountId);
    }

    public void writeOnAfterUpdate(TriggerTypes.UpdateRecord record, TriggerTypes.UnitOfWork unitOfWork) {
        unitOfWork.toInsert(new Task(WhatId = ((Contact) record.getNewSObject()).AccountId, Subject = 'Review contact'));
    }
}
cls
public with sharing class OpportunityAccountTypeWriter implements AfterUpdate.Writer, AfterUpdate.ParentQuery, AfterUpdate.RecursionGuard {
    public Map<SObjectField, TriggerTypes.ParentFields> queryParentsOnAfterUpdate() {
        return new Map<SObjectField, TriggerTypes.ParentFields>{ Opportunity.AccountId => TriggerTypes.ParentFields.with(Account.Type) };
    }

    public Integer maxRunsPerRecordOnAfterUpdate() {
        return 1;
    }

    public Boolean writeOnAfterUpdateWhen(TriggerTypes.UpdateRecord record) {
        if (!record.isChangedTo(Opportunity.StageName, 'Closed Won')) {
            return false;
        }

        Account account = (Account) record.getNewParent(Opportunity.AccountId);

        return account != null && account.Type != 'Customer - Direct';
    }

    public void writeOnAfterUpdate(TriggerTypes.UpdateRecord record, TriggerTypes.UnitOfWork unitOfWork) {
        Opportunity newOpportunity = (Opportunity) record.getNewSObject();

        unitOfWork.toUpdate(new Account(Id = newOpportunity.AccountId, Type = 'Customer - Direct'));
    }
}
cls
public with sharing class AccountAddressCascadeWriter implements AfterUpdate.Writer, AfterUpdate.RelatedQuery, AfterUpdate.ContinueOnError, AfterUpdate.RecursionGuard {
    public Integer maxRunsPerRecordOnAfterUpdate() {
        return 1;
    }

    public Map<String, AfterUpdate.RecordsProvider> queryRelatedOnAfterUpdate() {
        return new Map<String, AfterUpdate.RecordsProvider>{ 'contacts' => new AccountContactsProvider() };
    }

    public Boolean writeOnAfterUpdateWhen(TriggerTypes.UpdateRecord record) {
        return record.isAnyChanged(Account.BillingStreet, Account.BillingCity, Account.BillingState, Account.BillingPostalCode, Account.BillingCountry);
    }

    public void writeOnAfterUpdate(TriggerTypes.UpdateRecord record, TriggerTypes.UnitOfWork unitOfWork) {
        Account newAccount = (Account) record.getNewSObject();
        Account oldAccount = (Account) record.getOldSObject();

        for (SObject row : record.getRelated('contacts').getAllWhereKeyEquals(record.getId())) {
            Contact contact = (Contact) row;

            if (!this.mailingFollowedAccount(contact, oldAccount)) {
                continue;
            }

            unitOfWork.toUpdate(
                new Contact(
                    Id = contact.Id,
                    MailingStreet = newAccount.BillingStreet,
                    MailingCity = newAccount.BillingCity,
                    MailingState = newAccount.BillingState,
                    MailingPostalCode = newAccount.BillingPostalCode,
                    MailingCountry = newAccount.BillingCountry
                )
            );
        }
    }

    private Boolean mailingFollowedAccount(Contact contact, Account oldAccount) {
        if (String.isBlank(contact.MailingStreet) && String.isBlank(contact.MailingCity)) {
            return true;
        }

        return contact.MailingStreet == oldAccount.BillingStreet &&
            contact.MailingCity == oldAccount.BillingCity &&
            contact.MailingPostalCode == oldAccount.BillingPostalCode &&
            contact.MailingCountry == oldAccount.BillingCountry;
    }

    private with sharing class AccountContactsProvider implements AfterUpdate.RecordsProvider {
        public List<SObject> query(TriggerTypes.UpdateRecords records) {
            return [
                SELECT Id, AccountId, MailingStreet, MailingCity, MailingState, MailingPostalCode, MailingCountry
                FROM Contact
                WHERE AccountId IN :records.getIds()
            ];
        }

        public String keyOf(SObject row) {
            return ((Contact) row).AccountId;
        }
    }
}

Rules ​

  • Without it, the depth is 3 and nothing is skipped. When a record comes back after 3 runs, each run logs an error and the handler keeps acting. A loop that never ends fails the save at the platform's limit of 16 nested triggers.
  • It counts passes per class name and context, not nesting depth. The count goes up each time the predicate returns true and never resets during the transaction. Separate updates of the same record count too. Two instances of one class share one count, and BeforeUpdate keeps its own.
  • Skipped and logged. A record at the cap is skipped before its predicate, and the run logs an error. The Finalizer does not get the record.
  • 0 or less stops the handler. Every record is skipped, and every run logs an error. null means no cap and no error.

TIP

Prefer a change gate. isChanged or isChangedTo in the predicate stops re-entry without counting.