Spring › Feature

Building a JSON checkpoint state machine for Spring batch jobs

How to build a JSON cursor checkpoint state machine with REQUIRES_NEW transaction isolation so large external API batch jobs resume safely after failures.

Building a JSON checkpoint state machine for Spring batch jobs

When a batch job collects tens of thousands of records from an external public API, a network timeout or rolling deployment shouldn’t force a restart from item #1. In this post, I share a JSON checkpoint state machine paired with REQUIRES_NEW transaction isolation so individual item failures roll back cleanly without wiping out batch progress or error logs.

Built with Spring Boot, Kotlin, Spring Data JPA, PostgreSQL, and ShedLock.


Why large external API batch jobs break in production

While running a full-collection batch job (judgment-full, pulling over 50,000 court rulings from public legal portals), I quickly hit four failure modes that an in-memory loop or a naive chunk-based batch can’t absorb cleanly:

  1. Intermittent upstream timeouts: Fetching tens of thousands of records takes hours. If the upstream portal returns 504 Gateway Timeout or 502 Bad Gateway on record #9,990, restarting from record #1 on the next scheduled run wastes hours of runtime and burns through strict API quotas.
  2. Rolling deployments and pod eviction: In Kubernetes or any continuous deployment pipeline, application instances restart frequently. When a long-running batch receives SIGTERM, it must stop without losing the exact offset it reached.
  3. Transaction contamination from a single bad record: Upstream APIs occasionally serve malformed XML/JSON or data that triggers a database constraint violation. If that single failure bubbles up through a shared @Transactional boundary, it rolls back the entire batch—erasing both the checkpoint and the error record.
  4. Partial page consumption: Most public APIs paginate responses in blocks of 100 (page=42). If the job crashes after processing 35 of the 100 items on page 42, storing only the page number forces the next run to re-fetch and re-parse those 35 items.

To solve all four problems without pulling in a heavyweight batch framework, I combined a fine-grained JSON cursor state machine with per-item transaction isolation (JobContext.processResult).

Admin job dashboard showing the Resume action and saved JSON checkpoint Figure 1. The admin job dashboard (/admin/jobs). After processing 150 records and stopping safely, the saved JSON checkpoint (page=42, 68 items remaining) is ready for an immediate Resume.


Modeling the checkpoint cursor as a JSON state machine

Storing only a database auto-increment ID or a single page index doesn’t work well for two-step external API ingestion. Each list API call returns 100 serial numbers, and the job must call a separate detail API for every serial number.

Instead, I model the cursor as an immutable data class that stores both the current page number and the exact list of unprocessed serial numbers (pending) still remaining on that page.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// src/main/kotlin/com/example/server/judgment/application/JudgmentCollectionJobs.kt
package com.example.server.judgment.application

/**
 * Persists the collection date range and remaining serial numbers (pending)
 * so an interrupted job resumes at the exact next item without duplicate API calls.
 */
data class JudgmentCollectionCursor(
    val kind: String,                      // Collection type ("full", "incremental", "labor")
    val from: String,                      // Start date (YYYY-MM-DD)
    val to: String,                        // End date (YYYY-MM-DD)
    val page: Int = 1,                     // Current external API page number
    val pending: List<Long> = emptyList(), // Unprocessed precedent serial numbers on this page
    val lastPage: Boolean = false,         // Whether the list API reached its final page
    val done: Boolean = false,             // Whether the entire date range is complete
    val listing: List<JudgmentListing> = emptyList() // List-level metadata (sentence date, court, etc.)
)

The state machine advances through four predictable transitions:

  1. Fetch a page: When pending is empty, call the list API (client.list(cursor.page, 100)), populate pending with the returned serial numbers, and increment page.
  2. Consume one item: Take pending.first(), call the detail API, and persist the domain entity.
  3. Advance the cursor: Build a new immutable cursor with pending.drop(1) and commit the serialized JSON string to PostgreSQL right away.
  4. Mark completion: Once lastPage == true and the final item in pending finishes, set done = true.
