Trigger Lib

Trigger lib

This post was NOT written by AI.
I only used AI to help refine my grammar because I am not a native English speaker.


Introduction

A major part of most Salesforce projects is automation. Automation in Salesforce can be achieved via Flows, Apex Triggers and periodically running jobs. I’m not the biggest fan of Salesforce Flows, which are extremely impractical in the AI era because they block AI’s potential and have a lot of limitations. I’ve described all the problems with Flows in my Salesforce Flow Considerations post. Since Flows have many problems, Apex Triggers are, in my opinion, the only good choice. However, Apex Triggers are not perfect and come with the following problems:

  • Apex Triggers can become messy and hard to understand
  • Messy Apex Triggers can cause System.LimitException: Too many SOQL queries: 101
  • Messy Apex Triggers can cause System.LimitException: Too many DML statements: 151
  • Consultants and Admins don’t know how to code
  • AI Agents build logic in triggers without thinking about the system as a whole, which can cause many bugs and a lack of transaction control
  • It’s not easy to add new automation to the existing structure
  • There is no out-of-the-box functionality to disable triggers
  • Multiple triggers on one object run in no fixed order
  • Recursion
  • Trigger logic can only be tested with DML
  • There is no out-of-the-box error-handling strategy

This is why developers usually use Apex Trigger Frameworks, which address at least part of these issues.

Trigger Frameworks Issue

In the AI era, developers use AI to produce code without thinking about the system as a whole. You’re supposed to be more productive and just deliver, right? But Salesforce governor limits are shared by everything that runs in the same transaction. You can write or generate the best code in the world, but if another team’s code in that transaction runs a query in a loop, your logic breaks too.

Apex Trigger Frameworks should help here, and there are plenty of them on the "market". I’ve used many of them on my projects, and they worked fine. However, I haven’t found one that gives you the tools to optimize the transaction and avoid Too many SOQL queries, Too many DML statements or long-running automations.

This is why I created Trigger Lib.

Trigger Lib

Trigger Lib is part of Apex Fluently, a collection of modern open-source Salesforce libraries.

Unlike other frameworks, it gives you a strict way to write Apex handlers: one small, focused class per concern, with one role in a trigger context. It also has built-in SOQL query bulkification and uses a Unit of Work to reduce the number of DML statements.

The Trigger Lib follows the Framework-Driven Development principles:

  • Idiot-proof (AI-proof)
  • Optimized for code and limits
  • Quality by design

Let me show you how it works and why it’s worth considering for your project.

Architecture

Trigger Lib is NOT a metadata-driven framework. I believe custom metadata only makes code more complicated, as I described in The Hidden Cost of Configurable Code. That doesn’t mean you can’t use custom metadata, though. You still can!

To run handlers registered in custom metadata records, call the runFromMetadata() method. Its name makes it explicit that the code runs based on metadata records.

trigger ContactTrigger on Contact(before insert, after insert, before update, after update, before delete, after delete, after undelete) {
    TriggerOrchestrator.runFromMetadata();
}

The other option, which needs no custom metadata records, is an orchestrator: a class that lists all the handlers.

trigger ContactTrigger on Contact(before insert, after insert, before update, after update, before delete, after delete, after undelete) {
    TriggerOrchestrator.run(new ContactTriggerOrchestrator());
}

With an orchestrator, custom metadata is optional. You only use it to switch handlers off, and the framework works without any metadata records.

Trigger Lib has three levels:

  1. Trigger – where you start the framework with run(orchestrator) or runFromMetadata().
  2. Orchestrator or custom metadata – where all handlers and their order are defined.
  3. Handler – a small, focused class. Instead of one generic handler type, each handler has one of four roles:
    • Populators exist only in before insert and before update, and set fields on the records being saved.
    • Validators exist in the before contexts and reject invalid records.
    • Writers exist in the after insert, after update and before delete. They are responsible for CRUD operations on related records.
    • Dispatchers exist in the after contexts and start async jobs, publish events or send emails.
// level 1
trigger ContactTrigger on Contact(before insert, after insert, before update, after update, before delete, after delete, after undelete) {
    TriggerOrchestrator.run(new ContactTriggerOrchestrator());
    // or
    TriggerOrchestrator.runFromMetadata();
}
// level 2
public with sharing class ContactTriggerOrchestrator implements TriggerOrchestrator.BeforeInsert {
    public List<BeforeInsert.Handler> beforeInsertHandlers() {
        return new List<BeforeInsert.Handler>{
            new ContactEmailNormalizationPopulator(),
            // ...
        };
    }
}

// or

