Spring Batch: chunk processing that survives failures

Spring Batch processes large amounts of data in chunks: read some items, process them, write them, commit, repeat. It records progress in a job repository, so a job that fails halfway can restart where it stopped. This page runs a CSV import with Spring Batch 6 and Spring Boot 4, then a failure and restart, skip and retry, and a partitioned step on several threads.

Contents

How Spring Batch structures work

A batch job is work without a user waiting: import a file every night, recalculate prices, send a million statements. The hard parts are not the reading and writing; they are what happens when something fails after an hour. Spring Batch answers with a fixed structure:

  • Job: the whole piece of work, made of one or more steps run in order or by a flow.
  • Step: one phase. Most steps are chunk-oriented: an ItemReader reads items one by one, an optional ItemProcessor transforms or filters each, and an ItemWriter writes a whole chunk at once. Each chunk is one transaction.
  • Job repository: tables (BATCH_JOB_INSTANCE, BATCH_JOB_EXECUTION, BATCH_STEP_EXECUTION and others) where Spring Batch records every run, with counts and the position each reader had reached at the last commit.
  • Job parameters: the values that identify one run, such as the file name or the date. A job plus its identifying parameters is a job instance; each attempt to run it is an execution.

Chunks are the key idea. Committing every item is slow; committing once at the end means a failure loses everything. With a chunk size of 100, a failure loses at most one chunk, and a restart continues from the last committed chunk.

What changed in Spring Batch 6 (Spring Boot 4)
AreaSpring Batch 6Spring Batch 5 (Spring Boot 3)
Chunk stepschunk(size) returns the new ChunkOrientedStepBuilderchunk(size, transactionManager) on SimpleStepBuilder
Running jobsJobOperator, which now extends JobLauncherJobLauncher
Packagesorg.springframework.batch.core.job.Job, ...core.step.Step, readers and writers under org.springframework.batch.infrastructure.itemorg.springframework.batch.core.Job, org.springframework.batch.item
RetrySpring Framework 7's RetryPolicySpring Retry
Default job repositoryResourcelessJobRepository, no database; JDBC with @EnableJdbcJobRepositoryJDBC, needing a database

Spring Boot 4 has two starters: spring-boot-starter-batch and spring-boot-starter-batch-jdbc. The examples use the JDBC one, which stores the job repository in the application's database and creates its tables automatically for embedded databases (spring.batch.jdbc.initialize-schema=embedded). They run against H2 and set spring.batch.job.enabled=false, so that Spring Boot does not run the job at startup and main can start it with JobOperator.

A first job: CSV to database

Seven customers in a CSV file, two of them without an email, are imported with a chunk size of 3. The processor drops customers without an email and lower-cases the rest, and a listener prints each chunk as it is written:

Text
id,name,email
1,Ann,ann@example.com
2,Bob,BOB@EXAMPLE.COM
3,Cara,
4,Dan,dan@example.com
5,Eve,eve@example.com
6,Finn,
7,Gus,gus@example.com
Java
package batch.first;

import java.util.Locale;
import java.util.Map;
import javax.sql.DataSource;
import org.springframework.batch.core.job.Job;
import org.springframework.batch.core.job.JobExecution;
import org.springframework.batch.core.job.builder.JobBuilder;
import org.springframework.batch.core.job.parameters.JobParametersBuilder;
import org.springframework.batch.core.launch.JobOperator;
import org.springframework.batch.core.listener.ItemWriteListener;
import org.springframework.batch.core.repository.JobRepository;
import org.springframework.batch.core.step.Step;
import org.springframework.batch.core.step.StepExecution;
import org.springframework.batch.core.step.builder.StepBuilder;
import org.springframework.batch.infrastructure.item.Chunk;
import org.springframework.batch.infrastructure.item.ItemProcessor;
import org.springframework.batch.infrastructure.item.database.JdbcBatchItemWriter;
import org.springframework.batch.infrastructure.item.database.builder.JdbcBatchItemWriterBuilder;
import org.springframework.batch.infrastructure.item.file.FlatFileItemReader;
import org.springframework.batch.infrastructure.item.file.builder.FlatFileItemReaderBuilder;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.ClassPathResource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.transaction.PlatformTransactionManager;

