Implement retry mechanism with exponential backoff #20

Closed
opened 2026-10-04 19:28:24 +00:00 by daniel · 1 comment
Owner

Imported from GitHub samson-media/barn#20 — opened by @daniel-samson on 2026-01-21 12:42:45 UTC

Overview

Implement the retry mechanism with exponential backoff for failed jobs.

Context

  • Read first: docs/config.md (retry behavior section)
  • Depends on: #4 (job model), #6 (scheduler)

Requirements

1. Retry Configuration

From docs/config.md:

  • max_retries: Maximum retry attempts (default: 3)
  • retry_delay_seconds: Initial delay (default: 30)
  • retry_backoff_multiplier: Exponential multiplier (default: 2.0)
  • retry_on_exit_codes: Specific exit codes to retry (default: all)

2. Retry Calculator

com.samsonmedia.barn.jobs.RetryCalculator.java:

public class RetryCalculator {
    private final JobsConfig config;

    public boolean shouldRetry(Job job) {
        // Check if retries are enabled
        if (job.retryCount() >= getMaxRetries(job)) {
            return false;
        }

        // Check if exit code is retryable
        if (!isRetryableExitCode(job.exitCode())) {
            return false;
        }

        return true;
    }

    public Duration calculateDelay(int retryCount) {
        // delay = base_delay * (multiplier ^ retry_count)
        double delaySeconds = config.retryDelaySeconds()
            * Math.pow(config.retryBackoffMultiplier(), retryCount);
        return Duration.ofSeconds((long) delaySeconds);
    }

    public Instant calculateRetryAt(Job job) {
        Duration delay = calculateDelay(job.retryCount());
        return Instant.now().plus(delay);
    }
}

3. Retry State Management

When a job fails and should be retried:

  1. Calculate next retry time
  2. Update retry_count (increment by 1)
  3. Update retry_at (next execution time)
  4. Append to retry_history (previous attempt details)
  5. Change state back to QUEUED
public void scheduleRetry(Job job) {
    int newRetryCount = job.retryCount() + 1;
    Instant retryAt = retryCalculator.calculateRetryAt(job);

    stateFiles.writeRetryCount(newRetryCount);
    stateFiles.writeRetryAt(retryAt);
    stateFiles.appendRetryHistory(job.exitCode(), job.error());
    stateFiles.writeState(JobState.QUEUED);
}

4. Retry History File

retry_history file format (append-only):

2026-01-21T18:40:01Z|exit_code=1|error=Connection timeout
2026-01-21T18:41:30Z|exit_code=1|error=Connection timeout
2026-01-21T18:44:00Z|exit_code=1|error=Connection timeout

5. Scheduler Integration

The scheduler should:

  1. Check retry_at for queued jobs
  2. Only execute jobs where retry_at <= now or retry_at is null
  3. Log retry attempts clearly
// In scheduler loop
Optional<Job> findNextQueued() {
    return repository.findAll().stream()
        .filter(j -> j.state() == JobState.QUEUED)
        .filter(j -> j.retryAt() == null || j.retryAt().isBefore(Instant.now()))
        .min(Comparator.comparing(Job::createdAt));
}

6. Output Display

When showing job status, include retry info:

Human format:

Job: job-9f83c
State:      queued (retry scheduled)
Retries:    2/3
Next Retry: 2026-01-21 18:44:00 (in 2m 30s)

Retry History:
  Attempt 1: exit=1 at 2026-01-21 18:40:01 - Connection timeout
  Attempt 2: exit=1 at 2026-01-21 18:41:30 - Connection timeout

JSON format:

{
  "retry_count": 2,
  "max_retries": 3,
  "retry_at": "2026-01-21T18:44:00Z",
  "retry_history": [
    {"attempt": 1, "exit_code": 1, "error": "Connection timeout", "timestamp": "2026-01-21T18:40:01Z"},
    {"attempt": 2, "exit_code": 1, "error": "Connection timeout", "timestamp": "2026-01-21T18:41:30Z"}
  ]
}

7. Per-Job Retry Override

From CLI:

barn run --max-retries=5 --retry-delay=60 my-command

Store in manifest.json and use instead of global config.

8. Tests Required

  • RetryCalculatorTest.java: Test delay calculation, retry eligibility
  • RetrySchedulerTest.java: Test job requeuing with delay
  • Integration test: Job fails, retries with backoff, eventually succeeds or gives up