// custom metadata records
// level 3
public with sharing class ContactEmailNormalizationPopulator implements BeforeInsert.Populator {
    public Boolean populateOnBeforeInsertWhen(TriggerTypes.InsertRecord record) {
        return record.isNotBlank(Contact.Email);
    }

    public void populateOnBeforeInsert(TriggerTypes.InsertRecord record) {
        Contact newContact = (Contact) record.getNewSObject();
        record.put(Contact.Email, newContact.Email.trim().toLowerCase());
    }
}

Besides the four roles, Trigger Lib has add-on interfaces for query bulkification, bypassing, recursion control, swallowing exceptions and more. Depending on the context, you can add:

  • ParentQuery
  • PriorParentQuery
  • RelatedQuery
  • OwnUnitOfWork
  • Bypassable
  • RecursionGuard
  • Finalizer
  • ContinueOnError

As I mentioned, Trigger Lib follows the Framework-Driven Development principles, which make code easy to work with for both developers and AI Agents.

First of all, the code is "Idiot-proof (AI-proof)". Each interface exists only in the contexts where it fits, and it forces you to implement exactly the methods it needs. Neither you nor the AI has to remember all the methods: just pick one role and as many add-ons as you need.

public class AfterInsert {
    // Roles - pick one

    public interface Writer extends Handler {
        Boolean writeOnAfterInsertWhen(TriggerTypes.InsertRecord record);
        void writeOnAfterInsert(TriggerTypes.InsertRecord record, TriggerTypes.UnitOfWork unitOfWork);
    }

    public interface Dispatcher extends Handler {
        Boolean dispatchOnAfterInsertWhen(TriggerTypes.InsertRecord record);
        void dispatchOnAfterInsert(TriggerTypes.InsertRecords records);
    }

    // Add-ons - pick as many as you need

    public interface ParentQuery {
        Map<SObjectField, TriggerTypes.ParentFields> queryParentsOnAfterInsert();
    }

    public interface RelatedQuery {
        Map<String, AfterInsert.RecordsProvider> queryRelatedOnAfterInsert();
    }

    public interface RecordsProvider {
        List<SObject> query(TriggerTypes.InsertRecords records);
        String keyOf(SObject row);
    }

    public interface OwnUnitOfWork {
        DML.Committable ownUnitOfWorkOnAfterInsert();
    }

    public interface Bypassable {
        Boolean bypassOnAfterInsertWhen();
    }

    public interface Finalizer {
        void finalizeOnAfterInsert(TriggerTypes.InsertRecords records);
    }

    public interface ContinueOnError {}

    // ...
}

This approach gives you "Quality by design". Instead of handler classes with hundreds or thousands of lines, you end up with small classes of up to 100 lines (I’ve never seen a longer one with Trigger Lib), each focused on one goal: populating, validating, writing or dispatching.

Finally, Trigger Lib is "Optimized for code and limits". It helps with the Salesforce limits that AI or inexperienced developers tend to hit. DML in before insert and before update throws a runtime error, and handlers never need SOQL or DML per record: ParentQuery and RelatedQuery load the data in bulk, and Writers register DML on a Unit of Work that commits it in bulk. I’ll cover this in more detail below. The goal is that neither you nor the AI has to worry about limits or the existing logic, because the framework handles them for you.

Populators

Populators are a kind of handler that only makes sense in the Before Insert and Before Update contexts. They are used to set field values and can be created per field or per group of fields.

public interface Populator extends BeforeInsert.Handler {
    Boolean populateOnBeforeInsertWhen(TriggerTypes.InsertRecord record);
    void populateOnBeforeInsert(TriggerTypes.InsertRecord record);
}

public interface Populator extends BeforeUpdate.Handler {
    Boolean populateOnBeforeUpdateWhen(TriggerTypes.UpdateRecord record);
    void populateOnBeforeUpdate(TriggerTypes.UpdateRecord record);
}

Each populator has two methods:

  1. populateOn{Context}When(record) – this method qualifies records; only records that meet the criteria are passed to the populateOn{Context} method. It’s the equivalent of an if statement inside a for loop. SOQL and DML statements are blocked here. Additional records can be queried only through add-on interfaces.
  2. populateOn{Context}(record) – this method contains the automation; this is where we set field values. The method is executed only for qualified records. SOQL and DML statements are blocked here. Additional records can be queried only through add-on interfaces.

Examples

public with sharing class ContactLeadSourcePopulator implements BeforeInsert.Populator {
    public Boolean populateOnBeforeInsertWhen(TriggerTypes.InsertRecord record) {
        return record.isBlank(Contact.LeadSource);
    }

    public void populateOnBeforeInsert(TriggerTypes.InsertRecord record) {
        record.put(Contact.LeadSource, 'Web');
    }
}
public with sharing class ContactDescriptionPopulator implements BeforeInsert.Populator, BeforeInsert.ParentQuery {
    public Map<SObjectField, TriggerTypes.ParentFields> queryParentsOnBeforeInsert() {
        return new Map<SObjectField, TriggerTypes.ParentFields>{ 
            Contact.AccountId => TriggerTypes.ParentFields.with(Account.Name) 
        };
    }

    public Boolean populateOnBeforeInsertWhen(TriggerTypes.InsertRecord record) {
        return record.getNewParent(Contact.AccountId) != null;
    }

    public void populateOnBeforeInsert(TriggerTypes.InsertRecord record) {
        Account parentAccount = (Account) record.getNewParent(Contact.AccountId);
        record.put(Contact.Description, parentAccount.Name);
    }
}

