Apex · Lightning · Salesforce · Trigger

Asynchronous Apex Trigger using Change Data Capture

Change Data Capture event is a notification that Salesforce sends when a change to a Salesforce record occurs as part of a create, update, delete, or undelete operation.

When we are saving a record in salesforce it causes the platform to start apex transaction . Change event triggers run asynchronously after the apex transaction is completed. 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.

How it works ?

First enable change data capture in your org.
1. steps : Setup -> Integrations -> Change Data Capture

2. Move object you want to enable Change Data Capture to Selected Entities.
(in developer org maximum 5 object can be selected)

Create Asynchronous Apex Triggers :
Steps : Developer Console -> File -> New -> Apex Trigger.
Naming convention to find change event object.
Standard Object : AccountChangeEvent [ObjectNameChangeEvent]
Custom Object : Data_Storage_Test__ChangeEvent [ObjectName__ChangeEvent]

Select the object and provide name for your Trigger.

trigger datastorageTriggerChangeEvent on Data_Storage_Test__ChangeEvent (after insert) {
    
    for(Data_Storage_Test__ChangeEvent rec : trigger.new){
        EventBus.ChangeEventHeader header = rec.ChangeEventHeader;
        if (header.changetype == 'CREATE') { 
            List<String> recordId = header.getRecordIds(); 
            //perform resource-intensive business logic here 
        }
        else if(header.changetype == 'UPDATE'){
            List<String> changedFields = header.changedfields; // list of fields updated
        }
        else if(header.changetype == 'DELETE'){
            
        }
        else if(header.changetype == 'UNDELETE'){
            
        }
    }
}

Debugging Asynchronous Apex Triggers :

Steps : Setup-> logs -> Debug Logs -> New.
Traced Entity Type : Automated Process
Debug Level : Default
Click Save.

you will be able to see debug logs generated from Asynchronous apex trigger.


Advantages:
Performance Comparison :

Performance in Duration(Approx) : O(N) where n = 1000000

Apex Trigger14905.77
Future Method called from Apex Trigger13830.23
Async Trigger299.24
Future Method called from Async Trigger289.67

we can clearly see reduced transaction processing time by using Asynchronous Apex triggers.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s