Acceptance Criteria

  • Failed jobs retry up to max_retries times
  • Retry delay follows exponential backoff
  • retry_on_exit_codes filter works
  • Per-job retry override works
  • Retry history is recorded
  • Job eventually marked failed after max retries
  • Status output shows retry info
  • mvn verify passes
  • Tests have 80%+ coverage

Implementation Notes

Exponential backoff formula:

delay = base_delay * (multiplier ^ retry_count)

With defaults (30s, 2.0x, max 3):
- Retry 1: 30 * 2^0 = 30 seconds
- Retry 2: 30 * 2^1 = 60 seconds
- Retry 3: 30 * 2^2 = 120 seconds

Consider adding jitter to prevent thundering herd:

double jitter = ThreadLocalRandom.current().nextDouble(0.8, 1.2);
delaySeconds = delaySeconds * jitter;

Definition of Done

  • Retries work with exponential backoff
  • History tracked correctly
  • Per-job overrides work
  • All tests pass
<!-- github-import:issue:20 --> _Imported from GitHub samson-media/barn#20 — opened by **@daniel-samson** on 2026-01-21 12:42:45 UTC_ ## Overview Implement the retry mechanism with exponential backoff for failed jobs. ## Context - **Read first**: `docs/config.md` (retry behavior section) - **Depends on**: #4 (job model), #6 (scheduler) ## Requirements ### 1. Retry Configuration From `docs/config.md`: - `max_retries`: Maximum retry attempts (default: 3) - `retry_delay_seconds`: Initial delay (default: 30) - `retry_backoff_multiplier`: Exponential multiplier (default: 2.0) - `retry_on_exit_codes`: Specific exit codes to retry (default: all) ### 2. Retry Calculator `com.samsonmedia.barn.jobs.RetryCalculator.java`: ```java public class RetryCalculator { private final JobsConfig config; public boolean shouldRetry(Job job) { // Check if retries are enabled if (job.retryCount() >= getMaxRetries(job)) { return false; } // Check if exit code is retryable if (!isRetryableExitCode(job.exitCode())) { return false; } return true; } public Duration calculateDelay(int retryCount) { // delay = base_delay * (multiplier ^ retry_count) double delaySeconds = config.retryDelaySeconds() * Math.pow(config.retryBackoffMultiplier(), retryCount); return Duration.ofSeconds((long) delaySeconds); } public Instant calculateRetryAt(Job job) { Duration delay = calculateDelay(job.retryCount()); return Instant.now().plus(delay); } } ``` ### 3. Retry State Management When a job fails and should be retried: 1. Calculate next retry time 2. Update `retry_count` (increment by 1) 3. Update `retry_at` (next execution time) 4. Append to `retry_history` (previous attempt details) 5. Change state back to `QUEUED` ```java public void scheduleRetry(Job job) { int newRetryCount = job.retryCount() + 1; Instant retryAt = retryCalculator.calculateRetryAt(job); stateFiles.writeRetryCount(newRetryCount); stateFiles.writeRetryAt(retryAt); stateFiles.appendRetryHistory(job.exitCode(), job.error()); stateFiles.writeState(JobState.QUEUED); } ``` ### 4. Retry History File `retry_history` file format (append-only): ``` 2026-01-21T18:40:01Z|exit_code=1|error=Connection timeout 2026-01-21T18:41:30Z|exit_code=1|error=Connection timeout 2026-01-21T18:44:00Z|exit_code=1|error=Connection timeout ``` ### 5. Scheduler Integration The scheduler should: 1. Check `retry_at` for queued jobs 2. Only execute jobs where `retry_at <= now` or `retry_at` is null 3. Log retry attempts clearly ```java // In scheduler loop Optional<Job> findNextQueued() { return repository.findAll().stream() .filter(j -> j.state() == JobState.QUEUED) .filter(j -> j.retryAt() == null || j.retryAt().isBefore(Instant.now())) .min(Comparator.comparing(Job::createdAt)); } ``` ### 6. Output Display When showing job status, include retry info: Human format: ``` Job: job-9f83c State: queued (retry scheduled) Retries: 2/3 Next Retry: 2026-01-21 18:44:00 (in 2m 30s) Retry History: Attempt 1: exit=1 at 2026-01-21 18:40:01 - Connection timeout Attempt 2: exit=1 at 2026-01-21 18:41:30 - Connection timeout ``` JSON format: ```json { "retry_count": 2, "max_retries": 3, "retry_at": "2026-01-21T18:44:00Z", "retry_history": [ {"attempt": 1, "exit_code": 1, "error": "Connection timeout", "timestamp": "2026-01-21T18:40:01Z"}, {"attempt": 2, "exit_code": 1, "error": "Connection timeout", "timestamp": "2026-01-21T18:41:30Z"} ] } ``` ### 7. Per-Job Retry Override From CLI: ```bash barn run --max-retries=5 --retry-delay=60 my-command ``` Store in manifest.json and use instead of global config. ### 8. Tests Required - `RetryCalculatorTest.java`: Test delay calculation, retry eligibility - `RetrySchedulerTest.java`: Test job requeuing with delay - Integration test: Job fails, retries with backoff, eventually succeeds or gives up ## Acceptance Criteria - [ ] Failed jobs retry up to max_retries times - [ ] Retry delay follows exponential backoff - [ ] `retry_on_exit_codes` filter works - [ ] Per-job retry override works - [ ] Retry history is recorded - [ ] Job eventually marked failed after max retries - [ ] Status output shows retry info - [ ] `mvn verify` passes - [ ] Tests have 80%+ coverage ## Implementation Notes Exponential backoff formula: ``` delay = base_delay * (multiplier ^ retry_count) With defaults (30s, 2.0x, max 3): - Retry 1: 30 * 2^0 = 30 seconds - Retry 2: 30 * 2^1 = 60 seconds - Retry 3: 30 * 2^2 = 120 seconds ``` Consider adding jitter to prevent thundering herd: ```java double jitter = ThreadLocalRandom.current().nextDouble(0.8, 1.2); delaySeconds = delaySeconds * jitter; ``` ## Definition of Done - Retries work with exponential backoff - History tracked correctly - Per-job overrides work - All tests pass
daniel added this to the M2: Job Execution milestone 2026-10-04 19:28:24 +00:00
daniel added the execution label 2026-10-04 19:28:24 +00:00
Author
Owner

@daniel-samson commented on 2026-01-21 15:21:06 UTC:

Implemented retry mechanism with exponential backoff:

New Files:

  • src/main/java/com/samsonmedia/barn/jobs/RetryCalculator.java: Calculates retry eligibility and delays with exponential backoff
  • src/test/java/com/samsonmedia/barn/jobs/RetryCalculatorTest.java: Comprehensive tests for retry logic

Updated Files:

  • JobRunner.java: Integrated retry handling - automatically schedules retries for failed jobs
  • JobRepository.java: Enhanced scheduleRetry() to record retry history

Features:

  • Exponential backoff: delay = base_delay * (multiplier ^ retry_count)
  • Default settings: 30s base, 2.0x multiplier, max 3 retries
  • Jitter (±20%) to prevent thundering herd issues
  • Maximum delay cap of 1 hour
  • Configurable retryOnExitCodes filter (empty = retry all non-zero)
  • Per-job retry overrides support
  • Retry history tracking in retry_history file
  • JobResult.retryScheduled field to indicate pending retry

Delay Schedule (with defaults):

  • Retry 1: ~30 seconds
  • Retry 2: ~60 seconds
  • Retry 3: ~120 seconds

All 765 tests pass.

<!-- github-import:comment:3778771966 --> _**@daniel-samson** commented on 2026-01-21 15:21:06 UTC:_ Implemented retry mechanism with exponential backoff: **New Files:** - `src/main/java/com/samsonmedia/barn/jobs/RetryCalculator.java`: Calculates retry eligibility and delays with exponential backoff - `src/test/java/com/samsonmedia/barn/jobs/RetryCalculatorTest.java`: Comprehensive tests for retry logic **Updated Files:** - `JobRunner.java`: Integrated retry handling - automatically schedules retries for failed jobs - `JobRepository.java`: Enhanced `scheduleRetry()` to record retry history **Features:** - Exponential backoff: `delay = base_delay * (multiplier ^ retry_count)` - Default settings: 30s base, 2.0x multiplier, max 3 retries - Jitter (±20%) to prevent thundering herd issues - Maximum delay cap of 1 hour - Configurable `retryOnExitCodes` filter (empty = retry all non-zero) - Per-job retry overrides support - Retry history tracking in `retry_history` file - `JobResult.retryScheduled` field to indicate pending retry **Delay Schedule (with defaults):** - Retry 1: ~30 seconds - Retry 2: ~60 seconds - Retry 3: ~120 seconds All 765 tests pass.
This repo is archived. You cannot comment on issues.