Validators

Validation rules don’t cover everything, so you need to use the .addError(...) method. Validators are handlers that can be used to validate records. They exist in the Before Insert, Before Update and Before Delete contexts; in Before Delete, they block the deletion.

public interface Validator extends BeforeInsert.Handler {
    Boolean addErrorOnBeforeInsertWhen(TriggerTypes.InsertRecord record);
    void addErrorOnBeforeInsert(TriggerTypes.RejectableInsertRecord record);
}

public interface Validator extends BeforeUpdate.Handler {
    Boolean addErrorOnBeforeUpdateWhen(TriggerTypes.UpdateRecord record);
    void addErrorOnBeforeUpdate(TriggerTypes.RejectableUpdateRecord record);
}

public interface Validator extends BeforeDelete.Handler {
    Boolean addErrorOnBeforeDeleteWhen(TriggerTypes.DeleteRecord record);
    void addErrorOnBeforeDelete(TriggerTypes.RejectableDeleteRecord record);
}

Similarly to populators, they consist of two methods:

  1. addErrorOn{Context}When(record) – this method qualifies records; only records that meet the criteria are passed to the addErrorOn{Context} method. It’s the equivalent of an if statement inside a for loop. SOQL and DML statements are blocked here. Additional records can be queried only through add-on interfaces.
  2. addErrorOn{Context}(record) – this method sets a validation error, either on a field or at the record level. The method is executed only for qualified records. SOQL and DML statements are blocked here. Additional records can be queried only through add-on interfaces.

If a validator qualifies a record but doesn’t add an error to it, the library throws an exception.

Examples

public with sharing class ContactEmailValidator implements BeforeInsert.Validator {
    public Boolean addErrorOnBeforeInsertWhen(TriggerTypes.InsertRecord record) {
        return record.isBlank(Contact.Email);
    }

    public void addErrorOnBeforeInsert(TriggerTypes.RejectableInsertRecord record) {
        record.addError(Contact.Email, 'Email is required.');
    }
}
public with sharing class OpportunityWinAmountValidator implements BeforeUpdate.Validator {
    public Boolean addErrorOnBeforeUpdateWhen(TriggerTypes.UpdateRecord record) {
        return record.isChangedTo(Opportunity.StageName, 'Closed Won') && (record.isNull(Opportunity.Amount) || record.lessThanOrEqualTo(Opportunity.Amount, 0));
    }

    public void addErrorOnBeforeUpdate(TriggerTypes.RejectableUpdateRecord record) {
        record.addError(Opportunity.Amount, 'Set a positive Amount before moving this Opportunity to Closed Won.');
    }
}

Writers

The best practice is to run DML statements in the after contexts. Writers exist in all four after contexts (After Insert, After Update, After Delete and After Undelete) and in Before Delete.

Each DML statement in Salesforce fires all automations on that object (flows and triggers), and each automation consumes SOQL query and DML statement limits. This is why we should reduce the number of DML statements in triggers. Trigger Lib provides a unit of work out of the box: each writer adds records to it, and by default the library commits them all at once at the end of each trigger chunk. Under the hood we use DML Lib, which builds a dependency graph, groups records into buckets and executes them in the correct order.

public interface Writer extends AfterInsert.Handler {
    Boolean writeOnAfterInsertWhen(TriggerTypes.InsertRecord record);
    void writeOnAfterInsert(TriggerTypes.InsertRecord record, TriggerTypes.UnitOfWork unitOfWork);
}

public interface Writer extends AfterUpdate.Handler {
    Boolean writeOnAfterUpdateWhen(TriggerTypes.UpdateRecord record);
    void writeOnAfterUpdate(TriggerTypes.UpdateRecord record, TriggerTypes.UnitOfWork unitOfWork);
}

Like populators and validators, writers consist of two methods:

  1. writeOn{Context}When(record) – this method qualifies records; only records that meet the criteria are passed to the writeOn{Context} method. It’s the equivalent of an if statement inside a for loop. SOQL statements are blocked here. Additional records can be queried only through add-on interfaces.
  2. writeOn{Context}(record, unitOfWork) – this method adds records to the unit of work instead of running DML statements. The method is executed only for qualified records. SOQL statements are blocked here. Additional records can be queried only through add-on interfaces.