@SpringBootApplication
public class FirstJob {

    record Customer(int id, String name, String email) {
    }

    @Bean
    FlatFileItemReader<Customer> reader() {
        return new FlatFileItemReaderBuilder<Customer>()
                .name("customerReader")
                .resource(new ClassPathResource("batch/customers.csv"))
                .linesToSkip(1)
                .delimited().names("id", "name", "email")
                .targetType(Customer.class)
                .build();
    }

    @Bean
    ItemProcessor<Customer, Customer> processor() {
        return customer -> customer.email().isBlank()
                ? null
                : new Customer(customer.id(), customer.name(),
                        customer.email().toLowerCase(Locale.ROOT));
    }

    @Bean
    JdbcBatchItemWriter<Customer> writer(DataSource dataSource) {
        return new JdbcBatchItemWriterBuilder<Customer>()
                .dataSource(dataSource)
                .sql("INSERT INTO customer (id, name, email) VALUES (:id, :name, :email)")
                .beanMapped()
                .build();
    }

    @Bean
    Step importStep(JobRepository jobRepository, PlatformTransactionManager tx,
            FlatFileItemReader<Customer> reader, ItemProcessor<Customer, Customer> processor,
            JdbcBatchItemWriter<Customer> writer) {
        return new StepBuilder("importCustomers", jobRepository)
                .<Customer, Customer>chunk(3)
                .transactionManager(tx)
                .reader(reader)
                .processor(processor)
                .writer(writer)
                .listener(new ItemWriteListener<Customer>() {
                    @Override
                    public void afterWrite(Chunk<? extends Customer> items) {
                        System.out.println("  chunk written: " + items.getItems().stream()
                                .map(Customer::name).toList());
                    }
                })
                .build();
    }

    @Bean
    Job importJob(JobRepository jobRepository, Step importStep) {
        return new JobBuilder("importJob", jobRepository).start(importStep).build();
    }

    public static void main(String[] args) throws Exception {
        SpringApplication app = new SpringApplication(FirstJob.class);
        app.setDefaultProperties(Map.of(
                "spring.main.banner-mode", "off",
                "logging.level.root", "WARN",
                "spring.batch.job.enabled", "false"));
        try (var context = app.run(args)) {
            JdbcTemplate jdbc = context.getBean(JdbcTemplate.class);
            jdbc.execute("CREATE TABLE customer (id INT PRIMARY KEY, name VARCHAR(20),"
                    + " email VARCHAR(50))");
            JobExecution execution = context.getBean(JobOperator.class).start(
                    context.getBean(Job.class),
                    new JobParametersBuilder().addString("file", "customers.csv")
                            .toJobParameters());
            System.out.println("Job status: " + execution.getStatus());
            for (StepExecution step : execution.getStepExecutions()) {
                System.out.println("Step " + step.getStepName() + ": read "
                        + step.getReadCount() + ", filtered " + step.getFilterCount()
                        + ", written " + step.getWriteCount() + ", commits "
                        + step.getCommitCount());
            }
            System.out.println("Table: " + jdbc.queryForList(
                    "SELECT email FROM customer ORDER BY id", String.class));
        }
    }
}
Output
chunk written: [Ann, Bob]
  chunk written: [Dan, Eve]
  chunk written: [Gus]
Job status: COMPLETED
Step importCustomers: read 7, filtered 2, written 5, commits 3
Table: [ann@example.com, bob@example.com, dan@example.com, eve@example.com, gus@example.com]
  • The step read 7 items in three chunks of up to 3. The first chunk read Ann, Bob and Cara; the processor returned null for Cara, which means "filter this item out", so only Ann and Bob were written.
  • The second chunk read Dan, Eve and Finn and wrote Dan and Eve. The last chunk held only Gus, because the file ended.
  • The counts add up: 7 read, 2 filtered, 5 written, in 3 commits, one per chunk. Bob's email was stored in lower case.

FlatFileItemReader mapped each line to the Customer record by column name with targetType, and JdbcBatchItemWriter sent each chunk as one JDBC batch, with named parameters taken from the record's components by beanMapped(). The reader has a name because it saves its position in the step's execution context under that name; the next section depends on it.

Failure and restart

The writer of this job fails on the chunk that contains Eve the first time, as if a disk filled up. The job is then started again with the same parameters, and a third time after it has completed:

Java
package batch.restart;

import java.util.Map;
import javax.sql.DataSource;
import org.springframework.batch.core.job.Job;
import org.springframework.batch.core.job.JobExecution;
import org.springframework.batch.core.job.builder.JobBuilder;
import org.springframework.batch.core.job.parameters.JobParameters;
import org.springframework.batch.core.job.parameters.JobParametersBuilder;
import org.springframework.batch.core.launch.JobOperator;
import org.springframework.batch.core.repository.JobRepository;
import org.springframework.batch.core.step.Step;
import org.springframework.batch.core.step.StepExecution;
import org.springframework.batch.core.step.builder.StepBuilder;
import org.springframework.batch.infrastructure.item.ItemWriter;
import org.springframework.batch.infrastructure.item.database.JdbcBatchItemWriter;
import org.springframework.batch.infrastructure.item.database.builder.JdbcBatchItemWriterBuilder;
import org.springframework.batch.infrastructure.item.file.FlatFileItemReader;
import org.springframework.batch.infrastructure.item.file.builder.FlatFileItemReaderBuilder;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.ClassPathResource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.transaction.PlatformTransactionManager;

@SpringBootApplication
public class RestartJob {

    record Customer(int id, String name, String email) {
    }

    static boolean failOnEve = true;

    @Bean
    FlatFileItemReader<Customer> reader() {
        return new FlatFileItemReaderBuilder<Customer>()
                .name("customerReader")
                .resource(new ClassPathResource("batch/customers.csv"))
                .linesToSkip(1)
                .delimited().names("id", "name", "email")
                .targetType(Customer.class)
                .build();
    }

    @Bean
    Step importStep(JobRepository jobRepository, PlatformTransactionManager tx,
            FlatFileItemReader<Customer> reader, DataSource dataSource) {
        JdbcBatchItemWriter<Customer> insert = new JdbcBatchItemWriterBuilder<Customer>()
                .dataSource(dataSource)
                .sql("INSERT INTO customer (id, name) VALUES (:id, :name)")
                .beanMapped()
                .build();
        insert.afterPropertiesSet();
        ItemWriter<Customer> writer = chunk -> {
            System.out.println("  writing " + chunk.getItems().stream()
                    .map(Customer::name).toList());
            insert.write(chunk);
            if (failOnEve && chunk.getItems().stream().anyMatch(c -> c.name().equals("Eve"))) {
                throw new IllegalStateException("disk full while writing Eve's chunk");
            }
        };
        return new StepBuilder("importCustomers", jobRepository)
                .<Customer, Customer>chunk(3)
                .transactionManager(tx)
                .reader(reader)
                .writer(writer)
                .build();
    }

    @Bean
    Job importJob(JobRepository jobRepository, Step importStep) {
        return new JobBuilder("importJob", jobRepository).start(importStep).build();
    }

    public static void main(String[] args) throws Exception {
        SpringApplication app = new SpringApplication(RestartJob.class);
        app.setDefaultProperties(Map.of(
                "spring.main.banner-mode", "off",
                "logging.level.root", "OFF",
                "spring.batch.job.enabled", "false"));
        try (var context = app.run(args)) {
            JdbcTemplate jdbc = context.getBean(JdbcTemplate.class);
            jdbc.execute("CREATE TABLE customer (id INT PRIMARY KEY, name VARCHAR(20))");
            JobOperator operator = context.getBean(JobOperator.class);
            Job job = context.getBean(Job.class);
            JobParameters params = new JobParametersBuilder()
                    .addString("file", "customers.csv").toJobParameters();

            System.out.println("Run 1");
            report(operator.start(job, params), jdbc);

            failOnEve = false;
            System.out.println("Run 2, same parameters");
            report(operator.start(job, params), jdbc);

            System.out.println("Run 3, same parameters");
            try {
                operator.start(job, params);
            } catch (Exception e) {
                System.out.println("  " + e.getClass().getSimpleName() + ": "
                        + e.getMessage());
            }
            System.out.println("Job instances: " + jdbc.queryForObject(
                    "SELECT COUNT(*) FROM BATCH_JOB_INSTANCE", Integer.class)
                    + ", executions: " + jdbc.queryForList(
                    "SELECT STATUS FROM BATCH_JOB_EXECUTION ORDER BY JOB_EXECUTION_ID",
                    String.class));
        }
    }