stateDiagram-v2
    [*] --> Idle: Waiting for trigger
    Idle --> FetchPage: pending is empty
    FetchPage --> FetchPage: Fill 100 items & page++
    FetchPage --> ConsumeItem: Pop pending.first()
    ConsumeItem --> SaveAndCommit: Item Tx (REQUIRES_NEW) succeeds
    SaveAndCommit --> ConsumeItem: Drop item & save checkpoint
    ConsumeItem --> RollbackAndSkip: Parse or DB error
    RollbackAndSkip --> ConsumeItem: Log error & drop item
    ConsumeItem --> Complete: lastPage=true & pending empty
    Complete --> [*]: Done (done=true)

Dual persistence: global cursor vs. per-run snapshot

A common mistake in custom batch runners is storing checkpoints only in the execution history table (job_runs). When the next run starts, it has to scan previous runs to locate the latest valid checkpoint, which complicates queries and opens race conditions.

I persist the checkpoint in two places: a global settings table (job_settings) and a per-run history table (job_runs).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// src/main/kotlin/com/example/server/job/domain/JobSetting.kt
package com.example.server.job.domain

import com.example.server.common.BaseEntity
import jakarta.persistence.*
import org.hibernate.Length

@Entity
@Table(name = "job_settings")
class JobSetting(
    @Column(nullable = false, unique = true, updatable = false)
    val name: String,
    @Column(nullable = false)
    var cron: String,
    var enabled: Boolean = false,
    @Column(length = Length.LONG32)
    var checkpoint: String? = null, // Single source of truth for the next run
) : BaseEntity() {
    @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
    val id: Long = 0
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// src/main/kotlin/com/example/server/job/domain/JobRun.kt
package com.example.server.job.domain

import com.example.server.common.BaseEntity
import jakarta.persistence.*
import java.time.Instant
import org.hibernate.Length

@Entity
@Table(name = "job_runs")
class JobRun(
    @Column(name = "job_name", nullable = false, updatable = false)
    val jobName: String,
    @Enumerated(EnumType.STRING)
    val trigger: JobTrigger,
    @Enumerated(EnumType.STRING)
    val startMode: JobStartMode, // RESUME vs RESTART
    val instanceId: String,
    var leaseUntil: Instant,
    @Column(length = Length.LONG32)
    var checkpoint: String? = null, // Final progress snapshot for this run
) : BaseEntity() {
    @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
    val id: Long = 0
    @Enumerated(EnumType.STRING)
    var status: JobStatus = JobStatus.RUNNING
    var processedCount: Long = 0
    var successCount: Long = 0
    var failureCount: Long = 0
}
  • job_settings.checkpoint: The single source of truth that the next scheduled or manual run reads. It survives restarts and rolling updates untouched.
  • job_runs.checkpoint: The point-in-time snapshot where a specific run (for example, #1084) finished or stopped. It gives operators a clean audit trail for progress monitoring and failure analysis.

PostgreSQL console output showing saved JSON checkpoints Figure 2. Inspecting PostgreSQL via psql. job_settings holds the global JSON cursor for the next execution, while job_runs retains the per-run snapshot.


Isolating item rollbacks from checkpoint commits

The hardest transactional requirement in a checkpointed batch is straightforward to state:

If saving a business entity fails, that entity write must roll back—yet the runner’s failureCount, the job_run_errors row, and the advanced checkpoint must still commit.

If business writes and runner state share a single @Transactional boundary, any exception rolls back the error log and resets the cursor. To prevent that, JobContext and JobStateStore isolate each item inside a short Propagation.REQUIRES_NEW transaction.

1. Lease checks and error handling in JobContext

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
// src/main/kotlin/com/example/server/job/application/JobContext.kt
package com.example.server.job.application

import java.time.Duration
import java.time.Instant
import net.javacrumbs.shedlock.core.SimpleLock

class JobContext internal constructor(
    val runId: Long,
    val checkpoint: String?,
    private val states: JobStateStore,
    private var lock: SimpleLock,
    private val leaseDuration: Duration,
    private var leaseUntil: Instant,
) {
    /**
     * Checks thread interruption, distributed lease validity, and admin cancellation.
     * Called right before and after external HTTP calls to stop stale work immediately.
     */
    fun check() {
        if (Thread.currentThread().isInterrupted) throw JobStopped("Execution thread was interrupted.")
        if (!leaseUntil.isAfter(Instant.now())) throw JobStopped("Execution lease has expired.")
        states.check(runId)
    }

    /**
     * Runs the business persistence action for one item and advances the checkpoint.
     * Unexpected exceptions roll back the item write while recording the failure separately.
     */
    fun processResult(itemKey: String, checkpoint: String, action: () -> String?): Boolean {
        check()
        return try {
            states.recordResult(runId, itemKey, checkpoint, action)
        } catch (e: JobStopped) {
            throw e
        } catch (e: Exception) {
            val message = "Failed to save item: ${e.javaClass.simpleName}. Preserving checkpoint."
            failure(itemKey, message)
            throw IllegalStateException(message, e)
        }
    }

    fun checkpoint(value: String) { check(); states.checkpoint(runId, value) }
    fun failure(itemKey: String, message: String) { check(); states.recordError(runId, itemKey, message) }
    fun total(count: Long) { check(); states.total(runId, count) }
    internal fun unlock() = lock.unlock()
}

2. Short REQUIRES_NEW commits in JobStateStore

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
// src/main/kotlin/com/example/server/job/application/JobStateStore.kt
package com.example.server.job.application

import com.example.server.common.BusinessException
import com.example.server.job.domain.*
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Propagation
import org.springframework.transaction.annotation.Transactional

@Service
class JobStateStore(
    private val settings: JobSettingRepository,
    private val runs: JobRunRepository,
    private val errors: JobRunErrorRepository,
) {
    /**
     * Commits one item's persistence result and updated checkpoint in an isolated transaction.
     * External HTTP I/O happens before this call so DB connections stay short-lived.
     */
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    fun recordResult(id: Long, itemKey: String, checkpoint: String, action: () -> String?): Boolean {
        val original = runs.findById(id).orElseThrow { BusinessException(JobErrorCode.NOT_FOUND) }
        val setting = settings.lockByName(original.jobName) ?: throw BusinessException(JobErrorCode.NOT_FOUND)
        val run = guarded(id)

        // 1. Run domain persistence (returns an error message string on validation/parse failure)
        val error = action()

        // 2. Re-verify cancellation or lease expiry so a stopped thread can't overwrite state
        validate(run)

        // 3. Update run counters
        run.processedCount++
        if (error == null) {
            run.successCount++
        } else {
            run.failureCount++
            run.errorSummary = error.take(1000)
            errors.save(JobRunError(id, itemKey.take(255), error.take(1000)))
        }

        // 4. Write the new JSON checkpoint to both global settings and this run's snapshot
        saveCheckpoint(setting, run, checkpoint)
        return error == null
    }

    private fun saveCheckpoint(setting: JobSetting, run: JobRun, checkpoint: String) {
        require(checkpoint.length <= 10000) { "Checkpoint JSON cannot exceed 10,000 characters." }
        setting.checkpoint = checkpoint
        run.checkpoint = checkpoint
    }

    private fun guarded(id: Long): JobRun =
        (runs.lockById(id) ?: throw BusinessException(JobErrorCode.NOT_FOUND)).also(::validate)

    private fun validate(run: JobRun) {
        if (run.cancelRequested) throw JobStopped("Cancellation requested by admin.")
        if (run.status != JobStatus.RUNNING) throw JobStopped("Job run is already terminated.")
    }
}
sequenceDiagram
    autonumber
    actor Batch as JudgmentCollectionJobs
    participant Context as JobContext
    participant Store as JobStateStore (REQUIRES_NEW)
    participant DB as PostgreSQL
    Batch->>Context: processResult("prec:214589", nextCursor, action)
    Context->>Context: check() lease & cancel flag
    Context->>Store: recordResult(runId, itemKey, nextCursor)
    activate Store
    Note over Store,DB: Start isolated Tx-Item
    alt Parse or domain error
        Note over Store: Domain entity write skipped
        Store->>DB: INSERT job_run_errors
        Store->>DB: UPDATE job_runs & job_settings
    else Domain save succeeds
        Store->>DB: INSERT raw_judgments & domain row
        Store->>DB: UPDATE job_runs & job_settings
    end
    Note over Store,DB: Commit Tx-Item
    deactivate Store
    Store-->>Context: return (error == null)
    Context-->>Batch: Continue to next item

With this boundary in place, a single broken upstream payload never crashes the job or traps the scheduler in an infinite retry loop. The bad item gets logged to job_run_errors, the cursor advances past it, and the remaining items finish normally.

Spring Boot console log showing an isolated item rollback while the batch continues Figure 3. Live Spring Boot batch log. When prec:214589 fails XML parsing, its domain write is skipped while the error record and cursor advance (pending.drop(1)) commit atomically, letting the batch finish all 100 items.


Implementing the collection loop (collect())

Here is how JudgmentCollectionJobs.collect() ties the cursor state machine, external HTTP calls, and JobContext together:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
// src/main/kotlin/com/example/server/judgment/application/JudgmentCollectionJobs.kt
package com.example.server.judgment.application

import com.example.server.job.application.JobContext
import com.example.server.job.application.JobStateStore
import tools.jackson.databind.json.JsonMapper
import java.time.LocalDate

class JudgmentCollectionJobs(
    private val client: LawPrecedentClient,
    private val importer: JudgmentImportService,
    private val properties: JudgmentCollectionProperties,
    private val mapper: JsonMapper,
) {
    fun collect(context: JobContext, kind: String) {
        val today = LocalDate.now(JobStateStore.ZONE)
        val source = SOURCES.getValue(kind)

        // 1. Restore the previous checkpoint from context
        val previous = context.checkpoint?.let { decode(it, JudgmentCollectionCursor::class.java) }
        val start = when (kind) {
            "full" -> properties.fullFrom
            "labor" -> LocalDate.of(1, 1, 1)
            else -> today.minusDays(properties.incrementalDays - 1L)
        }

        // Start a fresh cursor if none exists or an incremental run already finished
        var cursor = previous?.takeUnless { it.done && kind == "incremental" }
            ?: JudgmentCollectionCursor(kind, start.toString(), today.toString())

        context.checkpoint(mapper.writeValueAsString(cursor))
        if (cursor.done) return

        var processed = 0
        // Cap items per run (e.g., 100) to bound execution time and quota usage
        while (processed < properties.maxItemsPerRun) {
            context.check()

            // 2. Fetch the next list page once pending is empty
            if (cursor.pending.isEmpty()) {
                val page = client.list(cursor.page, 100, LocalDate.parse(cursor.from), LocalDate.parse(cursor.to), source)
                if (page.items.isEmpty()) {
                    context.checkpoint(mapper.writeValueAsString(cursor.copy(done = true)))
                    context.total(processed.toLong())
                    return
                }

                cursor = cursor.copy(
                    page = cursor.page + 1,
                    pending = page.items.map { it.precSerial },
                    lastPage = page.page * 100L >= page.totalCount,
                    listing = page.items.map(JudgmentListing::from)
                )

                // Drop optional metadata if serialized JSON approaches the DB column limit
                if (mapper.writeValueAsString(cursor).length > 9500) {
                    cursor = cursor.copy(listing = emptyList())
                }
                context.checkpoint(mapper.writeValueAsString(cursor))
            }

            // 3. Pop the next serial number
            val serial = cursor.pending.first()

            // 4. Call detail API outside any DB transaction (preserves cursor on failure)
            val detail = client.detail(serial, context)
                ?: throw LawPrecedentException("Stopping collection after detail API failure. Use Resume to retry.")

            val listing = cursor.listing.firstOrNull()?.takeIf { it.precSerial == serial }
            val nextCursor = cursor.copy(
                pending = cursor.pending.drop(1),
                listing = cursor.listing.drop(1),
                done = cursor.lastPage && cursor.pending.size == 1
            )

            // 5. Commit item and advance checkpoint atomically
            context.processResult("prec:$serial", mapper.writeValueAsString(nextCursor)) {
                importer.collect(serial, detail.rawJson, listing = listing, dataSourceName = source).error
            }

            cursor = nextCursor
            processed++
            if (cursor.done) break
        }

        context.total(processed.toLong())
    }

    private fun <T> decode(value: String, type: Class<T>): T = try {
        mapper.readValue(value, type)
    } catch (e: Exception) {
        throw IllegalStateException("Cannot parse saved checkpoint. Run with RESTART mode.", e)
    }

    companion object {
        val SOURCES = mapOf(
            "full" to "Supreme Court",
            "incremental" to "Supreme Court",
            "labor" to "Workers Compensation Precedents"
        )
    }
}

Guarding against oversized checkpoint JSON

If an upstream list page contains unusually long case titles or court names, serializing 100 listing entries can push the checkpoint past the 10,000-character limit enforced by saveCheckpoint().

1
2
3
if (mapper.writeValueAsString(cursor).length > 9500) {
    cursor = cursor.copy(listing = emptyList())
}

When the serialized payload crosses 9,500 characters, I drop the optional listing metadata and keep only the essential pending serial numbers. That prevents a column-length failure from halting the batch mid-page.


Manual operator controls: RESUME vs. RESTART and graceful cancellation

Operators can trigger any job manually from the admin UI in two modes:

Start modeCheckpoint behaviorWhen to use
JobStartMode.RESUMECopies job_settings.checkpoint into the new JobRunAfter a network outage, rate-limit pause, or deployment restart
JobStartMode.RESTARTClears job_settings.checkpoint to null and starts from page 1After a full schema redesign or intentional full resync
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// src/main/kotlin/com/example/server/job/application/JobStateStore.kt
@Transactional(propagation = Propagation.REQUIRES_NEW)
fun begin(job: JobDefinition, trigger: JobTrigger, mode: JobStartMode, instance: String): JobRun? {
    val setting = settings.lockByName(job.name) ?: throw BusinessException(JobErrorCode.NOT_FOUND)
    val now = Instant.now()

    // ... validate active leases and running jobs ...

    // Ignore saved checkpoint when starting in RESTART mode
    val initialCheckpoint = if (mode == JobStartMode.RESTART) null else setting.checkpoint

    return runs.saveAndFlush(
        JobRun(job.name, trigger, mode, instance, now.plus(job.leaseDuration), initialCheckpoint)
    )
}

@Transactional(propagation = Propagation.REQUIRES_NEW)
fun activate(id: Long) {
    val run = runs.findById(id).orElseThrow { BusinessException(JobErrorCode.NOT_FOUND) }
    val setting = settings.lockByName(run.jobName) ?: throw BusinessException(JobErrorCode.NOT_FOUND)

    // Clear global checkpoint once a RESTART run officially starts
    if (run.startMode == JobStartMode.RESTART) {
        setting.checkpoint = null
    }
}

Graceful cancellation without killing threads

When an operator clicks Cancel in the admin dashboard, the server never forcibly kills the worker thread. Instead, it sets job_runs.cancel_requested = true in PostgreSQL.

Once the current item finishes committing its transaction, the loop calls context.check() before starting the next item. That check detects cancelRequested and throws JobStopped, transitioning the run cleanly to JobStatus.CANCELLED with the exact last processed item committed.


When not to use this pattern and production checklist

This lightweight pattern is a great fit for sequential external API ingestion where each item takes 100ms–1s over HTTP, and pairs naturally with a lightweight ShedLock distributed job runner and immutable raw data reparsing. However, don’t use per-item REQUIRES_NEW commits for pure local database ETL jobs that process millions of rows per minute—the per-row commit overhead will bottleneck PostgreSQL WAL I/O, and Spring Batch’s chunk-oriented processing or JdbcTemplate bulk upserts will serve you far better.

Before deploying a JSON checkpoint state machine to production, verify these four points:

  • Keep external I/O outside @Transactional: Never call client.detail(...) inside a database transaction. Open the short REQUIRES_NEW transaction only after the HTTP response arrives so HikariCP connections don’t stall.
  • Make domain writes idempotent: A crash right after an external call or a duplicate delivery can still replay an item. Back every domain write with a unique index or ON CONFLICT DO UPDATE.
  • Cap cursor payload size: Keep the cursor focused on page numbers and IDs, and add defensive truncation for any optional metadata fields.
  • Lock job_settings on state updates: Pessimistic locking (lockByName) ensures a cancelled or lease-expired worker can never overwrite a newer run’s checkpoint.
This post is licensed under CC BY 4.0 by the author.