Batch Apex: A Developer’s Guide

Harsh VermaHarsh Verma
4 min read

In Salesforce development, efficiently managing large volumes of data is a common challenge. Apex Batch is an essential feature that allows developers to process records in the background, enhancing performance and user experience. In this guide, we’ll dive into what Apex Batch is and how it functions.

What is Batch Apex?

Batch Apex is designed for handling large jobs that involve thousands or even millions of records, which could exceed normal processing limits. By processing records asynchronously in manageable chunks—hence the name "Batch Apex"—you can effectively stay within Salesforce's platform limits. If your tasks include data cleansing, archiving, or similar operations, Batch Apex is often the best solution.

How Does Batch Apex Work?

Let’s consider a scenario where you need to process 1 million records using Batch Apex. The execution logic in your batch class is invoked for each set of records being processed. When you initiate a batch job, it is added to the Apex job queue and executed as a discrete transaction. This approach provides two significant advantages:

  1. Fresh Governor Limits: Each transaction begins with a new set of governor limits, making it easier to ensure your code operates within Salesforce’s constraints.

  2. Transaction Independence: If one batch fails, any previously successful transactions remain unaffected, allowing for greater reliability in processing.

Batch Apex Syntax

To implement Batch Apex, you need to create a class that implements the Database.Batchable interface include the following three methods.

  1. Start Method: The start method is responsible for collecting the batches of records or objects that will be processed. It runs once at the beginning of the batch job and returns a Database.QueryLocator or an Iterable.

  2. Execute Method: The execute method processes the records that were collected by the start method. This method is called for each batch of records and contains the logic for how each batch will be handled. Here, you can perform operations like updates, inserts, or deletes.

  3. Finish Method: The finish method executes any post-processing operations after all batches have been processed. It is called once when the entire batch job is complete. You can use this method for tasks such as sending notifications, logging results, or performing cleanup actions.

Batch Apex is typically stateless, treating each execution as a separate transaction. For example, a job processing 1,000 records in batches of 200 runs as five distinct transactions. However, by implementing the Database.Stateful interface, you can maintain state across these transactions.

Here’s what the skeleton of a Batch Apex class looks like:

Sample Batch Apex Code

global class POCBatchApex implements Database.Batchable<sObject>, Database.Stateful {
    // Variable to keep track of the number of batches processed
    global Integer noOfBatches = 0;

    // Start method to define the scope of records to process
    global Database.QueryLocator start(Database.BatchableContext BC) {
        return Database.getQueryLocator('SELECT Id, Name FROM Account');    
    }

    // Execute method to process each batch of records
    global void execute(Database.BatchableContext BC, List<Account> lstAccount) {
        noOfBatches += 1; // Increment the batch counter

        for (Account acc : lstAccount) {
            acc.Name += ' ForceDev'; // Update the account name
        }

        try {
            update lstAccount; // Attempt to update the accounts
        } catch (Exception e) {
            System.debug(e); // Log any exceptions
        }
    }

    // Finish method to execute after all batches are processed
    global void finish(Database.BatchableContext BC) {
        System.debug('Number of Batches Processed: ' + noOfBatches);
    }
}

To run a Batch Apex class, follow these steps:

  1. Instantiate the Batch Class: Create an instance of your Batch Apex class.

  2. Call Database.executeBatch: Use this method to start the batch processing.

You can optionally specify a second parameter to define the batch size, which determines how many records are processed in each execution of the execute method.

Before

After

To check the status of Apex Job, go to Salesforce org setup and in Quick find box type Apex Jobs. You will see the list of Apex jobs.

Conclusion

Batch Apex is an invaluable tool for Salesforce developers, enabling the efficient processing of large datasets while adhering to platform limits. By leveraging its capabilities, you can ensure that your data processing tasks are both effective and resilient.

0
Subscribe to my newsletter

Read articles from Harsh Verma directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Harsh Verma
Harsh Verma