We know Salesforce works on a multi-tenant architecture and has implemented a runtime engine to make sure nobody monopolizes the resources. In this regard, Salesforce implements governor limits and one of the many governor limits applied in Salesforce is only 10,000 records can be processed at a time. Now, what if our organization has millions of records to update on a regular basis? What if you are dealing with critical data say Bank application data and often need to make changes to them?  Batch Apex in Salesforce helps to accomplish such crucial requirements. Let us dive down into the concepts of the Batch Apex.

What is Batch Apex in Salesforce?

Batch apex covers the entire set of records that needs to be processed and divide it into small manageable chunks. This is a very powerful method of executing millions of records like in data cleaning or archiving records which otherwise would hit the governor limit in normal DML operation.

Batch Apex in Salesforce
Batch Apex divides records into Small Chunks

Each of the batches will be under the governor limit and a developer will be able to process up to 50 million records. Batch Apex is an Asynchronous apex, which means it will not run immediately with any user action but when the resources are available for the operation.

Benefits of Batch Apex

Some of the key advantages on Batch Apex in Salesforce are:

  1. Batch apex helps to execute millions of records without hitting the governor limits.
  2. A developer can Schedule a batch class to run at different time and frequency.
  3. If one of the batches fails to process the records, other batches will not rollback.

Normal Apex vs Batch Apex – Governor limits

Governor LimitsApexBatch Apex
Total number of SOQL queries issued100200
Total number of records retrieved by SOQL queries50,00050 million
Total Heap Size6 MB12 MB

Batch class in Salesforce

To invoke batch Apex in Salesforce programmatically a class must implements database.batchable interface which includes 3 methods mentioned below:

  • start()
  • execute()
  • finish()

Let us understand each of these methods in detail:

start(): This method is called at the starting of the batch job to collect the records on which the operation will perform. This method returns either a Database.QueryLocator object or an iterable having the records or objects passed to the job.QueryLocator object bypasses the governor limit for the total number of records retrieved by SOQL queries.

Syntax:
 global(Database.QueryLocator|Iterable<sObject>) start(Database.BatchableContext bc) {}

Note:

  •  Use the Database.QueryLocator object if you are having a simple query to create the scope of objects in the batch job.
  • Use the iterable object when you create complex/custom scope for the batch job

execute(): This method performs all the operation defined on each chunk of data. Data that is collected using start method are divided into default batch size of 200 and the execute method is called every time for each of the batches.

Syntax: global void execute(Database.BatchableContext BC, list<sObject>){}

Batches of information appears to execute in the order they come from the start method. However, the order in which batches of data execute cannot be confirmed as it depends on various other factors.

finish(): finish method is called after all records are processed for the post-processing operations like sending an email, executing another batch job i.e. Chaining Batch jobs( we will discuss this later in this post).

Syntax: global void finish(Database.BatchableContext BC){}

How to create a batch class

  1. Go to settings and click on setup
go to setting and click on setup

  2. Go to quick find and search for Apex class under Platform Tools–> Custom code as shown below:

Search Apex class for batch apex in Saleforce

3. Click on the Apex class and click on the New button 

Create batch apex in salesforce

Let us take an example of a batch Apex where we need to update the custom field status__c of contact with Processed

/********************* Sample Batch Class****************/

  global class batchContactUpdate implements Database.Batchable<sObject> {
// Start
    global Database.QueryLocator start(Database.BatchableContext BC) {
        String query = 'SELECT Id,Name,status__c FROM Contact';
        return Database.getQueryLocator(query);
    }
   // Execute
    global void execute(Database.BatchableContext BC, List<Contact> scope) {
         for(Contact c : scope)
         {c.status__c= 'Processed';            
         }
         update scope;
    }   
    // Finish
    global void finish(Database.BatchableContext BC) {
    }
}

/********************* End of the code******************/

Aftere writing the batch class, save it and open the Anonymous Apex block in the developer console and enter the following code to execute :

batchContactStatusUpdate cs = new batchContactStatusUpdate ();
database.executeBatch(cs);

As you can see below from the logs our batch class has executed successfully and records are also updated properly.

solution

Batch class Testing

  1. While testing a batch apex in Salesforce you can test only one execution of the execute method. Implement the scope parameter of the executeBatch method to limit the number of records passed into the execute method. This would ensure that you aren’t hitting the governor limits.
  2. The executeBatch method will invoke an asynchronous process. More sure that the asynchronously processed batch job is finished before testing against the results.
  3.  Use the Test methods startTest and stopTest around the executeBatch method to ensure that it finishes before continuing your test. System collects any asynchronous calls made post startTest method.

Governor limits in Batch Apex

  1. start method from only one apex job can run at a run time in an organization.
  2. Up to 5 queued or active batch jobs are allowed for the apex.
  3. The maximum batch apex method in executions per 24 hour period is 2,50,000.
  4. Start method could have up to 15 query cursors open at a time per user.
  5. At max, 50 million records can be returned in the Database.QueryLocator object.
  6. The Start, Execute and Finish method of the batch apex can use up to 10 callouts each.

Batch Apex best practices

  • Use Batch Apex efficiently only if you have more than one batch of records. Otherwise, it is better to use Queueable Apex.
  • Implement the SOQL query properly to fetch records faster.
  • Try to minimize the Asynchronous requests to reduce the delay chances.
  • If you are trying to invoke a batch job using a trigger, make sure the trigger does not add more batch jobs than the limit.

Chaining Batch jobs

  • API version 26.0 onwards, you can invoke another batch job from an existing batch job to chain batch jobs together. 
  • Chain two batch job, when the first job finishes other start batch processing, Use this concept when processing large data volumes. if batch processing isn’t needed, it is better to use Queueable Apex.
  • Call Database.executeBatch or System.scheduleBatch from the finish method of the current batch class to invoke another batch job. The new batch job will start after the first batch job finishes.

Let me know if you like this post, your feedback really matters.

Refer :

  1. Batch Apex interview questions asked in top IT companies
  2. Batch Apex Trailhead module for practical coding experience 

Reference :

  1. https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_batch_interface.htm


2 Comments

RAHUL TALANKAR · January 9, 2020 at 11:01 am

Very well Explain you. step by step.

    Nilesh Raj · January 9, 2020 at 12:17 pm

    Thanks Rahul, I am glad you liked the post.

Did you Like the content? Let me know

%d bloggers like this: