Building a lightweight distributed job runner with ShedLock
Replace Spring Batch with a lightweight distributed job runner backed by Redis ShedLock, PostgreSQL lease heartbeats, and checkpoint-based resume.
Instead of pulling in Spring Batch’s nine metadata tables and chunk-transaction constraints for a handful of API-scraping jobs, I built a lightweight distributed job runner backed by Redis ShedLock and PostgreSQL lease heartbeats. This post covers the dual-lock fencing design, dedicated executor isolation, checkpoint resume, and graceful cancellation.
Why I built a lightweight runner instead of using Spring Batch
In my court-ruling collection and AI summarization service (demo-backend-server), daily batch jobs fetch hundreds to thousands of rulings from external APIs (judgment-collection-job) and discover newly published cases (judgment-discovery-job).
I looked at Spring Batch first, but four practical mismatches pushed me toward a smaller custom runner:
- Heavy metadata schema: Running Spring Batch means maintaining 9+ framework tables (
BATCH_JOB_EXECUTION,BATCH_STEP_EXECUTION, and friends) just to track a few collection jobs. - No built-in multi-instance locking: When multiple pods fire a cron schedule at the same second, Spring Batch doesn’t prevent duplicate runs on its own—you still have to layer Quartz clustering or ShedLock on top.
- Long chunk transactions starve DB connections: External court API scraping and LLM summarization calls have high network latency. Wrapping external I/O inside a chunk transaction holds HikariCP connections open for seconds at a time.
- Live operator controls: From
/admin/jobs, operators need to edit cron schedules without redeploying, cancel an in-flight run cleanly at a safe boundary, and watch live progress percentages and per-item errors.
The alternative was straightforward: claim the distributed lock fast in Redis with ShedLock, and track execution state, lease heartbeats, and checkpoints in PostgreSQL using short REQUIRES_NEW transactions.
Figure 1. Admin jobs dashboard (/admin/jobs) displaying registered jobs, live progress, and manual Resume/Restart triggers.
When not to use a custom runner: Stick with Spring Batch if you need complex multi-step DAG workflows, partitioned parallel chunk processing over millions of database rows, or standard Spring Batch ecosystem connectors. A lightweight runner shines specifically when jobs are I/O-heavy, moderate in count, and need tight admin UI integration.
Core architecture: Redis ShedLock + PostgreSQL lease fencing
Long-running distributed jobs face two classic failure modes: duplicate execution across nodes and zombie locks left behind by crashed pods.
Relying on a Redis lock TTL alone forces a bad trade-off. A long TTL blocks subsequent runs for minutes if a pod gets OOM-killed; a short TTL expires while a slow job is still running, letting a second node start a duplicate run.
To eliminate both failure modes, I paired Redis ShedLock (fast initial claim) with a PostgreSQL lease heartbeat (renewal and fencing).
sequenceDiagram
autonumber
actor Scheduler as JobScheduler (Cron Poll)
participant Node1 as Instance Node-1
participant Node2 as Instance Node-2
participant Redis as Redis (ShedLock)
participant DB as PostgreSQL (JobStateStore)
par Concurrent trigger
Scheduler->>Node1: start("judgment-collection-job")
Scheduler->>Node2: start("judgment-collection-job")
end
Node1->>Redis: locks.lock("job:judgment-collection-job", lease=10m)
Note over Node1,Redis: Lock acquired (SimpleLock)
Node2->>Redis: locks.lock("job:judgment-collection-job", lease=10m)
Note over Node2,Redis: Lock denied (Optional.empty)
Node2-->>Scheduler: Throw ALREADY_RUNNING & exit cleanly
Node1->>DB: begin() -> Create JobRun #1042 (leaseUntil = now + 10m)
Node1->>Node1: Dispatch async work to jobExecutor
loop Process items (1..N)
Node1->>Node1: context.check() (cancel flag & lease expiry)
opt Remaining lease < 5 min
Node1->>Redis: lock.extend(10m, Duration.ZERO)
Node1->>DB: states.renew(runId, now + 10m)
end
Node1->>DB: states.record(SUCCEEDED, checkpoint) [REQUIRES_NEW]
end
Node1->>DB: finish(SUCCEEDED)
Node1->>Redis: lock.unlock()
How the two layers protect each other
- Initial claim (Redis ShedLock): At startup, ShedLock runs
SET key value NX PXwith a 10-minuteleaseDuration. Any competing node immediately receivesALREADY_RUNNINGand backs off. - Database lease record: The winning node writes a
job_runsrow withlease_until = now + 10m. - Heartbeat renewal: Before every item, the loop calls
context.check(). Once remaining lease time drops below half (5 minutes), it extends both the Redis lock andjob_runs.lease_untilby another 10 minutes. - Crash recovery and fencing: If the worker pod dies, a 10-second polling scheduler calls
recoverExpired()to mark stale runs asFAILED. Even if a paused JVM thread wakes up later after a long GC pause,states.check()rejects its writes becauselease_untilhas expired—preventing zombie writes. (For more on keeping distributed locks aligned with DB transaction boundaries, see my note on Redis distributed locks and transaction boundaries.)
JobDefinition and JobRunner: contract and thread-pool isolation
1. Defining a job contract
Every job implements a minimal JobDefinition Spring bean:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// src/main/kotlin/com/example/server/job/application/JobDefinition.kt
package com.example.server.job.application
import java.time.Duration
/**
* Batch job specification.
* Each job keeps per-item external call timeouts shorter than leaseDuration
* and calls context.check() between items to renew the lease.
*/
interface JobDefinition {
val name: String
val description: String
val defaultCron: String
val leaseDuration: Duration get() = Duration.ofMinutes(10)
fun execute(context: JobContext)
}
2. Isolating batch execution from web threads
Long-running jobs must never run on Tomcat request threads. I isolate them in a dedicated ThreadPoolTaskExecutor bean alongside the ShedLock RedisLockProvider:
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
// src/main/kotlin/com/example/server/job/JobConfig.kt
package com.example.server.job
import net.javacrumbs.shedlock.provider.redis.spring.RedisLockProvider
import org.springframework.beans.factory.annotation.Value
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.data.redis.connection.RedisConnectionFactory
import org.springframework.scheduling.annotation.EnableScheduling
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor
@Configuration
@EnableScheduling
class JobConfig {
@Bean
fun jobLockProvider(
factory: RedisConnectionFactory,
@Value("\${spring.profiles.active:default}") environment: String,
) = RedisLockProvider.Builder(factory)
.environment("demo-app:$environment")
.safeUpdate(true)
.build()
@Bean
fun jobExecutor() = ThreadPoolTaskExecutor().apply {
corePoolSize = 2
maxPoolSize = 2
queueCapacity = 0 // Reject immediately when saturated instead of silent queuing
setThreadNamePrefix("batch-job-")
setWaitForTasksToCompleteOnShutdown(true)
setAwaitTerminationSeconds(30)
}
}
Setting
queueCapacity = 0prevents jobs from sitting silently in an in-memory queue and firing at an unexpected time later. When both worker threads are busy, Spring throwsTaskRejectedException, whichJobRunnerconverts into a clearCAPACITY_EXCEEDEDerror.
3. Lock claim and async dispatch in JobRunner
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
// src/main/kotlin/com/example/server/job/application/JobRunner.kt
package com.example.server.job.application
import com.example.server.common.BusinessException
import com.example.server.job.domain.*
import java.time.Duration
import java.time.Instant
import java.util.UUID
import net.javacrumbs.shedlock.core.LockConfiguration
import net.javacrumbs.shedlock.provider.redis.spring.RedisLockProvider
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.ObjectProvider
import org.springframework.beans.factory.annotation.Qualifier
import org.springframework.core.task.TaskExecutor
import org.springframework.core.task.TaskRejectedException
import org.springframework.stereotype.Service
@Service
class JobRunner(
definitions: ObjectProvider<JobDefinition>,
private val states: JobStateStore,
private val locks: RedisLockProvider,
@Qualifier("jobExecutor") private val executor: TaskExecutor,
) {
val definitions: List<JobDefinition> = definitions.orderedStream().toList().also { jobs ->
require(jobs.map { it.name }.distinct().size == jobs.size) { "Duplicate job names detected." }
}
private val instance = "${System.getenv("HOSTNAME") ?: "local"}-${UUID.randomUUID().toString().take(8)}"
private val logger = LoggerFactory.getLogger(javaClass)
fun definition(name: String): JobDefinition = definitions.find { it.name == name }
?: throw BusinessException(JobErrorCode.NOT_FOUND)
fun start(name: String, trigger: JobTrigger = JobTrigger.MANUAL, mode: JobStartMode = JobStartMode.RESUME): Long? {
val job = definition(name)
val setting = states.register(job)
if (trigger == JobTrigger.SCHEDULED && (!setting.enabled || setting.nextScheduledAt?.isAfter(Instant.now()) != false)) {
return null
}
val started = Instant.now()
// 1. Acquire Redis ShedLock immediately to block duplicate runs
val lock = locks.lock(LockConfiguration(started, "job:${job.name}", job.leaseDuration, Duration.ZERO))
.orElseThrow { BusinessException(JobErrorCode.ALREADY_RUNNING) }
// 2. Persist JobRun record with initial lease timestamp
val run = try {
states.begin(job, trigger, mode, instance)
} catch (e: Exception) {
lock.unlock()
throw e
}
if (run == null) {
lock.unlock()
return null
}
val leaseUntil = started.plus(job.leaseDuration)
val context = JobContext(run.id, run.checkpoint, states, lock, job.leaseDuration, leaseUntil)
// 3. Hand off execution to the isolated batch thread pool
try {
states.renew(run.id, leaseUntil)
executor.execute {
try {
context.check()
states.activate(run.id)
job.execute(context)
context.check()
states.finish(run.id)
} catch (e: Exception) {
states.finish(run.id, e.message ?: e.javaClass.simpleName)
logger.warn("Job {} run {} ended: {}", name, run.id, e.javaClass.simpleName)
} finally {
runCatching { context.unlock() }.onFailure { logger.warn("Failed to unlock job {}", name, it) }
}
}
} catch (e: Exception) {
states.finish(run.id, "Failed to start job execution: ${e.javaClass.simpleName}")
context.unlock()
if (e is TaskRejectedException) throw BusinessException(JobErrorCode.CAPACITY_EXCEEDED)
throw e
}
return run.id
}
}
Dynamic scheduling and graceful cancellation
Hardcoding @Scheduled(cron = "0 0 4 * * *") in source code forces a redeployment every time an operator wants to adjust a schedule. Instead, I store cron expressions in job_settings and poll every 10 seconds:
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
// src/main/kotlin/com/example/server/job/application/JobScheduler.kt
package com.example.server.job.application
import com.example.server.common.BusinessException
import com.example.server.job.domain.JobErrorCode
import com.example.server.job.domain.JobTrigger
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Value
import org.springframework.scheduling.annotation.Scheduled
import org.springframework.stereotype.Component
@Component
class JobScheduler(
private val runner: JobRunner,
private val states: JobStateStore,
@Value("\${app.jobs.scheduling-enabled:true}") private val schedulingEnabled: Boolean,
) {
private val logger = LoggerFactory.getLogger(javaClass)
@Scheduled(fixedDelayString = "\${app.jobs.poll-delay:10000}", initialDelayString = "\${app.jobs.poll-delay:10000}")
fun poll() {
// Recover runs whose heartbeats expired due to pod crashes
states.recoverExpired()
if (!schedulingEnabled) return
runner.definitions.forEach { job ->
try {
runner.start(job.name, JobTrigger.SCHEDULED)
} catch (e: BusinessException) {
if (e.errorCode != JobErrorCode.ALREADY_RUNNING && e.errorCode != JobErrorCode.CAPACITY_EXCEEDED) {
logger.warn("Schedule check failed for job {}: {}", job.name, e.errorCode.code)
}
} catch (e: Exception) {
logger.error("Schedule check failed for job {}", job.name, e)
}
}
}
}
Cooperative cancellation without half-written state
Killing a worker thread with Thread.interrupt() mid-request risks leaving external API calls and DB updates half-committed. Instead, clicking Cancel in /admin/jobs simply sets JobRun.cancelRequested = true in PostgreSQL. Before the worker starts the next item, context.check() validates the flag and throws JobStopped:
1
2
3
4
5
6
7
// Inside JobStateStore.kt
private fun validate(run: JobRun) {
if (run.cancelRequested) throw JobStopped("Cancellation requested by admin.")
if (run.status != JobStatus.RUNNING || !run.leaseUntil.isAfter(Instant.now())) {
throw JobStopped("Run is no longer active or lease has expired.")
}
}
Every item committed before the cancellation point stays intact along with its latest checkpoint, and the run transitions cleanly to CANCELLED.
Per-item error isolation and checkpoint resume
One malformed ruling shouldn’t roll back 999 valid records. JobContext commits each item in its own short REQUIRES_NEW transaction and logs individual item failures to a separate error table without aborting the batch. (For a deeper look at designing idempotent checkpoints, see my post on the batch checkpoint-resume pattern.)
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
// src/main/kotlin/com/example/server/job/application/JobContext.kt
package com.example.server.job.application
import com.example.server.job.domain.JobItemResult
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,
) {
fun check() {
if (Thread.currentThread().isInterrupted) throw JobStopped("Worker thread was interrupted.")
if (!leaseUntil.isAfter(Instant.now())) throw JobStopped("Execution lease has expired.")
// Renew heartbeat once half the lease duration has elapsed
if (Instant.now().plus(leaseDuration.dividedBy(2)).isAfter(leaseUntil)) {
val renewedAt = Instant.now()
lock = lock.extend(leaseDuration, Duration.ZERO).orElseThrow { JobStopped("Lost distributed lock ownership.") }
leaseUntil = renewedAt.plus(leaseDuration)
states.renew(runId, leaseUntil)
}
states.check(runId)
}
fun total(count: Long) { check(); states.total(runId, count) }
fun process(itemKey: String, checkpoint: String? = null, action: () -> Unit): Boolean {
check()
return try {
states.record(runId, JobItemResult.SUCCEEDED, checkpoint, action)
true
} catch (e: JobStopped) {
throw e
} catch (e: Exception) {
failure(itemKey, e.message ?: e.javaClass.simpleName)
false
}
}
fun skip(checkpoint: String? = null) { check(); states.record(runId, JobItemResult.SKIPPED, checkpoint) }
fun failure(itemKey: String, message: String) { check(); states.recordError(runId, itemKey, message) }
internal fun unlock() = lock.unlock()
}
Here is what the persisted execution history looks like in PostgreSQL:
Figure 2. job_runs history in PostgreSQL tracking status, processed/failed counts, instance ID, and last checkpoint.
Operators can launch any job in two modes:
- Resume (
JobStartMode.RESUME): Loads the last committed checkpoint (for example,court:2026-11-08:p742) and picks up right after it—saving external API quota and avoiding duplicate scraping. - Restart (
JobStartMode.RESTART): Resets the checkpoint tonulland reprocesses from the beginning.
Verifying mutual exclusion under contention
To confirm that two independent instances can’t run the same job concurrently, I wrote an integration test with two separate JobRunner instances and 8 threads firing start() at the exact same moment via a CountDownLatch:
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
// src/test/kotlin/com/example/server/job/JobRunnerTest.kt
@Test
fun `concurrent manual starts across two runners execute the job only once`() {
val ready = CountDownLatch(1)
val release = CountDownLatch(1)
val counter = AtomicInteger()
fixture.action = { counter.incrementAndGet(); ready.countDown(); check(release.await(5, TimeUnit.SECONDS)) }
val second = anotherRunner()
val ids = try {
Executors.newFixedThreadPool(8).use { pool ->
val start = CountDownLatch(1)
val requests = (0..7).map { index ->
pool.submit<Result<Long?>> {
check(start.await(5, TimeUnit.SECONDS))
runCatching { (if (index % 2 == 0) runner else second).start(fixture.name) }
}
}
start.countDown()
check(ready.await(5, TimeUnit.SECONDS))
val results = requests.map { it.get(5, TimeUnit.SECONDS) }
// Exactly 1 of the 8 concurrent requests succeeds
assertThat(results.count { it.isSuccess }).isEqualTo(1)
// The other 7 fail cleanly with ALREADY_RUNNING
results.mapNotNull { it.exceptionOrNull() }.forEach {
assertThat(it).isInstanceOf(BusinessException::class.java)
assertThat((it as BusinessException).errorCode).isEqualTo(JobErrorCode.ALREADY_RUNNING)
}
results.mapNotNull { it.getOrNull() }
}
} finally { release.countDown() }
completed(ids.single())
assertThat(counter.get()).isEqualTo(1) // Job body ran exactly once
}
Figure 3. Multi-instance concurrency test output: Node-1 acquires the ShedLock while Node-2 skips cleanly with ALREADY_RUNNING.
Summary checklist
- Keep metadata minimal: Three entities (
JobSetting,JobRun,JobRunError) cover scheduling, progress, checkpoints, and per-item errors without 9+ framework tables. - Pair Redis locks with DB leases: Use ShedLock for fast contention rejection and PostgreSQL
lease_untilheartbeats to recover crashed pods and fence zombie workers. - Isolate worker threads with
queueCapacity = 0: Prevent batch jobs from starving Tomcat threads or piling up silently in memory. - Commit per item with
REQUIRES_NEW: Keep external API and LLM latency outside DB transactions and preserve progress cleanly on graceful cancellation.