What is the Batch job in Salesforce?

Understanding Batch Jobs in Salesforce

Batch Apex in Salesforce is a powerful asynchronous processing framework designed to handle large volumes of data and long-running operations. When you need to process thousands (or millions) of records without hitting governor limits, Batch Apex lets you break the work into manageable chunks and process them sequentially or in parallel.

Key Components

Batch Apex uses three main interfaces:

  • start: Collects the set of records or objects to be processed. It returns a Database.QueryLocator or an Iterable<SObject>.
  • execute: Processes each batch of records. The batch size can be specified (default 200), and each execution runs in its own context.
  • finish: Executes post-processing logic once all batches have completed (e.g., sending notifications, chain another batch job).

Why use Batch Apex?

Batch Apex is ideal when you need to:

  • Process large data sets (beyond synchronous limits).
  • Avoid long-running transactions and governor limit issues.
  • Schedule recurring heavy processing using the Apex Scheduler.
  • Chain batch jobs for multi-step processing.

Example: Basic Batch Apex Class

public class AccountBatch implements Database.Batchable<SObject> {
public Database.QueryLocator start(Database.BatchableContext bc) {
return Database.getQueryLocator([SELECT Id, Name FROM Account WHERE CreatedDate = LAST_N_DAYS:30]);
}

public void execute(Database.BatchableContext bc, List<SObject> scope) {
List<Account> accounts = (List<Account>)scope;
for (Account a : accounts) {
// business logic here
}
update accounts;
}

public void finish(Database.BatchableContext bc) {
// final steps, e.g., send email or chain another job
}
}

Best Practices

  • Keep execute() logic focused and bulkified.
  • Use Database.Stateful if you need to maintain state across batches.
  • Handle exceptions carefully; consider using Database.saveResult to handle partial failures.
  • Monitor batch jobs via the Salesforce UI (Setup > Apex Jobs) or programmatically.
  • Limit chained batches to avoid exceeding the maximum number of apex jobs.

Limits and Considerations

Key limits to remember:

  • Each batch execution has its own governor limits.
  • Maximum batch size is 2,000; default is 200.
  • Maximum of 5 queued or active batch jobs at one time (per org limits may vary with flex queues).
  • Batch Apex can be executed via Apex, scheduled, or invoked from the UI/Triggers.

Batch Apex remains a cornerstone for scalable data processing on the Salesforce platform. Proper design and testing ensure it delivers robust performance while respecting multi-tenant governor limits.