Examples

public with sharing class ContactTaskWriter implements AfterInsert.Writer {
    public Boolean writeOnAfterInsertWhen(TriggerTypes.InsertRecord record) {
        return record.isNotNull(Contact.AccountId);
    }

    public void writeOnAfterInsert(TriggerTypes.InsertRecord record, TriggerTypes.UnitOfWork unitOfWork) {
        unitOfWork.toInsert(new Task(WhatId = ((Contact) record.getNewSObject()).AccountId, Subject = 'Review contact'));
    }
}

Dispatchers

A dispatcher is a kind of handler used to enqueue a Queueable or publish events. Dispatchers exist in all four after contexts. The dispatchOn{Context} method gets all qualified records at once, as TriggerTypes.InsertRecords, TriggerTypes.UpdateRecords, TriggerTypes.DeleteRecords or TriggerTypes.UndeleteRecords. These types have bulkification methods like getIds(), getIdsOf(field) and getValuesOf(field). If you need the individual records, call getRecords().

public interface Dispatcher extends AfterInsert.Handler {
    Boolean dispatchOnAfterInsertWhen(TriggerTypes.InsertRecord record);
    void dispatchOnAfterInsert(TriggerTypes.InsertRecords records);
}

public interface Dispatcher extends AfterUpdate.Handler {
    Boolean dispatchOnAfterUpdateWhen(TriggerTypes.UpdateRecord record);
    void dispatchOnAfterUpdate(TriggerTypes.UpdateRecords records);
}

Like the other roles, dispatchers consist of two methods:

  1. dispatchOn{Context}When(record) – this method qualifies records; only records that meet the criteria are passed to the dispatchOn{Context} method. It’s the equivalent of an if statement inside a for loop. SOQL statements are blocked here. Additional records can be queried only through add-on interfaces.
  2. dispatchOn{Context}(records) – this method gets all qualified records at once, behind an interface with bulkification methods, so you don’t need to loop over the records to retrieve values. It’s executed only when at least one record qualifies.

dispatchOn{Context} runs once per trigger chunk of up to 200 records, so when 1,000 records are updated, the example below enqueues 5 jobs. Because it doesn’t run per record, SOQL isn’t blocked there. DML isn’t blocked either, but it runs immediately, outside the unit of work, so leave record changes to writers.

Examples

public with sharing class ContactSyncDispatcher implements AfterUpdate.Dispatcher {
    public Boolean dispatchOnAfterUpdateWhen(TriggerTypes.UpdateRecord record) {
        return record.isChanged(Contact.Email);
    }

    public void dispatchOnAfterUpdate(TriggerTypes.UpdateRecords records) {
        System.enqueueJob(new ContactSyncJob(records.getIds()));
    }

    public class ContactSyncJob implements Queueable {
        private Set<Id> recordIds;

        public ContactSyncJob(Set<Id> recordIds) {
            this.recordIds = recordIds;
        }

        public void execute(QueueableContext context) {
            // logic here
        }
    }
}

To avoid Too many queueable jobs we highly recommend to use Async Lib in the dispatchers.

Bulkify SOQLs

I classified 919 SOQL queries that run from triggers in three projects I’ve worked on. Here are the results:

Group %
Parent Queries 31%
Config Queries (metadata, running user, profiles, territory setup) 23%
Siblings (other children of the same parent) 12%
Children 11%
Via an earlier query’s results 10%
Matched by value 9%
Trigger record re-queried 3%
Unrelated records 2%

The shares differ from project to project, but parent and config queries were the top two in every one of them.

My conclusion is that most queries (54%) are parent and config queries (custom metadata, the running user, profiles). Both kinds can be shared across handlers. Parent queries rarely need complex conditions: the triggering records already hold the parent Ids in their lookup fields.
Siblings and children are the next big group, but their queries usually have complex WHERE conditions and are hard to reuse between handlers.

The goal of Trigger Lib is that neither you nor your AI agent has to think about bulkification; the framework takes care of it. No more shared context classes or services with cached query results. Such approaches are painful to maintain: your change can affect other parts of the system, not to mention merge conflicts. Trigger Lib solves it differently: you’re responsible only for your own handler. There are three ways to query records.

1. Parent Queries

Say you have 20 handlers, and each one queries 2–3 different parents. You end up with 40–60 of the 100 queries available in a transaction, not to mention that any DML can start other automation that uses the same limit.

In Trigger Lib, you can’t run your own SOQL in the per-record methods (the …When predicate and the action); a query there fails the save. Instead, you and your AI agents declare what you need, and Trigger Lib runs the queries in bulk. For parents, all you need to do is implement the ParentQuery interface.

