July 22, 2026By Komal Wavare

Batch Apex in Salesforce

Salesforce is one of the world’s leading Customer Relationship Management (CRM) platforms, widely used by organizations to manage customers, sales, marketing, and business processes. As businesses grow, the volume of data in Salesforce increases significantly. Processing thousands or millions of records using standard Apex can quickly exceed Salesforce governor limits.

To overcome this challenge, Salesforce provides Batch Apex, a powerful asynchronous processing framework designed to handle large volumes of data efficiently. Instead of processing all records at once, Batch Apex divides data into smaller chunks called batches, allowing each batch to execute independently with fresh limits.

What is Batch Apex?

Batch Apex is an asynchronous Apex feature that enables developers to process large datasets by splitting them into manageable batches. Each batch runs as a separate transaction, ensuring better performance and scalability.

For example, if an organization needs to update 500,000 Account records, Batch Apex can process them in batches of 200 records, resulting in 2,500 transactions.

Why Do We Need Batch Apex?

Standard Apex works well for small datasets, but it struggles with large-scale operations due to governor limits such as:

Key Limitations of Standard Apex

  • SOQL query limits
  • DML statement limits
  • CPU execution time
  • Heap size limits
  • Record processing limits

How Batch Apex Solves These Issues

Batch Apex resets governor limits after each batch execution, making it ideal for handling large data volumes efficiently.

Features of Batch Apex

Batch Apex provides several powerful features:

  • Processes millions of records efficiently
  • Runs asynchronously in the background
  • Provides fresh governor limits per batch
  • Supports job scheduling
  • Enables monitoring via Apex Jobs
  • Allows partial success handling
  • Supports Database.Stateful
  • Supports external API callouts (Database.AllowsCallouts)

Batch Apex Lifecycle

Every Batch Apex class implements the Database.Batchable interface, which includes three key methods:

1. start() Method

The start() method identifies the records to process.

Returns:

  • Database.QueryLocator
  • Iterable Collection

Example Query:

SELECT Id, Name FROM Account


This method executes only once.

2. execute() Method

The execute() method contains the core business logic.

  • Records are automatically divided into batches
  • Each batch runs as a separate transaction

Example Flow:

  • 2000 records
  • Batch size = 200
  • 10 execute() calls

Each execution receives a List (scope).

3. finish() Method

The finish() method executes after all batches are processed.

Common Use Cases:

  • Sending completion emails
  • Logging execution results
  • Chaining batch jobs
  • Generating reports
  • Updating audit records

Execution Flow of Batch Apex

The Batch Apex process follows a structured flow:

  1. Batch Job Starts
  2. start() executes
  3. Records are collected
  4. Records are divided into batches
  5. execute() runs for each batch
  6. finish() executes
  7. Job status becomes Completed


Batch Size in Batch Apex

  • Default batch size: 200 records
  • Minimum: 1
  • Maximum: 2000

Example:

Database.executeBatch(new UpdateAccountBatch(), 100);


Recommended batch size: 100–200 depending on logic complexity.

Database.QueryLocator vs Iterable

QueryLocator

Advantages:

  • Processes up to 50 million records
  • Uses SOQL queries
  • Better performance
  • Most commonly used

Use Case:

Updating all Account records

Iterable

Advantages:

  • Supports custom collections
  • Handles external API data
  • Useful for complex logic

Use Case:

Processing external web service data

Database.Stateful

By default, each execute() method is stateless, meaning variables reset after every transaction.

To preserve values across batches, use:

Database.Stateful

Example:

Integer totalUpdated = 0;


Use Cases:

  • Total processed records
  • Success and failure counts
  • Revenue calculations
  • Migration tracking

Database.AllowsCallouts

To make external API calls, implement:

Database.AllowsCallouts

Examples:

  • SAP integration
  • Payment gateways
  • Shipping APIs
  • Banking systems
  • ERP integrations

Real-World Use Cases of Batch Apex

Batch Apex is widely used in enterprise environments:

  • Customer Data Cleanup – Remove duplicates
  • Annual Discount Updates – Update pricing in bulk
  • Loan Processing – Evaluate large datasets
  • Hospital Management – Update patient records
  • E-Commerce – Archive old orders
  • Banking – Interest calculations
  • Insurance – Policy renewals
  • Education – Student status updates

Batch Apex Monitoring

Salesforce allows monitoring via:

Navigation Path:

Setup → Apex Jobs

Details Available:

  • Job ID
  • Status
  • Created Date
  • Processed Records
  • Failed Records
  • Completion Time

Developers can also use the AsyncApexJob object.

Batch Chaining

Batch jobs can trigger other batch jobs using the finish() method.

Example Flow:

  • Import Customers
  • Update Orders
  • Generate Reports

This ensures sequential execution of dependent processes.

Error Handling in Batch Apex

Proper error handling ensures system reliability.

Best Practices:

  • Use try-catch blocks
  • Log failed records
  • Store error messages
  • Retry failed batches
  • Notify administrators

Governor Limits in Batch Apex

Important limits include:

  • Up to 50 million records (QueryLocator)
  • Default batch size: 200
  • Max batch size: 2000
  • Fresh limits for each execute() call
  • Supports asynchronous processing

Advantages of Batch Apex

  • Handles large datasets efficiently
  • Prevents governor limit violations
  • High performance
  • Reliable execution
  • Supports scheduling
  • Easy monitoring
  • Scalable architecture
  • Enterprise-ready solution

Limitations of Batch Apex

  • Slower for small datasets
  • More complex than triggers
  • Results are not immediate
  • Requires careful error handling
  • Queue limits may delay execution

Best Practices for Batch Apex

To build efficient solutions:

  • Process only required fields
  • Write optimized SOQL queries
  • Prefer QueryLocator
  • Avoid SOQL/DML inside loops
  • Keep logic simple in execute()
  • Use Stateful only when needed
  • Log failures properly
  • Choose appropriate batch size
  • Test with large datasets
  • Monitor jobs regularly

Conclusion

Batch Apex in Salesforce is a powerful tool for handling large-scale data processing. By dividing records into smaller chunks, it ensures efficient execution while staying within governor limits.

For developers working on enterprise-level applications, mastering Batch Apex is essential for building scalable, reliable, and high-performance solutions.

Author:

Komal Wavare

Related Links:

Anthropic AI Tool

What is Writesonic

What is Claude AI

AI Engineer Roadmap

What is JasperAI

What is Copy AI

Do visit our channel to know more: SevenMentor


Komal Wavare

Expert trainer and consultant at SevenMentor with years of industry experience. Passionate about sharing knowledge and empowering the next generation of tech leaders.

#Technology#Education#Career Guidance
Batch Apex in Salesforce | SevenMentor