Skip to content

Spring Batch Job and Step Fundamentals

Interactive Diagram

새 탭 ↗

Spring Batch is not merely a library for processing many records at once. It is an execution framework that records a batch run and makes a restart possible. In an Integration platform, the important result is not only that “the job finished,” but also which Job and Step ran, how many items were read and written, and how many were skipped.

A Job is the top-level unit representing one batch execution. The actual work is divided into one or more Step instances, each with its own transaction and execution status.

Spring Batch hierarchy in which one job holds ordered steps and each step uses an ItemReader, ItemProcessor and ItemWriter Source: Spring Batch docs, The Domain Language of Batch, Spring Batch authors, Apache-2.0

PlantUML Diagram

Jobs and Steps are usually declared as @Bean factory methods in a configuration class. A single Step ties together the Reader, Processor, and Writer along with the chunk size and fault-tolerance policy.

@Bean
public Job interfaceJob(JobRepository jobRepository,
Step insertLogStep,
Step upsertStep,
Step updateLogStep) {
return new JobBuilder("interfaceJob", jobRepository)
.start(insertLogStep)
.next(upsertStep)
.next(updateLogStep)
.listener(traceJobExecutionListener)
.build();
}
@Bean
public Step upsertStep(JobRepository jobRepository,
PlatformTransactionManager transactionManager,
ItemReader<SourceRow> reader,
ItemProcessor<SourceRow, TargetRow> processor,
ItemWriter<TargetRow> writer) {
return new StepBuilder("upsertStep", jobRepository)
.<SourceRow, TargetRow>chunk(500, transactionManager)
.reader(reader)
.processor(processor)
.writer(writer)
.faultTolerant()
.skipLimit(50)
.skip(DataIntegrityViolationException.class)
.noSkip(SourceUnavailableException.class)
.build();
}

chunk(500, transactionManager) means a commit every 500 items, not that 500 items are loaded into memory before reading begins. skipLimit(50) is the total number of skips allowed across the whole Step; exceeding it marks the Step FAILED. Exceptions listed under noSkip are excluded from skipping and fail the Step immediately.

JobRepository persists execution state in three layers.

TableMeaningWhen a row appears
BATCH_JOB_INSTANCEThe logical execution keyed by Job name plus identifying parametersOnce, the first time that parameter combination runs
BATCH_JOB_EXECUTIONAn actual attempt at that InstanceOn every run, including every restart
BATCH_STEP_EXECUTIONA per-Step attempt with read/write/skip countsEach time a Step runs

BATCH_JOB_EXECUTION_PARAMS stores an IDENTIFYING flag per parameter. Identifying parameters are what identify the JobInstance, so re-running with the same values raises JobInstanceAlreadyCompleteException. Non-identifying parameters take no part in Instance identity, so they can change between runs while still resolving to the same Instance.

JobParameters params = new JobParametersBuilder()
.addString("ifId", ifId) // identifying: the logical Interface run
.addLocalDate("businessDate", businessDate) // identifying: the target business date
.addString("requestedBy", operator, false) // non-identifying: restart keeps the Instance
.addLong("retryHint", attempt, false) // non-identifying
.toJobParameters();

A common production mistake is making RunIdIncrementer or a timestamp an identifying parameter, which mints a fresh Instance on every run. Duplicate execution is then never blocked and restart becomes effectively unusable. If duplicate prevention and restart matter, the identifying parameters must be business-meaningful keys such as Interface ID and business date.

ExecutionContext is serialized into BATCH_JOB_EXECUTION_CONTEXT and BATCH_STEP_EXECUTION_CONTEXT. A Reader that implements ItemStream records its current position in update(ExecutionContext) and restores it in open(ExecutionContext) on restart. That is exactly why JdbcCursorItemReader or JpaPagingItemReader can skip already-processed ranges when a Job resumes. A hand-written Reader that does not implement ItemStream will always re-read from the beginning on restart.

A short, one-time operation is represented by a Tasklet. Recording a start log or calculating a final count are typical Tasklet steps.

Large data sets are better handled with a Chunk.

read item × chunkSize
│
▼
process items
│
▼
write chunk
│
▼
commit transaction

A Chunk becomes a commit unit, so the entire data set does not have to be loaded into memory. A Reader can read from a source cursor while a Writer performs a batch write to the target database. Recording readCount, writeCount, filterCount, and skipCount on StepExecution makes partial success observable.

An Integration Batch commonly separates its work into three types of Step.

  1. insertLogStep records the Interface start and the source watermark or reference time.
  2. upsertItemReaderWriterStep reads from the source and performs chunk-based upserts into the target.
  3. updateLogStep records the final status and processed counts.

The Job receives an ifId from identifying parameters or the execution environment and connects it to runtime configuration. A common JobExecutionListener can emit START, COMPLETED, and FAILED Trace events. API requests and Batch executions can then be searched through the same Trace model.