    static void report(JobExecution execution, JdbcTemplate jdbc) {
        StepExecution step = execution.getStepExecutions().iterator().next();
        System.out.println("  status " + execution.getStatus() + ", read "
                + step.getReadCount() + ", written " + step.getWriteCount()
                + ", commits " + step.getCommitCount() + ", rollbacks "
                + step.getRollbackCount());
        System.out.println("  table: " + jdbc.queryForList(
                "SELECT name FROM customer ORDER BY id", String.class));
    }
}
Output
Run 1
  writing [Ann, Bob, Cara]
  writing [Dan, Eve, Finn]
  status FAILED, read 6, written 3, commits 1, rollbacks 1
  table: [Ann, Bob, Cara]
Run 2, same parameters
  writing [Dan, Eve, Finn]
  writing [Gus]
  status COMPLETED, read 4, written 4, commits 2, rollbacks 0
  table: [Ann, Bob, Cara, Dan, Eve, Finn, Gus]
Run 3, same parameters
  JobInstanceAlreadyCompleteException: A job instance already exists and is complete for identifying parameters={JobParameter{name='file', value=customers.csv, type=class java.lang.String, identifying=true}}.  If you want to run this job again, change the parameters.
Job instances: 1, executions: [FAILED, COMPLETED]
  • Run 1 committed the first chunk (Ann, Bob, Cara), then failed on the second. That chunk's transaction rolled back, so Dan, Eve and Finn are not in the table even though their insert ran before the exception. The job ended FAILED with 1 commit and 1 rollback.
  • Run 2 used the same parameters, so it was the same job instance, and Spring Batch restarted it. The reader resumed after the last committed position, at Dan, and read only 4 lines. Nothing was imported twice.
  • Run 3 was refused with JobInstanceAlreadyCompleteException: a completed instance never runs again. The job repository holds one instance with two executions, FAILED then COMPLETED.

To run a job again with new data, give it new identifying parameters, such as the date or file name. RunIdIncrementer with JobOperator.startNextInstance adds an increasing run.id for jobs that have no natural parameter. Restart needs a job repository that persists state: with the resourceless repository, every run starts from the beginning.

Skip and retry

Some failures concern one bad item, and the job should continue without it. Others are temporary, and trying again will work. This file has a line whose id is not a number, and the writer, which stands in for a mail server, is busy for the first attempts at one chunk:

Text
id,name,email
1,Ann,ann@example.com
two,Bob,bob@example.com
3,Cara,cara@example.com
4,Dan,dan@example.com
5,Eve,eve@example.com
Java
package batch.fault;

import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import org.springframework.batch.core.job.Job;
import org.springframework.batch.core.job.JobExecution;
import org.springframework.batch.core.job.builder.JobBuilder;
import org.springframework.batch.core.job.parameters.JobParameters;
import org.springframework.batch.core.launch.JobOperator;
import org.springframework.batch.core.listener.SkipListener;
import org.springframework.batch.core.repository.JobRepository;
import org.springframework.batch.core.step.Step;
import org.springframework.batch.core.step.StepExecution;
import org.springframework.batch.core.step.builder.StepBuilder;
import org.springframework.batch.infrastructure.item.ItemWriter;
import org.springframework.batch.infrastructure.item.file.FlatFileItemReader;
import org.springframework.batch.infrastructure.item.file.FlatFileParseException;
import org.springframework.batch.infrastructure.item.file.builder.FlatFileItemReaderBuilder;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.retry.RetryPolicy;
import org.springframework.transaction.PlatformTransactionManager;

@SpringBootApplication
public class SkipAndRetry {

    record Customer(int id, String name, String email) {
    }

