What does Bulkify Mean?

Author: Bruce Tollefson Published: May 27, 2022; Modified: May 27, 2022
atom

Within Salesforce you have a bunch of governor transaction limits. These limits are are there for each transaction as a way to make sure one org is not able to use more resources than estimated / allotted for and slow down the whole tenant. That is where bulkifying comes in. This term is used to represent optimizing the Salesforce transaction. This requires a set of practices and patterns to be followed in order to properly implement.

Assume multiple records will be sent in a single Transaction

The biggest mindset change that you can make is to always think that the apex code you write or the flow trigger you create (yes flows need to be bulkified as well) will have a list of records run through it. Not single record.

Beware of Loops

Loops in general are very useful and used everywhere. However the quickest way to make sure your org is not optimized is to put a DML operation or SOQL query in the loop. A single transaction for the most part could have up to 200 records. If you have a single for loop with a SOQL query inside that runs for each record you will hit the SOQL query limit right away as the limit is 100 queries per transaction. The same will occur with a DML operation as the limit is 150 DML operations.

One thing that can be a little more complex is making sure that methods called within a loop do not contain SOQL queries or DML operations.

Perform Bulk DML Operations and SOQL Queries

As much as possible try to perform DML operations with a list instead of individual operations. One way to do this is if you need to perform the same type of DML operation on mutliple different objects is to put them in an sObject List. Instead of the following:

insert singleContact; insert opportunityLineItemList; insert singleTask; insert singleCustomObject;

you can add them to an sObject List:

List<sObject> sObjectList = new List<sObject>(); sObjectList.add(singleContact); sObjectList.add(opportunityLineItemList); sObjectList.add(singleTask); sObjectList.add(singleCustomObject); insert sObjectList;

This wouldn’t work if one record needed then other record’s Id before insert as that would need to be inserted first.

To bulkify SOQL queries you can use a set or list of Ids to get a list of records. One way to do this is to change a list into a Map<Id, sObject> by:

Map<Id, Account> accountMap = new Map<Id, Account>(accountListFromTrigger); List<Opportunity> acctOppList = [Select Id from Opportunity where AccountId IN :accountMap];

These few practices can change the apex code or flow (not everything would apply as flows can’t use maps) from not being bulkified to being bulkified.

Leave a Reply

Your email address will not be published. Required fields are marked *