Video in progress
A bank calculates interest on millions of accounts and prepares statements every night. How do you build such a batch system reliably?
I split the job into independent pieces and run them in parallel; each piece is idempotent and has a checkpoint, so after a crash it resumes where it stopped instead of starting over. The result is verified with control totals and published in two phases, and resources are capped so the daytime system isn't affected.
📖 Answer
The usual pains of a nightly batch: it crashed at 70% at 04:00, and when you restart it some accounts get interest written twice; the job doesn't finish by 08:00 and collides with morning traffic; and the log has no answer to "what happened yesterday?".
-
An idempotent unit. The result is unique on
(account_id, business_date). If you restart, existing ones are skipped. The business date is a parameter, not the system clock: a delayed job that runs the next day still calculates for yesterday's date. -
Chunks and checkpoints. In Spring Batch, a chunk-oriented step: read-calculate-write 1000 at a time, each chunk is its own transaction, and the state lives in the
JobRepository. If it crashes, the restart begins from the last committed chunk.
@Bean
Step accrueInterest(JobRepository repo, PlatformTransactionManager tx) {
return new StepBuilder("accrueInterest", repo)
.<Account, Accrual>chunk(1000, tx)
.reader(accountReader()) // keyset by id, not offset
.processor(interestCalculator())
.writer(accrualWriter()) // ON CONFLICT DO NOTHING
.faultTolerant()
.skip(InvalidAccountException.class).skipLimit(100)
.build();
}
-
Parallelism. Partitioning by ID ranges, each partition on its own worker. The ranges must be equal by row count, otherwise one piece finishes after everything else.
-
Protecting the DB. Read from a replica, throttle writes, set
statement_timeout. Decide in advance what happens if it doesn't finish by morning: can you stop it and continue in the daytime? -
Two-phase publishing. Results first sit in the
STAGEDstate, the control totals are checked (do the record count and the total amount match what's expected?), and then they're published with a single atomic flag. A half-finished result is never visible to customers. -
Observability. For each job: start/end time, the number processed and skipped, an SLA (for example, done by 06:00) and an alert if it's late. Skipped records go to a separate table, which an operator reviews.
I also think about the future: if the volume grows 10x, the nightly window won't be enough. Then a better route is to calculate incrementally during the day and only finalize at night.
Sign up to mark studied questions and save your progress.