public interface ParentQuery {
    Map<SObjectField, TriggerTypes.ParentFields> queryParentsOn{Context}();
}
public with sharing class ContactPopulator implements BeforeInsert.Populator, BeforeInsert.ParentQuery {
    public Map<SObjectField, TriggerTypes.ParentFields> queryParentsOnBeforeInsert() {
        return new Map<SObjectField, TriggerTypes.ParentFields>{
            Contact.AccountId => TriggerTypes.ParentFields.with(Account.Name, Account.Industry)
            // other relationships here
        };
    }

    public Boolean populateOnBeforeInsertWhen(TriggerTypes.InsertRecord record) {
        return record.getNewParent(Contact.AccountId) != null;
    }

    public void populateOnBeforeInsert(TriggerTypes.InsertRecord record) {
        Account parentAccount = (Account) record.getNewParent(Contact.AccountId);
        // logic here
    }
}

Your handler declares the fields it needs as a map of lookup field (Contact.AccountId) to parent fields (TriggerTypes.ParentFields.with(Account.Name, Account.Industry)). You can declare more lookups. Every handler does the same. Trigger Lib collects the declarations from all handlers, merges the fields for each lookup and queries the parents. Later, you just call record.getNewParent(Contact.AccountId), and that’s it! You have the parent record. For the parent from before the save, in the update and delete contexts, use PriorParentQuery and record.getOldParent(...).

There are also a few optimizations that make it even more awesome:

  • Queries only when a parent is read. Trigger Lib doesn’t query until a handler calls getNewParent. You can call it in the …When predicate too. Apex evaluates conditions one by one and stops as soon as the result is known. In record.equals(Contact.LeadSource, 'Web') && ((Account) record.getNewParent(Contact.AccountId))?.Industry == 'Banking', the parent is read only for contacts from the web. If no contact in the chunk comes from the web, no query is made.
  • Every record at once. The first read loads the parents of every record in the chunk, qualified or not, so later handlers read them from memory. Each lookup costs one query per chunk, no matter how many handlers read it.
  • A single query in the after contexts. In after insert, after update and after undelete, Trigger Lib doesn’t query each parent object separately. It queries the trigger records once and reads the parents through relationship fields, e.g. SELECT Account.Name, Account.Owner.Name, Owner.Email FROM Contact WHERE Id IN :contactIds. No matter how many parents the handlers request, only a single query is made.

2. Config Queries

When the config doesn’t depend on the trigger records, load it into a static variable of the handler:

public with sharing class ContactPopulator implements BeforeInsert.Populator {
    private static MySetting__c setting = MySetting__c.getOrgDefaults();
    private static User runningUser = [SELECT Profile.Name, UserRole.Name FROM User WHERE Id = :UserInfo.getUserId()];

    public Boolean populateOnBeforeInsertWhen(TriggerTypes.InsertRecord record) {
        return //... ;
    }

    public void populateOnBeforeInsert(TriggerTypes.InsertRecord record) {
        // logic here
    }
}

A static variable lives for the whole transaction, so the query runs once, no matter how many times the trigger fires. Don’t put the query in the constructor: a new handler instance is created for every trigger run, so the query would run again for every chunk of 200 records.

Custom settings and custom metadata don’t even need a query: getOrgDefaults(), getInstance() and getAll() read them without SOQL. Even SOQL on custom metadata doesn’t count toward the 100-query limit, unless the query includes a long text area field. So the config queries that really use up the limit are the others, such as the running user, profiles or territory setup.

When the config depends on the trigger records, use the RelatedQuery interface, described below.

3. Siblings, Children, etc.

To query any other records, use the RelatedQuery interface. In queryRelatedOn{Context}, return a map of names to providers. A provider has two methods: query, which runs once for the whole chunk, and keyOf, which returns the key each row is stored under. To read the rows, call record.getRelated('openCases').getAllWhereKeyEquals(record.getId()).

The provider runs only when the handler first calls record.getRelated(...) with its name; otherwise, no query is made. Like parent queries, query gets every record in the chunk, qualified or not.

If several handlers need the same query, move the provider to its own class and reuse it. That saves you from writing the query twice, but not from running it twice: each handler runs its own providers. Otherwise, keep providers as inner classes, so everything stays in one place.

