Database.BatchableContext is the context object that Salesforce passes to all three lifecycle methods of a batch class. Its sole purpose is to carry the JobId of the running batch so your code can identify and query the job.
The interface
The class has two methods:
Id getJobId(); // Returns the AsyncApexJob Id
Id getChildJobId(); // Returns the child AsyncApexJob Id of the currently executing chunk
That’s it. No state, no helpers, no configuration — just JobIds.
How you use it
public class MyBatch implements Database.Batchable<sObject> {
public Database.QueryLocator start(Database.BatchableContext ctx) {
System.debug('Job kicking off with Id ' + ctx.getJobId());
return Database.getQueryLocator('SELECT Id FROM Account');
}
public void execute(Database.BatchableContext ctx, List<Account> scope) {
// ... process chunk
}
public void finish(Database.BatchableContext ctx) {
AsyncApexJob job = [
SELECT Status, JobItemsProcessed, TotalJobItems,
NumberOfErrors, CreatedBy.Email
FROM AsyncApexJob
WHERE Id = :ctx.getJobId()
];
// ... send completion email
}
}
ctx.getJobId() is the most-used method. You’ll see it in nearly every production finish method to fetch the job’s final status.
What’s getChildJobId() for?
Each chunk’s execute runs as its own AsyncApexJob of type BatchApexWorker, a child of the parent BatchApex job. getChildJobId() returns that worker’s Id — useful if you want to log per-chunk diagnostics:
public void execute(Database.BatchableContext ctx, List<Account> scope) {
try {
// ... work
} catch (Exception e) {
insert new Batch_Error__c(
Parent_Job__c = ctx.getJobId(),
Worker_Job__c = ctx.getChildJobId(),
Message__c = e.getMessage()
);
throw e;
}
}
In practice, getChildJobId() is rarely used. getJobId() covers 95% of needs.
Why the parameter exists at all
Database.BatchableContext decouples your batch from the platform’s job-tracking machinery. Before this interface existed, you couldn’t reference the running job from inside it — you’d have to scan AsyncApexJob looking for “your” job, which is racy. With BatchableContext, the platform hands you the Id directly.
Common interview follow-ups
- Can I store the context in an instance variable? — Yes, but you rarely need to — each method gets the context as a parameter.
- Is
BatchableContextavailable outside the batch? — No. It only exists insidestart/execute/finish. - Is there an equivalent for Queueable? — Yes —
QueueableContextwithgetJobId(). Same idea, different interface.
Verified against: Apex Developer Guide — Database.BatchableContext Interface. Last reviewed 2026-05-17.