    static class MailServerBusyException extends RuntimeException {
        MailServerBusyException() {
            super("mail server busy");
        }
    }

    static final List<String> SENT = new ArrayList<>();
    static final AtomicInteger ATTEMPTS = new AtomicInteger();

    @Bean
    FlatFileItemReader<Customer> reader() {
        return new FlatFileItemReaderBuilder<Customer>()
                .name("customerReader")
                .resource(new ClassPathResource("batch/messy.csv"))
                .linesToSkip(1)
                .delimited().names("id", "name", "email")
                .targetType(Customer.class)
                .build();
    }

    @Bean
    Step mailStep(JobRepository jobRepository, PlatformTransactionManager tx,
            FlatFileItemReader<Customer> reader) {
        ItemWriter<Customer> mailer = chunk -> {
            int attempt = ATTEMPTS.incrementAndGet();
            List<String> names = chunk.getItems().stream().map(Customer::name).toList();
            if (names.contains("Dan") && attempt <= 3) {
                System.out.println("  attempt " + attempt + " for " + names + ": busy");
                throw new MailServerBusyException();
            }
            System.out.println("  attempt " + attempt + " for " + names + ": sent");
            SENT.addAll(names);
        };
        RetryPolicy retry = RetryPolicy.builder()
                .includes(MailServerBusyException.class)
                .maxRetries(3)
                .delay(Duration.ofMillis(10))
                .build();
        return new StepBuilder("mailCustomers", jobRepository)
                .<Customer, Customer>chunk(2)
                .transactionManager(tx)
                .reader(reader)
                .writer(mailer)
                .faultTolerant()
                .skip(FlatFileParseException.class)
                .skipLimit(5)
                .skipListener(new SkipListener<Customer, Customer>() {
                    @Override
                    public void onSkipInRead(Throwable t) {
                        FlatFileParseException e = (FlatFileParseException) t;
                        System.out.println("  skipped line " + e.getLineNumber() + ": "
                                + e.getInput());
                    }
                })
                .retryPolicy(retry)
                .build();
    }

    @Bean
    Job mailJob(JobRepository jobRepository, Step mailStep) {
        return new JobBuilder("mailJob", jobRepository).start(mailStep).build();
    }

    public static void main(String[] args) throws Exception {
        SpringApplication app = new SpringApplication(SkipAndRetry.class);
        app.setDefaultProperties(Map.of(
                "spring.main.banner-mode", "off",
                "logging.level.root", "OFF",
                "spring.batch.job.enabled", "false"));
        try (var context = app.run(args)) {
            JobExecution execution = context.getBean(JobOperator.class)
                    .start(context.getBean(Job.class), new JobParameters());
            StepExecution step = execution.getStepExecutions().iterator().next();
            System.out.println("Job status: " + execution.getStatus());
            System.out.println("read " + step.getReadCount() + ", read skips "
                    + step.getReadSkipCount() + ", written " + step.getWriteCount()
                    + ", rollbacks " + step.getRollbackCount());
            System.out.println("Mails sent: " + SENT);
        }
    }
}
Output
skipped line 3: two,Bob,bob@example.com
  attempt 1 for [Ann]: sent
  attempt 2 for [Cara, Dan]: busy
  attempt 3 for [Cara, Dan]: busy
  attempt 4 for [Cara, Dan]: sent
  attempt 5 for [Eve]: sent
Job status: COMPLETED
read 4, read skips 1, written 4, rollbacks 0
Mails sent: [Ann, Cara, Dan, Eve]
  • Line 3, two,Bob,..., failed to parse with FlatFileParseException, which is listed in skip(...). The skip listener received the line number and the raw text, and the step continued. In real jobs, that listener writes the line to an error file or table for someone to fix.
  • The skipped line still counted toward the first chunk of 2, so that chunk wrote only Ann.
  • The chunk with Cara and Dan failed twice with MailServerBusyException and succeeded on the third attempt. The RetryPolicy allows up to 3 retries for that exception, with a 10 ms delay between them.
  • The job completed with 4 items read, 1 read skip and 4 written.

