The New Asynchronous Apex Triggers in Summer 19 release

Asynchronous Apex Triggers helps to reduce the Apex Transaction time .

As a developer, you are always looking to shorten your time spent on development time. One area that can be improved is waiting for triggers to respond.

How Does It Work?

With Apex change event triggers, you can now process change event messages on the Lightning Platform. Change event triggers run asynchronously after the database transaction is completed.

You can now perform resource-intensive business logic asynchronously in the change event trigger and keep transaction-based logic in the Apex object trigger. By decoupling the processing of changes, change event triggers can help reduce transaction processing time.

Use Case

To reduce transaction times and limit constraints, move your complex logics or non-transactional logics to asynchronous processing Using Change Data Capture and Async Apex Triggers.

change data capture

Lets get some clarity on what Asynchronous and Change Data Capture is

Asynchronous Call

As before Summer’19, multiple ways of synchronous processing exists in Salesforce such as Batch Jobs, Scheduler Apex, Future method and Queueable Apex. In Summer 19 release, Salesforce provides another feature called “Asynchronous Apex Triggers” that can process data asynchronously Using Change Data Capture (CDC).

Change Data Capture (CDC)

Change Data Capture is a streaming product on the Lightning Platform that enables you to efficiently integrate your Salesforce data with external systems. With Change Data Capture, you can receive changes of Salesforce records in real time and synchronize corresponding records in an external data store. It also publishes events for changes in Salesforce records corresponding to create, update, delete, and undo operations.

How To Set Up

setup integration change data capture

Go to: Setup-> Integrations -> Change Data Capture

When enabling the Change Data Capture, Salesforce internally creates Change Event name that would look like below: 

  • Standard Object then STANDARDOBJECTAPINAMEChangeEvent.
  • Custom Object then CustomObjectName__ChangeEvent

Asynchronous Apex Trigger

These triggers run asynchronously after the database transaction is completed. A change event trigger is an “After Insert” trigger. The trigger fires after the change event message is published.

You can create an After Insert trigger in the Developer Console the same way how we create a Standard/Custom Object trigger after enabling the object for Change Data Capture.

Asynchronous Apex Triggers Example

  • Create a change event trigger that captures changes on opportunities
  • Create a follow-up task for opportunities whose stage is set to ‘Closed Won’.
  • Create a test method to provide test coverage for the trigger.

Step1: Enable Change Data Capture in Opportunity Object

Step 2: Create Apex Trigger in OpportunityChangeEvent Subject (After Insert)

Developer console opportunity change event

You can create an Asynchronous Apex Triggers in the developer console same way in Standard/Custon Object Triggers, while create a Asynchronous Apex Triggers make sure to select change even object from the object picklist.

Main Class

//trigger OpportunityChangeTrigger on OpportunityChangeEvent (after insert) 
{
    List<Task> tasks = new List<Task>();
    for(OpportunityChangeEvent opp : trigger.new) {
        EventBus.ChangeEventHeader header = opp.ChangeEventHeader;
        if (header.changetype == 'UPDATE') { 
//The trigger iterates all Event with changeType field is 'UPDATE'
            if(opp.isWon==true) { 
//check if opportunity isWon field is equal to true 
                Task newTask = new Task();
                newTask.Subject='Follow up on won opportunities: ' + header.recordIds;
                newTask.OwnerId = header.CommitUser;
                newTask.WhatId = header.recordIds[0];
                tasks.add(newTask);
            }
        }
    }
    if(tasks != null && !tasks.isEmpty()) {
        insert tasks; 
//insert the Task with all the isWon Opportunities
    }
}

Test Class

@isTest
public class TestOpportunityChangeTrigger {
    @isTest
    public static void test() {
        Test.enableChangeDataCapture();
        insert new Opportunity(Name = 'Sell 100 Widgets', StageName = 'Prospecting', CloseDate = Date.today().addMonths(3));
        Test.getEventBus().deliver();

        Task[] taskList = [SELECT Id, Subject FROM Task]; 
        System.assertEquals(0, taskList.size(), 'Unexpected task found');

        Opportunity updateOpp = [SELECT Id, Name, StageName, isWon, CloseDate from Opportunity][0];
        updateOpp.StageName = 'Closed Won';
        update updateOpp;
        Test.getEventBus().deliver();
        
        taskList = [SELECT Id,Subject FROM Task]; 
        System.assertEquals(1, taskList.size(), 'The change event trigger did not create the expected task.');        
        string start = 'Follow up on won opportunities';
        System.assertEquals(start, taskList[0].Subject.substring(0, start.length()), 'The task subject is wrong.');        
    }
}

Output Result

Create an opportunity and change the Stage as “Closed Won”.

Enable Activities and check the new Follow up on won Opportunity Task Created.

change data capture output result

Important Notes

  • Its Support All custom objects and a subset of standard objects are supported.
  • Change Data Capture sends notifications for created, updated, deleted, and undeleted records. 
  • For a standard object, the change event name is StandardObjectNameChangeEvent for example AccountChangeEvent
  • For a custom object, the change event name is CustomObjectName__ChangeEvent for example Employe__ChangeEvent (suffixed as __ChangeEvent) 
  • Asynchronous Apex triggers are change event triggers that run asynchronously after a database transaction is completed
  • Available only AFTER INSERT ChangeEvent
  • Default Allocations allow only 5 object entries to select Change Data Capture, if you like to enable more than 5 object, contact your Salesforce account team to enable Change Data Capture Add-on Licence

Reference Document

  1. Trailhead Badge for Change Data Capture Basics
  2. Change Data Capture Developer Guide
  3. Salesforce Release Notes
  4. Salesforce Document
  5. Salesforce Demo

Leave a Reply

%d bloggers like this: