Spring Batch Processing
Spring Batch Processing Interview with follow-up questions
1. What is Spring Batch and why is it used?
Spring Batch is a framework for reliable, large-scale batch processing in Java — running jobs that process big volumes of data without user interaction. It's used for ETL (extract-transform-load), data migration, cleansing, reconciliation, and report/file generation.
Why it's used (what it gives you over a hand-rolled loop):
- Chunk-oriented processing — read/process/write in chunks with a commit per chunk, so you handle datasets that don't fit in memory.
- Transaction management — each chunk is transactional, ensuring integrity.
- Restartability — execution state is persisted in the
JobRepository, so a failed job resumes from the failure point instead of reprocessing everything. - Fault tolerance — configurable skip and retry with backoff for bad/transient records.
- Scalability — multi-threaded steps, partitioning, remote chunking.
- Operational visibility — job/step metadata, status, and listeners.
@Bean
Step step(JobRepository repo, PlatformTransactionManager tx) {
return new StepBuilder("load", repo)
.chunk(500, tx)
.reader(reader()).processor(processor()).writer(writer())
.faultTolerant().skipLimit(10).skip(ParseException.class)
.build();
}
The 2026 note: with Spring Batch 5 / Boot 3+, it runs on Jakarta, @EnableBatchProcessing is optional (auto-configured), and the old JobBuilderFactory/StepBuilderFactory are replaced by JobBuilder/StepBuilder. The core value proposition — robustness, restartability, and scale for bulk data — is unchanged.
Follow-up 1
Can you explain the architecture of Spring Batch?
The architecture of Spring Batch follows a layered approach. At the highest level, there is a Job, which consists of one or more Steps. Each Step consists of one or more ItemReaders, ItemProcessors, and ItemWriters. The ItemReader is responsible for reading data from a data source, the ItemProcessor processes the data, and the ItemWriter writes the processed data to a destination. The JobLauncher is responsible for starting and managing the execution of Jobs. The JobRepository is used to store the metadata about the Jobs and their execution status.
Follow-up 2
What are the key components of Spring Batch?
The key components of Spring Batch are:
- Job: Represents a batch job and consists of one or more Steps.
- Step: Represents a single step within a Job and consists of an ItemReader, ItemProcessor, and ItemWriter.
- ItemReader: Reads data from a data source and provides it to the ItemProcessor.
- ItemProcessor: Processes the input data and optionally transforms it.
- ItemWriter: Writes the processed data to a destination.
- JobLauncher: Responsible for starting and managing the execution of Jobs.
- JobRepository: Stores the metadata about the Jobs and their execution status.
Follow-up 3
How does Spring Batch handle large datasets?
Spring Batch provides chunk-based processing to handle large datasets efficiently. In chunk-based processing, the data is read in chunks, processed, and then written in chunks. This allows Spring Batch to process large datasets without loading the entire dataset into memory at once. The size of the chunks can be configured based on the specific requirements of the application. Additionally, Spring Batch provides features like restartability and transaction management to ensure the reliability and consistency of the batch processing.
Follow-up 4
What is the role of JobRepository in Spring Batch?
The JobRepository in Spring Batch is responsible for storing the metadata about the Jobs and their execution status. It provides a way to persist the state of the batch jobs, allowing them to be restarted or resumed in case of failures or system restarts. The JobRepository also manages the transactional aspects of the batch processing, ensuring that the data is processed consistently and reliably. By default, Spring Batch uses a relational database as the storage for the JobRepository, but it can be customized to use other storage mechanisms as well.
2. What is a Job in Spring Batch and how is it configured?
A Job is the top-level unit of work in Spring Batch — an ordered flow of one or more Steps. You configure it as a Spring bean using the JobBuilder, defining the step sequence and any job-level listeners/parameters.
@Bean
Job importJob(JobRepository repo, Step load, Step report) {
return new JobBuilder("importJob", repo)
.start(load)
.next(report) // sequential steps
.listener(new MyJobListener())
.build();
}
@Bean
Step load(JobRepository repo, PlatformTransactionManager tx) {
return new StepBuilder("load", repo)
.chunk(500, tx).reader(r()).processor(p()).writer(w()).build();
}
The crucial 2026 correction: the source's JobBuilderFactory/StepBuilderFactory were removed in Spring Batch 5 (Boot 3). You now instantiate JobBuilder/StepBuilder directly, passing the JobRepository (and, for steps, a PlatformTransactionManager) — both are auto-configured beans you just inject.
Other points interviewers like: jobs are run by a JobLauncher with JobParameters (parameters identify a JobInstance, enabling restart and preventing duplicate runs); you can build conditional flows (.on("FAILED").to(...)) and parallel/split flows, not just linear next() chains. @EnableBatchProcessing is now optional under Boot.
Follow-up 1
What is a Step in Spring Batch?
In Spring Batch, a Step is a self-contained unit of work within a Job. It represents a single phase of a Job, such as reading data, processing data, or writing data. Each Step consists of a reader, a processor, and a writer. The reader is responsible for reading data from a data source, the processor is responsible for processing the data, and the writer is responsible for writing the processed data to a destination. The configuration of a Step in Spring Batch is done using the StepBuilderFactory class. The StepBuilderFactory is used to create a StepBuilder, which is then used to configure the Step. The StepBuilder allows you to specify the name, listener, and other properties of the Step. You can also add a reader, processor, and writer to the Step using the StepBuilder's reader, processor, and writer methods.
Follow-up 2
How can you define multiple steps in a Job?
To define multiple steps in a Job in Spring Batch, you can use the JobBuilder's flow or next methods. The flow method allows you to specify a Step or a Flow as the next step in the Job. The next method allows you to specify a Step as the next step in the Job. You can chain multiple flow or next methods to define the sequence of steps in the Job. For example:
@Bean
public Job myJob(JobBuilderFactory jobBuilderFactory, Step step1, Step step2) {
return jobBuilderFactory.get("myJob")
.flow(step1)
.next(step2)
.end()
.build();
}
Follow-up 3
What is the role of JobLauncher in Spring Batch?
In Spring Batch, the JobLauncher is responsible for launching a Job and executing its steps. It is the entry point for starting a Job. The JobLauncher is used to run a Job instance by providing the Job and any required JobParameters. The JobParameters can be used to provide input parameters to the Job, such as file paths or other configuration values. The JobLauncher executes the Job by invoking its steps in the specified order. The JobLauncher can be configured with different implementations, such as a SimpleJobLauncher or a AsyncJobLauncher, depending on the requirements of the application.
Follow-up 4
How can you handle errors in a Job?
In Spring Batch, you can handle errors in a Job by using the built-in error handling mechanisms provided by the framework. One way to handle errors is by using the SkipPolicy interface. The SkipPolicy allows you to define rules for skipping certain exceptions during the execution of a Step. You can implement the SkipPolicy interface and override its shouldSkip method to define the conditions for skipping exceptions. Another way to handle errors is by using the RetryPolicy interface. The RetryPolicy allows you to define rules for retrying failed operations during the execution of a Step. You can implement the RetryPolicy interface and override its canRetry and registerThrowable methods to define the conditions for retrying operations and handling exceptions. Additionally, you can also use the ItemListenerSupport and ChunkListenerSupport interfaces to handle errors at the item and chunk level, respectively. These interfaces provide callback methods that can be implemented to perform custom error handling logic.
3. What is chunk-oriented processing in Spring Batch?
Chunk-oriented processing is Spring Batch's primary step model: instead of loading everything at once, a step reads items one at a time, processes them, accumulates them into a chunk of size N, then writes the whole chunk in a single transaction — and repeats until the input is exhausted.
loop:
read N items (one-by-one via ItemReader)
process each (ItemProcessor)
write the chunk of N (ItemWriter) ← one transaction commits here
.chunk(1000, txManager)
.reader(reader()).processor(processor()).writer(writer())
Why it matters (the points interviewers want):
- Memory efficiency — only a chunk (e.g. 1,000 rows) is in memory at a time, so you process millions of records safely.
- Transactional integrity & restartability — one commit per chunk; if chunk #501 fails, prior chunks are already committed and the job can restart from that point (state tracked in the
JobRepository). - Performance tuning — the chunk/commit interval is a key knob: too small means many commits (slow); too large means big transactions and memory/rollback cost.
- Fault tolerance — integrates with skip/retry policies per item.
The contrast to mention: chunk-oriented steps suit item-based bulk data, whereas a tasklet step is for a single non-item task (run a script, delete a file). Choosing the right commit interval and skip/retry policy is the practical follow-up.
Follow-up 1
How can you configure chunk size in Spring Batch?
In Spring Batch, you can configure the chunk size by setting the chunk attribute on the step element in the job configuration XML file. For example, sets the chunk size to 10.
Follow-up 2
What is the difference between chunk and tasklet?
In Spring Batch, a chunk is a type of step that reads, processes, and writes data in chunks. It is suitable for processing large datasets. On the other hand, a tasklet is a type of step that performs a single task or a series of tasks. It is suitable for processing small or simple tasks.
Follow-up 3
How does Spring Batch handle transaction management in chunk processing?
In Spring Batch, transaction management in chunk processing is handled by the framework itself. By default, each chunk is processed within a single transaction. If any exception occurs during the processing of a chunk, the transaction is rolled back, and the chunk is retried. This ensures data integrity and consistency.
Follow-up 4
Can you explain how commit interval works in Spring Batch?
In Spring Batch, the commit interval determines how often the transaction is committed during chunk processing. It is set using the commit-interval attribute on the chunk element in the job configuration XML file. For example, `` commits the transaction after processing every 10 items in the chunk.
4. How does Spring Batch handle errors and retries?
Spring Batch has built-in fault tolerance you enable on a step with .faultTolerant(), combining three mechanisms:
- Retry — for transient failures (e.g. a deadlock or flaky network call), re-attempt the item up to a limit, optionally with a backoff policy. Configure with
.retryLimit(n).retry(SomeException.class). - Skip — for bad records you don't want to abort the whole job over, skip the offending item and continue. Configure with
.skipLimit(n).skip(ParseException.class); once the skip limit is exceeded, the step fails. - Restart — because execution state is persisted in the
JobRepository, a job that fails can be restarted and resume from the failed chunk, not from the beginning.
new StepBuilder("step", repo).chunk(100, tx)
.reader(r()).processor(p()).writer(w())
.faultTolerant()
.retryLimit(3).retry(TransientException.class)
.skipLimit(50).skip(FlatFileParseException.class)
.listener(new SkipLoggingListener())
.build();
Points interviewers reward: use retry for transient/recoverable errors and skip for permanent/data errors — applying them to the wrong category is a common mistake (don't retry a malformed record forever). Add SkipListener/RetryListener to log/audit skipped or retried items, and remember the rollback semantics: on a chunk failure, Batch may reprocess the chunk item-by-item to isolate the bad one. Tune skipLimit/retryLimit so a flood of errors still fails the job loudly rather than silently dropping data.
Follow-up 1
What is Skip Limit in Spring Batch?
Skip Limit in Spring Batch is a configuration property that defines the maximum number of items that can be skipped before the job fails. When an item fails and the skip count exceeds the skip limit, the job will be marked as failed. Skip Limit can be set globally for the entire job or can be specified at the step level.
Follow-up 2
How can you implement a custom Skip Policy?
To implement a custom Skip Policy in Spring Batch, you need to create a class that implements the SkipPolicy interface. This interface has a single method called shouldSkip(), which determines whether an item should be skipped or not. Inside this method, you can write custom logic to decide when to skip an item based on its exception or any other criteria. Once the custom Skip Policy is implemented, it can be configured in the job or step configuration.
Follow-up 3
What is the role of RetryTemplate in Spring Batch?
RetryTemplate is a key component in Spring Batch for handling retries. It provides a way to define the retry logic and behavior. RetryTemplate allows you to configure the maximum number of retries, the backoff policy, and the exception types to retry. It also provides hooks for customizing the retry behavior, such as adding a RetryListener to perform actions before and after each retry attempt. RetryTemplate is used by default in Spring Batch to retry failed items, but it can also be used in custom code to handle retries.
Follow-up 4
Can you explain how Backoff Policy works in Spring Batch?
Backoff Policy in Spring Batch is used to control the delay between retry attempts. It defines how long to wait before the next retry after a failed attempt. Spring Batch provides several built-in backoff policies, such as FixedBackOffPolicy, ExponentialBackOffPolicy, and UniformRandomBackOffPolicy. FixedBackOffPolicy simply waits for a fixed amount of time between retries. ExponentialBackOffPolicy increases the delay exponentially with each retry. UniformRandomBackOffPolicy introduces a random delay within a specified range. Backoff Policy can be configured in the RetryTemplate to control the retry behavior.
5. How can you schedule Jobs in Spring Batch?
Spring Batch itself doesn't schedule jobs — a Job is launched by a JobLauncher, and you trigger that launch from a scheduler. The common options:
- Spring's
@Scheduled— the simplest in-process approach: a scheduled method launches the job viaJobLauncherwith freshJobParameters.
@Scheduled(cron = "0 0 2 * * *") // 02:00 daily
public void run() throws Exception {
jobLauncher.run(importJob,
new JobParametersBuilder()
.addLong("run.id", System.currentTimeMillis()) // unique → new JobInstance
.toJobParameters());
}
- Quartz — for richer scheduling (persistent, clustered, misfire handling); a
QuartzJobBeanlaunches the Batch job. - External schedulers — cron, your CI/CD, or a Kubernetes CronJob running the app as a task (often the cleanest for containerized batch).
- Event-driven — trigger via Spring Integration (
JobLaunchingGateway) when a file/message arrives, instead of a fixed time.
The gotchas interviewers want: a JobInstance is identified by job name + JobParameters, so to run "the same" job again you must pass unique parameters (e.g. a timestamp/run id) — otherwise Batch treats it as a completed instance and won't rerun it. For multi-instance deployments, ensure only one node launches a given job (Quartz clustering, a leader/lock, or a single CronJob) to avoid duplicate runs. (Note: "QuartzJobScheduler"/"TaskScheduler" aren't Batch-specific scheduler classes — scheduling is done by @Scheduled, Quartz, or an external trigger.)
Follow-up 1
What is the role of JobScheduler in Spring Batch?
The JobScheduler in Spring Batch is responsible for triggering the execution of Jobs based on a specified schedule. It allows you to define when and how often a Job should be executed. The JobScheduler can be configured to use different scheduling mechanisms, such as cron expressions or fixed intervals. It ensures that Jobs are executed automatically according to the defined schedule.
Follow-up 2
How can you use Cron expressions to schedule Jobs?
Cron expressions are commonly used in Spring Batch to schedule Jobs. A cron expression is a string that represents a schedule based on time. It consists of six fields that define different aspects of the schedule, such as the minute, hour, day of the month, month, day of the week, and year. You can configure the JobScheduler in Spring Batch to use a cron expression to define the schedule for executing Jobs. For example, you can use the following cron expression to schedule a Job to run every day at 8:00 AM: 0 0 8 * * ?.
Follow-up 3
Can you explain how JobParameters work in Spring Batch?
In Spring Batch, JobParameters are used to provide input parameters to a Job at runtime. JobParameters can be used to pass dynamic values to a Job, such as file paths, dates, or any other information required for the Job execution. JobParameters can be defined and configured when launching a Job, and they can be accessed within the Job using the @Value annotation or the JobParameter class. By using JobParameters, you can make your Jobs more flexible and reusable.
Follow-up 4
How can you prevent a Job from running concurrently?
To prevent a Job from running concurrently in Spring Batch, you can configure the JobLauncher to use a JobRepository with a specific isolation level. The isolation level determines how concurrent access to the JobRepository is handled. By setting the isolation level to ISOLATION_SERIALIZABLE, you can ensure that only one instance of a Job can be executed at a time. This prevents multiple instances of the same Job from running concurrently and ensures data integrity during Job execution.
Live mock interview
Mock interview: Spring Batch Processing
- Read your scene and goals
- Talk it out; goals tick off live
- Get a score and stronger lines
Your voice and your AI key never touch our servers; the key stays in this browser and is sent only to Google. Only your round scores are saved to track progress.