A @JobScope bean can read the execution context at Job execution time. A @StepScope bean reads parameters and context at Step execution time. If this distinction is ignored and Interface configuration is loaded at application startup, values can leak between different Jobs executed by the same process.

Transactions are usually separated as follows.

AreaResponsibilityFailure meaning
Batch metadata transactionStore Job and Step stateExecution history cannot be recorded
Source readSource cursor or queryRead failure; restart position must be checked
Target write ChunkBatch write to the target DBRoll back the Chunk or apply skip policy
Trace loggingStart, end, and error eventsAn observability path separated from business work

When source and target are different databases, do not assume one global transaction. After a target write has committed, a restart requires an idempotency key and duplicate-prevention policy.

The same boundaries apply when using MyBatis adapters. MyBatisCursorItemReader is useful for streaming queries, but it can open its cursor on a connection separate from the batch Step transaction. Do not assume that rolling back a target chunk automatically rewinds the source cursor. Verify the Reader’s ItemStream checkpoint together with driver cursor and fetch-size behavior in a restart test. A long cursor transaction also occupies a source connection and snapshot, so bound both timeout and chunk processing time.

MyBatisBatchItemWriter groups items into batch statements, but it does not make source and target one transaction. Verify that its SqlSessionTemplate participates in the Step transaction manager for the same DataSource if target writes must roll back with the chunk. Separate databases or transaction managers can partially commit; make target keys idempotent and validate the assertUpdates policy and the business meaning of a zero update count.

Restart and Retry sound similar but address different layers of failure.

Restart re-runs a failed JobExecution as a new JobExecution under the same JobInstance. It resumes from the Step that failed, not from the step after it. Steps that already ended COMPLETED are skipped rather than re-executed. If a Step must always run again (recomputing a reference timestamp, for example), mark it allowStartIfComplete(true) so it executes even in the COMPLETED state.

@Bean
public Step insertLogStep(JobRepository jobRepository,
PlatformTransactionManager transactionManager) {
return new StepBuilder("insertLogStep", jobRepository)
.tasklet(insertLogTasklet, transactionManager)
.allowStartIfComplete(true) // always re-run on restart
.startLimit(3) // maximum attempts for this Step
.build();
}

Retry is the policy for re-attempting a transient exception raised during chunk processing, and it is widely misunderstood. The failed chunk is not retried inside the same transaction. Adding faultTolerant() installs FaultTolerantChunkProcessor: when a retryable exception occurs, the chunk transaction is rolled back first. Spring Batch then replays the same items one at a time (effectively chunk size 1) each in a new transaction. Only that way can it identify which item is problematic, exhaust its retry limit, or classify it as a skip.

@Bean
public Step upsertStepWithRetry(JobRepository jobRepository,
PlatformTransactionManager transactionManager,
ItemReader<SourceRow> reader,
ItemProcessor<SourceRow, TargetRow> processor,
ItemWriter<TargetRow> writer) {
return new StepBuilder("upsertStep", jobRepository)
.<SourceRow, TargetRow>chunk(500, transactionManager)
.reader(reader)
.processor(processor)
.writer(writer)
.faultTolerant()
.retryLimit(3)
.retry(TransientDataAccessException.class)
.retry(SocketTimeoutException.class)
.noRetry(DataIntegrityViolationException.class)
.skipLimit(50)
.skip(DataIntegrityViolationException.class)
.backOffPolicy(exponentialBackOff())
.build();
}

Because of this rollback-and-replay model, the Reader and Processor of a retryable Step must be free of side effects. If a Processor calls an external API or writes to a side table, that effect happens again when the rolled-back items are reprocessed. The batch metadata and target-write transactions roll back; the external call does not. Move effectful logic into the Writer, and even there guard it with an idempotency key.

Stateful Readers deserve the same caution. A Reader that does not implement ItemStream cannot rewind its position after a rollback, so items can be lost or processed twice.

  • Network timeouts and transient lock contention are reasonable bounded-retry candidates.
  • Schema and business-rule errors are not fixed by retrying; mark them noRetry and skip or quarantine them.
  • A write with an external side effect must not be automatically retried without an idempotency key.
  • On restart, verify both the source watermark and the target duplicate-prevention rule.
  • When retry and skip are combined, an item moves to skip evaluation only after its retry limit is exhausted. Observe both limits separately.

At minimum, collect these values for both Job and Step.

  • JobInstance ID / JobExecution ID
  • Start/end timestamps and final ExitStatus
  • Read / write / filter / skip counts
  • Retry and rollback counts
  • Source watermark and processing range
  • Trace guid, uuid, hop, and interfaceId

A Batch can be technically successful while its readCount and writeCount are unexpected. Technical status and business outcome should be recorded as separate fields.

Spring Batch is built around Job and Step. Tasklet is suited to small operations, while Chunk processing is suited to large data sets. JobRepository records execution state, and a Listener connects the lifecycle to Trace events. This lets an Integration platform operate API, message, and Batch workloads with one execution-history and error model.