A retried write repeats the whole chunk, so Cara was in all three attempts. With a real mail server, a write that sent Cara's mail and then failed on Dan's would send Cara's twice. Writers used with retry must be idempotent, for example by recording what was sent in the same transaction. Spring Batch 6 builds retry on Spring Framework 7's RetryPolicy from org.springframework.core.retry, so the Spring Retry classes used in Spring Batch 5 code no longer apply here.

Partitioning: one step on several threads

When one thread is too slow, a partitioned step splits the data into ranges and runs a copy of a worker step for each range, in parallel. Each worker has its own step execution, so each range can be restarted on its own. Thirty orders are split into three ranges of ten:

Java
package batch.partition;

import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import javax.sql.DataSource;
import org.springframework.batch.core.configuration.annotation.StepScope;
import org.springframework.batch.core.job.Job;
import org.springframework.batch.core.job.JobExecution;
import org.springframework.batch.core.job.builder.JobBuilder;
import org.springframework.batch.core.job.parameters.JobParameters;
import org.springframework.batch.core.launch.JobOperator;
import org.springframework.batch.core.partition.Partitioner;
import org.springframework.batch.core.repository.JobRepository;
import org.springframework.batch.core.step.Step;
import org.springframework.batch.core.step.builder.StepBuilder;
import org.springframework.batch.infrastructure.item.ExecutionContext;
import org.springframework.batch.infrastructure.item.ItemWriter;
import org.springframework.batch.infrastructure.item.database.JdbcCursorItemReader;
import org.springframework.batch.infrastructure.item.database.builder.JdbcCursorItemReaderBuilder;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.core.task.SimpleAsyncTaskExecutor;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.transaction.PlatformTransactionManager;

@SpringBootApplication
public class PartitionedJob {

    static final Set<String> THREADS = ConcurrentHashMap.newKeySet();

    @Bean
    Partitioner rangePartitioner() {
        return gridSize -> {
            Map<String, ExecutionContext> partitions = new HashMap<>();
            int size = 30 / gridSize;
            for (int i = 0; i < gridSize; i++) {
                ExecutionContext context = new ExecutionContext();
                context.putInt("min", i * size + 1);
                context.putInt("max", (i + 1) * size);
                partitions.put("range" + i, context);
            }
            return partitions;
        };
    }

    @Bean
    @StepScope
    JdbcCursorItemReader<Integer> rangeReader(DataSource dataSource,
            @Value("#{stepExecutionContext['min']}") int min,
            @Value("#{stepExecutionContext['max']}") int max) {
        return new JdbcCursorItemReaderBuilder<Integer>()
                .name("rangeReader")
                .dataSource(dataSource)
                .sql("SELECT id FROM orders WHERE id BETWEEN ? AND ? ORDER BY id")
                .queryArguments(min, max)
                .rowMapper((rs, row) -> rs.getInt(1))
                .build();
    }

    @Bean
    Step workerStep(JobRepository jobRepository, PlatformTransactionManager tx,
            JdbcCursorItemReader<Integer> rangeReader, JdbcTemplate jdbc) {
        ItemWriter<Integer> writer = chunk -> {
            THREADS.add(Thread.currentThread().getName());
            for (Integer id : chunk.getItems()) {
                jdbc.update("UPDATE orders SET total = total * 2 WHERE id = ?", id);
            }
        };
        return new StepBuilder("worker", jobRepository)
                .<Integer, Integer>chunk(4)
                .transactionManager(tx)
                .reader(rangeReader)
                .writer(writer)
                .build();
    }

    @Bean
    Step managerStep(JobRepository jobRepository, @Qualifier("workerStep") Step workerStep,
            Partitioner partitioner) {
        return new StepBuilder("manager", jobRepository)
                .partitioner("worker", partitioner)
                .step(workerStep)
                .gridSize(3)
                .taskExecutor(new SimpleAsyncTaskExecutor("part-"))
                .build();
    }

    @Bean
    Job orderJob(JobRepository jobRepository, @Qualifier("managerStep") Step managerStep) {
        return new JobBuilder("orderJob", jobRepository).start(managerStep).build();
    }

