Implementing Background Job Processing

1. Designing Job Queue System

ComponentDetail
QueuePending jobs (Redis, DB, broker)
Worker poolPolls and executes
Result storeStatus + output
SchedulerFor delayed/recurring jobs

2. Implementing Scheduled Jobs

Example: @Scheduled cron

@Configuration @EnableScheduling
public class ScheduleConfig {}

@Service
public class ReportJob {
    @Scheduled(cron = "0 0 2 * * *", zone = "UTC")  // 02:00 UTC daily
    public void daily() { reports.generateDaily(); }
}

3. Implementing Cron Job Processor

FieldRange
second0-59 (Spring includes seconds)
minute0-59
hour0-23
day-of-month1-31
month1-12
day-of-week0-7 (0 or 7 = Sun)

4. Implementing Job Scheduling Logic

LibraryDetail
Spring @ScheduledSimple, in-process
QuartzJDBC-backed, clustered
ShedLockDistributed lock for @Scheduled
db-schedulerLightweight DB-backed

5. Handling Job Failures

StrategyDetail
RetryWith backoff
DLQManual investigation
AlertingOn repeated failure
IdempotencyRequired for safe retry

6. Implementing Job Retry Logic

SettingRecommendation
Max attempts3-5
BackoffExponential + jitter
Per-error policyDon't retry 4xx-style failures
Visible in UIShow attempt count

7. Implementing Distributed Job Locks

Example: ShedLock

@Scheduled(cron = "0 */5 * * * *")
@SchedulerLock(name = "syncFx", lockAtMostFor = "PT4M", lockAtLeastFor = "PT30S")
public void syncFx() { fxService.sync(); }
// Only one node executes at a time

8. Implementing Job Priority Queues

ApproachDetail
Multiple queueshigh / default / low; workers poll high first
Score-basedRedis sorted set by priority
Starvation guardPeriodically promote low

9. Implementing Job Status Tracking

StatusMeaning
PENDINGQueued
RUNNINGWorker executing
SUCCEEDEDCompleted OK
FAILEDPermanent failure
RETRYINGWill be re-attempted
CANCELLEDUser-cancelled

10. Implementing Long-Running Job Logic

PracticeDetail
CheckpointingSave progress periodically
ResumablePick up where it left off
HeartbeatDetect stalled workers
CancellationCooperative interruption
Progress reportingPercent / step counters

11. Handling Job Concurrency

SettingDetail
Worker countPer node
Per-queue concurrencyIsolate noisy neighbors
Per-tenant capFairness
BackpressurePause polling when overloaded

12. Implementing Job Result Storage

StorageUse
DB rowStatus + small result
Object store (S3)Large outputs
Redis with TTLShort-lived results
StreamedFor real-time consumers