Skip to content
Tutorials Center
My learning

Topics

Lesson 25 of 36 ยท Asynchronous Apex

Batch Apex: start, execute, finish and Scope Size

Learn Batch Apex: the Database.Batchable interface, start, execute and finish, scope size, Database.Stateful, chaining and testing, with a runnable Java chunking stand-in.

What if you must update two million records? A normal transaction would hit governor limits within the first few hundred. Batch Apex splits the job into chunks. Each chunk (a "scope", 200 records by default) runs as its own transaction with a fresh set of limits, so a very large data set can be processed safely. If one chunk fails, the others still complete.

Batch Apex needs an org to run. The Apex code below is read-only; the Java stand-ins model chunking and statefulness so you can experiment with the numbers.

The three methods

A batch class implements Database.Batchable<sObject> and provides:

  1. start: returns the records to process, as a Database.QueryLocator (up to 50 million rows) or an Iterable.
  2. execute: called once per chunk with a list of records.
  3. finish: called once at the end, for summaries, emails or chaining the next job.
APEX
public with sharing class StaleLeadCleanup implements Database.Batchable<SObject>, Database.Stateful {
    private Integer processed = 0;
    private Integer failed = 0;

    public Database.QueryLocator start(Database.BatchableContext bc) {
        return Database.getQueryLocator(
            'SELECT Id, Status FROM Lead WHERE LastActivityDate < LAST_N_DAYS:365 AND IsConverted = false');
    }

    public void execute(Database.BatchableContext bc, List<Lead> scope) {
        for (Lead l : scope) {
            l.Status = 'Archived';
        }
        List<Database.SaveResult> results = Database.update(scope, false);
        for (Database.SaveResult r : results) {
            if (r.isSuccess()) { processed++; } else { failed++; }
        }
    }

    public void finish(Database.BatchableContext bc) {
        System.debug('Archived ' + processed + ' leads, ' + failed + ' failed');
    }
}

Run it and choose a scope size (the number of records per execute call, 1 to 2,000; default 200):

APEX
Id jobId = Database.executeBatch(new StaleLeadCleanup(), 100);

A smaller scope uses fewer limits per transaction (helpful if each record triggers callouts or heavy logic); a larger one finishes faster.

Database.Stateful

By default each execute call gets a fresh copy of the class; member variables are reset. Implement Database.Stateful to keep values across chunks, as the counters above do. Stateful batches are a little slower because the state is serialised between chunks, so use it only when you need totals.

Partial success with Database methods

update scope; fails the whole chunk if one record fails. Database.update(scope, false) allows partial success and gives a SaveResult per record, so you can count and log failures. Use it in batch jobs.

Limits and rules worth knowing

  • Up to 5 batch jobs can be running at once; others wait in the Apex flex queue (up to 100 holding).
  • Each chunk has the usual per-transaction limits (for example 100 SOQL queries for sync, 200 for async), but they are fresh for every chunk.
  • In start, a QueryLocator ignores the 50,000 row SOQL limit; an Iterable is limited by it.
  • Callouts from execute need Database.AllowsCallouts.
  • A running batch can call System.enqueueJob or another Database.executeBatch only from finish (batch chaining).
APEX
public void finish(Database.BatchableContext bc) {
    Database.executeBatch(new RecalculateScoresBatch(), 200);
}

Testing a batch

In a test, only one chunk executes: tests can run a batch against at most scope-size records. Insert fewer than 200 rows, call Database.executeBatch between startTest and stopTest, then assert.

APEX
@isTest
static void archivesStaleLeads() {
    List<Lead> leads = new List<Lead>();
    for (Integer i = 0; i < 50; i++) {
        leads.add(new Lead(LastName = 'Stale ' + i, Company = 'Co', Status = 'Open'));
    }
    insert leads;

    Test.startTest();
    Database.executeBatch(new StaleLeadCleanup(), 200);
    Test.stopTest();

    Assert.areEqual(50, [SELECT COUNT() FROM Lead WHERE Status = 'Archived']);
}

(In a real test you would also need the LastActivityDate condition satisfied, for example by changing the query for tests; keeping the SOQL in an overridable method is a common technique.)

Try the idea: chunking (Java stand-in)

Java Stand-in: split records into scopes (Java)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

1,050 records at scope 200 give six chunks: five full ones and a last one of 50. In Apex each chunk is a separate transaction.

Try the idea: Stateful and partial failure (Java stand-in)

Java Stand-in: totals across chunks with one bad record (Java)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

This mirrors Database.update(scope, false): good rows are saved, bad rows are counted, and one bad record does not abort the job.

Batch, queueable or something else?

flowchart TD
    A["How many records?"] -->|"a handful"| B["@future or Queueable"]
    A -->|"thousands, ordered steps"| C["Queueable chain"]
    A -->|"tens of thousands to millions"| D["Batch Apex"]
    A -->|"at a fixed time"| E["Scheduled Apex starts a batch"]

Pick the tool by volume and timing. Scheduled Apex often launches a batch job; see the next lesson.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does the finish method of a batch class do?

    finish runs once at the end; execute runs per chunk; start supplies the records.
  2. 2. What is the default scope size?

    Database.executeBatch uses 200 records per chunk unless you pass a scope size between 1 and 2,000.
  3. 3. Why implement Database.Stateful?

    Without Stateful, member variables reset for each chunk; Stateful preserves them, at some cost.
  4. 4. Why use Database.update(scope, false) in execute?

    The false argument turns off all-or-none behaviour; you inspect each SaveResult.

Summary

  • Batch Apex processes huge data sets in chunks; each chunk is a fresh transaction.
  • Implement start, execute, finish; launch with Database.executeBatch(job, scopeSize).
  • Use Database.Stateful for totals and Database.update(..., false) for partial success.
  • Test with fewer than one chunk of records between startTest and stopTest.

Next: Scheduled Apex and Cron Expressions