Asynchronous Apex Trigger

Did you know that there is a way to run Triggers Asynchronously in Salesforce?

Yes, you read that right.

Sometimes there are too many operations in an Apex Trigger and it feels better to run a new operation asynchronously. 

To make a trigger run asynchronously you have to follow two steps:

  1. Enable the Change Data Capture for the object you want to create a trigger.
  2. Create an Apex Trigger for the object change event.

Explanation:

By enabling the Change Data Capture for any object, salesforce will automatically publish an event every time a record will be inserted, updated, deleted, or undeleted.

That event will be captured by the Apex Trigger.

Example Problem: When an Opportunity is Created or Updated then segregate the opportunity on the basis of some complex logic which takes a lot of time.

Solution: Since the segregation logic is complex it will be better to run the trigger asynchronously.

  1. So first we go to Setup -> Change Data Capture and add Opportunity to the Multi Select Picklist and save it.
  2. Next, we create a Trigger called OpportunityChangeAsyncTrigger which will run on OpportunityChangeEvent. 

The code will look something like this ->

trigger OpportunityChangeAsyncTrigger on OpportunityChangeEvent(after insert){
	List<OpportunityChangeEvent> changes = Trigger.new;
	
	//We capture all the opportunity id’s to act upon them.
	Set<String> oppIds = new Set<String>();
	for(OpportunityChangeEvent opp : changes){
		List<String> recordIds = opp.ChangeEventHeader.getRecordIds();
        		oppIds.addAll(recordIds);
        }
        // Resource Intensive Task
        Map<String, String> opportunityClassifier =  classifier.classifyOpportunity(oppIds);
}

Note: Only after insert, update, delete and, undelete operations are allowed in asynchronous apex. You can not use a before-trigger with an asynchronous trigger.