    public static void main(String[] args) throws Exception {
        SpringApplication app = new SpringApplication(PartitionedJob.class);
        app.setDefaultProperties(Map.of(
                "spring.main.banner-mode", "off",
                "logging.level.root", "WARN",
                "spring.batch.job.enabled", "false"));
        try (var context = app.run(args)) {
            JdbcTemplate jdbc = context.getBean(JdbcTemplate.class);
            jdbc.execute("CREATE TABLE orders (id INT PRIMARY KEY, total INT)");
            for (int id = 1; id <= 30; id++) {
                jdbc.update("INSERT INTO orders VALUES (?, 10)", id);
            }
            JobExecution execution = context.getBean(JobOperator.class)
                    .start(context.getBean(Job.class), new JobParameters());
            System.out.println("Job status: " + execution.getStatus());
            execution.getStepExecutions().stream()
                    .sorted(Comparator.comparing(s -> s.getStepName()))
                    .forEach(s -> System.out.println("  " + s.getStepName() + ": read "
                            + s.getReadCount() + ", written " + s.getWriteCount()
                            + ", commits " + s.getCommitCount()));
            System.out.println("Worker threads used: " + THREADS.size());
            System.out.println("Orders doubled: " + jdbc.queryForObject(
                    "SELECT COUNT(*) FROM orders WHERE total = 20", Integer.class));
        }
    }
}
Output
Job status: COMPLETED
  manager: read 30, written 30, commits 9
  worker:range0: read 10, written 10, commits 3
  worker:range1: read 10, written 10, commits 3
  worker:range2: read 10, written 10, commits 3
Worker threads used: 3
Orders doubled: 30
  • The Partitioner created three execution contexts, range0 to range2, each with a min and max id. The manager step ran the worker once per context, on three threads of the SimpleAsyncTaskExecutor.
  • Each worker read 10 orders in chunks of 4, so 3 commits (4, 4 and 2). The manager's counts are the sum: 30 read and written, 9 commits.
  • The reader is @StepScope: a new instance is created for each worker step execution, and @Value("#{stepExecutionContext['min']}") injects that worker's range.

The program sorts the step executions before printing them, because the workers finish in a different order on each run. Partitioning works when the data splits cleanly by key and the workers do not compete for the same rows. Spring Batch can also run partitions in other JVMs through Spring Integration, with the same Partitioner.

Running jobs in production

  • On startup: with spring.batch.job.enabled=true, the default, Spring Boot runs the job when the application starts, and the process exits when it finishes. Command-line arguments without --, such as file=customers.csv, become job parameters. With more than one job, set spring.batch.job.name.
  • Scheduling: run the application from a scheduler such as cron or Kubernetes CronJobs, one process per run. That keeps memory clean between runs and makes the exit code the job's status.
  • Restarting: start the job again with the same identifying parameters. Non-identifying parameters are not copied from the failed execution, so pass them again.
  • A job killed mid-run: its execution stays STARTED in the repository, and a restart is refused because Spring Batch thinks it is still running. Spring Batch 6 adds JobOperator.recover to bring such an execution back to a restartable state, which earlier versions needed manual SQL updates for.
  • A separate database for metadata: annotate a DataSource bean with @BatchDataSource (and defaultCandidate = false) to keep the job repository apart from the business data, as described on the multiple data sources page.

Choosing the right building block

Spring Batch features for common needs
NeedUse
Read, transform and write many recordsA chunk-oriented step with a chunk size of 100 to 1,000
One action, such as deleting a file or calling a procedureA Tasklet step
Bad records that should not stop the jobfaultTolerant().skip(...) with a skip listener that records them
Temporary failures in a writer or processorretryPolicy(...), with idempotent writers
Resuming after a crashThe JDBC job repository and the same identifying parameters
A job that runs regularly with new dataA date or file parameter, or RunIdIncrementer
Too much data for one threadA partitioned step, or a multi-threaded step if order does not matter
Small one-off scriptsPlain JDBC or JdbcClient; Spring Batch adds more than it saves

Spring Batch's chunk transactions are ordinary Spring transactions; the @Transactional page explains how they commit and roll back. For the JDBC batching that JdbcBatchItemWriter uses, see JDBC transactions and batch updates, and for scheduling inside an application, see Spring scheduling.