public with sharing class AccountFormerCustomerCaseWriter implements AfterUpdate.Writer, AfterUpdate.RelatedQuery {
    public Map<String, AfterUpdate.RecordsProvider> queryRelatedOnAfterUpdate() {
        return new Map<String, AfterUpdate.RecordsProvider>{ 'openCases' => new OpenCases() };
    }

    public Boolean writeOnAfterUpdateWhen(TriggerTypes.UpdateRecord record) {
        return record.isChangedTo(Account.Type, 'Former Customer');
    }

    public void writeOnAfterUpdate(TriggerTypes.UpdateRecord record, TriggerTypes.UnitOfWork unitOfWork) {
        for (SObject row : record.getRelated('openCases').getAllWhereKeyEquals(record.getId())) {
            unitOfWork.toUpdate(new Case(Id = row.Id, Status = 'Closed'));
        }
    }

    private with sharing class OpenCases implements AfterUpdate.RecordsProvider {
        public List<SObject> query(TriggerTypes.UpdateRecords records) {
            return [SELECT Id, AccountId FROM Case WHERE AccountId IN :records.getIds() AND IsClosed = FALSE];
        }

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

Bulkify DMLs

Many of you have probably heard of the "Unit of Work" concept. As Salesforce puts it on Trailhead:

The Unit of Work is a design pattern that reduces repetitive code when implementing transaction management and the coding overheads of adhering to DML bulkification through extensive use of maps and lists. ~ Salesforce

The problem is that I’ve never seen a unit of work used in a way that really helps with transaction management.
I’ve seen the UoW pattern applied in Apex controllers, but each call from LWC to Apex starts a new transaction, and we usually make only 2–3 of the 150 allowed DML statements there. A UoW in Apex controllers isn’t a must-have.
Service classes are another candidate, but like Apex controllers, they usually aren’t full of DML. A UoW can help there, but it’s not a game changer.
There is one place, however, where a unit of work is CRUCIAL: Apex triggers. A transaction allows 150 DML statements, and every DML can start other automation that uses the same limits: not only DML statements, but SOQL queries too. The fewer DML statements we run, the faster the processing and the safer we are with the limits.
Most trigger frameworks don’t give you a unit of work out of the box. Of course, you can add one, but then each handler registers records in its own unit of work and commits it on its own, so the bulkification is minimal. With 20 handlers, each committing its own unit of work, you end up with at least 20 DML statements.

Trigger Lib works differently: it passes a shared unit of work, built on DML Lib, to your Writers as a parameter. A DML statement in a Writer’s per-record methods (the …When predicate and the action) fails the save, so the work has to go through the unit of work.
Each Writer registers whatever it needs to insert, update, upsert or delete, as well as the platform events to publish. DML Lib builds a dependency graph under the hood, so parents are inserted before their children. When the last handler of the trigger run finishes, everything is committed at once, with one DML statement per operation and object type.

public interface Writer extends AfterInsert.Handler {
    Boolean writeOnAfterInsertWhen(TriggerTypes.InsertRecord record);
    void writeOnAfterInsert(TriggerTypes.InsertRecord record, TriggerTypes.UnitOfWork unitOfWork);
}

Example

public with sharing class ContactWriter implements AfterInsert.Writer {
    public Boolean writeOnAfterInsertWhen(TriggerTypes.InsertRecord record) {
        return record.isNotNull(Contact.AccountId);
    }

    public void writeOnAfterInsert(TriggerTypes.InsertRecord record, TriggerTypes.UnitOfWork unitOfWork) {
        unitOfWork.toInsert(new Task(WhatId = ((Contact) record.getNewSObject()).AccountId, Subject = 'Review contact'));
    }
}

Sometimes you need your own unit of work. For that, there’s another add-on interface called, surprise, surprise, OwnUnitOfWork. The shared unit runs in system mode without sharing, but in your own unit, you choose the mode, sharing and other settings. It’s committed automatically right after your Writer finishes, and it’s never merged with the shared unit, so no other handler’s records end up in it.

public interface OwnUnitOfWork {
    DML.Committable ownUnitOfWorkOnAfterInsert();
}

Example

public with sharing class ContactWriter implements AfterInsert.Writer, AfterInsert.OwnUnitOfWork {
    public DML.Committable ownUnitOfWorkOnAfterInsert() {
        return new DML().userMode().identifier('ContactWriter');
    }

    public Boolean writeOnAfterInsertWhen(TriggerTypes.InsertRecord record) {
        return record.isNotNull(Contact.AccountId);
    }

    public void writeOnAfterInsert(TriggerTypes.InsertRecord record, TriggerTypes.UnitOfWork unitOfWork) {
        unitOfWork.toInsert(new Task(WhatId = ((Contact) record.getNewSObject()).AccountId, Subject = 'Review contact'));
    }
}

The identifier names the unit, so tests can mock it with DML.mock('ContactWriter'), and DML.retrieveResultFor('ContactWriter') reads its results.

Continue On Error

You don’t need to wrap your handler logic in try-catch blocks: Trigger Lib does it for you and logs errors through your implementation of the Logger interface. By default, an exception in a handler fails the save and rolls back its changes, just like in a standard trigger. You can change that behavior with ContinueOnError, a marker interface. When a handler that implements it throws, the library logs the error and swallows it: the failing handler stops, but the other handlers and the save continue.

ContinueOnError has to be added explicitly, so it’s immediately clear to a developer or an AI agent that the save goes on even when this handler fails. Some errors are never swallowed: the library’s own exceptions (for example, SOQL or DML in a blocked method) and limit exceptions such as Too many SOQL queries: 101, which Apex can’t catch.

Example

public with sharing class ContactPopulator implements BeforeUpdate.Populator, BeforeUpdate.ContinueOnError {
    public Boolean populateOnBeforeUpdateWhen(TriggerTypes.UpdateRecord record) {
        return record.isChanged(Contact.Email);
    }

    public void populateOnBeforeUpdate(TriggerTypes.UpdateRecord record) {
        // logic that fails here
    }
}

Logger

So what happens when an error occurs?

To log errors, implement TriggerOrchestrator.Logger. The library finds your implementation on its own, so there’s nothing to register (only one implementation per org is allowed).

public interface Logger {
    void log(TriggerOrchestrator.Error error);
    void flush();
}

This way, you can connect Trigger Lib to whatever logging framework you use. The Logger has two methods, log and flush. The log method is called every time an error occurs, and flush is called once at the end of the outermost trigger run, even when the run fails.

In other frameworks, developers are responsible for saving logs, and they usually do it in every handler’s catch block. Trigger Lib collects the errors and saves them as rarely as possible (at the end of the chunk).

Keep in mind that DML in flush is rolled back when the save fails. Publish the logs as a Publish Immediately platform event instead, so they survive a failed save. The example below publishes TriggerError__e, a platform event of your own:

public with sharing class TriggerErrorLogger implements TriggerOrchestrator.Logger {
    private List<TriggerError__e> events = new List<TriggerError__e>();

    public void log(TriggerOrchestrator.Error error) {
        this.events.add(
            new TriggerError__e(
                Handler__c = error.getHandlerName(),
                Operation__c = String.valueOf(error.getOperation()),
                Object__c = String.valueOf(error.getSObjectType()),
                RecordIds__c = String.join(new List<Id>(error.getRecordIds()), ','),
                Message__c = error.getException().getMessage(),
                StackTrace__c = error.getException().getStackTraceString()
            )
        );
    }

    public void flush() {
        if (this.events.isEmpty()) {
            return;
        }

        EventBus.publish(this.events);
        this.events.clear();
    }
}

Bypass

Do you use feature flags and want to deploy code as inactive?
Would you like to skip a specific handler?
Do you need to switch off all trigger handlers during a data migration?
Do you need to bypass triggers in unit tests?

All of this and much more is possible with Trigger Lib.

Trigger Lib has three different bypass mechanisms:

  • Custom metadata
  • The Bypassable interface
  • The TriggerOrchestrator.bypass() method

Custom Metadata

Unlike many other trigger frameworks, Trigger Lib does NOT require custom metadata. However, you can still use it to switch off all handlers of an object, or a single handler, in production. This is very useful when you need to deploy an inactive handler to production: all you need is a TriggerHandler__mdt record for it with Bypass__c = true.

Bypassable Interface

Another mechanism is the Bypassable interface:

public interface Bypassable {
    Boolean bypassOn{Context}When();
}

The Bypassable interface is useful when you use feature flags or have very specific conditions based on org configuration. When bypassOn{Context}When returns true, the whole handler is skipped without checking whether any records qualify.
To use it, you only need to implement the interface, which forces you to implement the bypassOn{Context}When method.

public with sharing class ContactReachabilityValidator implements BeforeInsert.Validator, BeforeInsert.Bypassable {
    public static Boolean isBypassed = false;

    public Boolean bypassOnBeforeInsertWhen() {
        return ContactReachabilityValidator.isBypassed || System.isBatch();
    }

    public Boolean addErrorOnBeforeInsertWhen(TriggerTypes.InsertRecord record) {
        return //...;
    }

    public void addErrorOnBeforeInsert(TriggerTypes.RejectableInsertRecord record) {
        // ...
    }
}

bypass() Method

You can bypass handlers in code and unit test in a few different ways: all handlers for a given SObjectType, a specific orchestrator, or a specific handler. You can even bypass everything by simply calling TriggerOrchestrator.bypass().all().

TriggerOrchestrator.bypass() returns TriggerOrchestrator.Bypassable, which is a different interface from the handler add-on above:

public interface Bypassable {
    Bypassable sObject(SObjectType sObjectType);
    Bypassable orchestrator(System.Type orchestrator);
    Bypassable handler(System.Type handler);
    void all();
    void clear();
}

Example

TriggerOrchestrator.bypass()
    .sObject(Account.SObjectType)
    .handler(ContactFollowUpTaskWriter.class);

// operation here

TriggerOrchestrator.bypass().clear();

Recursion Control

Trigger Lib offers recursion control only in the update contexts (Before Update and After Update), because that’s where infinite loops usually happen: an update runs logic that updates the same record again. Every populator, writer and dispatcher counts how many times it has run for each record in the transaction. A run counts only when the predicate returns true.

By default, the depth is 3 and nothing is skipped. Each time a record comes back after 3 runs, the library logs an error through your Logger, but the handler still runs. An endless loop still fails the save at Salesforce’s limit of 16 nested triggers.

To stop the handler instead, implement the RecursionGuard interface and its maxRunsPerRecordOn{Context}() method, which returns the depth. When a record reaches it, the library logs an error and skips the handler for that record.

public interface RecursionGuard {
    Integer maxRunsPerRecordOnBeforeUpdate();
}

public interface RecursionGuard {
    Integer maxRunsPerRecordOnAfterUpdate();
}

Example

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

    public Boolean writeOnAfterUpdateWhen(TriggerTypes.UpdateRecord record) {
        return // ...;
    }

    public void writeOnAfterUpdate(TriggerTypes.UpdateRecord record, TriggerTypes.UnitOfWork unitOfWork) {
        // ...
    }
}

Testing (no DMLs needed)

You can test your handlers as part of end-to-end tests, where you insert records and check that your logic works as expected. But imagine you’ve just written a small Populator and now need to test it. An end-to-end test requires knowing the relationships between objects: you need to check the existing test data factory or builder, update the test setup… ahhh, a lot of work for such a small Populator. Another way is to call each Populator method separately, but that doesn’t make sense, as you don’t test the class as a whole.

Trigger Lib gives you a third option: mocking with TriggerOrchestrator.mock() and TriggerOrchestrator.runTestFor(...).

You mock the whole trigger context and test your handler as a whole: the predicate, the action, the add-ons and the Finalizer all run, without a trigger and without inserting any records. Trigger Lib runs its own queries and commits through SOQL Lib and DML Lib, so you can mock them too: withParent(...) supplies the parents, and DML.mock('triggerUow') replaces the commit of the shared unit of work. Sibling and child queries can be mocked as well, as long as your RecordsProvider uses SOQL Lib; an inline [SELECT …] reads the test’s own data.

@IsTest
static void populateOnBeforeInsertWithMixedCaseEmail() {
    // Setup
    Contact doe = new Contact(LastName = 'Doe', Email = 'Jane.Doe@Example.com');

    TriggerOrchestrator.mock().beforeInsertFor(ContactEmailNormalizationPopulator.class).with(doe);

    // Test
    TriggerOrchestrator.runTestFor(new ContactEmailNormalizationPopulator());

    // Verify
    Assert.areEqual('jane.doe@example.com', doe.Email, 'The email should be lowercased.');
}
@IsTest
static void writeOnAfterInsertWithCustomer() {
    // Setup
    Account acme = new Account(Name = 'Acme', Type = 'Customer - Direct');

    DML.mock('triggerUow').allDmls();

    TriggerOrchestrator.mock().afterInsertFor(AccountWelcomeTaskWriter.class).with(acme);

    // Test
    TriggerOrchestrator.runTestFor(new AccountWelcomeTaskWriter());

    // Verify
    Task onboardingCall = (Task) DML.retrieveResultFor('triggerUow').insertsOf(Task.SObjectType).records()[0];
    Assert.areEqual('Onboarding call - Acme', onboardingCall.Subject, 'The task should name the account.');
}

Repository

Summary

Trigger Lib isn’t just another trigger library that only gives your trigger handlers a structure. It’s a whole framework that pushes your developers and AI agents to write code the right way. It runs queries and DML in bulk for them, and it stops them from making stupid mistakes: SOQL or DML in a handler’s per-record methods fails the save.
You can try it by copying the code from the Trigger Lib GitHub repository, together with SOQL Lib and DML Lib, or by installing the unlocked package. You’ll find every option on the Installation page.

Piotr Gajek
Piotr Gajek
Senior Salesforce Developer
Technical Architect and Full-stack Salesforce Developer. He started his adventure with Salesforce in 2017. Clean code lover and thoughtful solutions enthusiast.

You might also like

SOQL Lib

SOQL Lib

The SOQL Lib provides functional constructs for SOQL queries in Apex. Use the SOQL Lib as a Selector Layer on your project.

Piotr Gajek
Piotr Gajek

Senior Salesforce Developer

Apex Queueable Processing Framework

Apex Queueable Processing Framework

Struggling with “Too many queueable jobs” errors in Salesforce? This guide introduces AsyncLib, a framework that manages Apex asynchronous processing with queueable chains. It helps overcome strict governor limits by chaining jobs using Salesforce’s Finalizer interface. AsyncLib simplifies async execution, error handling, and scheduling for Queueable, Batchable, and Schedulable jobs—no more complex workarounds or manual tracking.

Mateusz Babiaczyk
Mateusz Babiaczyk

Salesforce Certified Technical Architect