Kubernetes Jobs are commonly used to execute tasks that need to run until completion. Examples include importing large datasets, generating reports, processing files, running database migrations, and performing scheduled data transformations.

A Job creates one or more Pods to execute the required workload. When a Pod completes successfully, Kubernetes records the completion. If a Pod fails, the Job controller can create another Pod to retry the work.

However, there is an important difference between restarting a Pod and resuming a job.

Suppose a Kubernetes Job processes a file containing one million records. The Pod successfully processes 600,000 records before being evicted because its node needs maintenance. Kubernetes may create a replacement Pod, but the replacement does not automatically know where the previous Pod stopped.

Without application-level recovery, the new Pod may start from the beginning and process the same records again.

This can waste computing resources, increase processing time, and create duplicate database updates or external operations.

To solve this problem, applications need durable checkpoints, reliable progress tracking, and retry-safe processing. Kubernetes manages Pod replacement, while the application manages the recovery of unfinished work.

Understand What Happens When a Job Pod Is Evicted

A Pod can be evicted for several reasons:

  • A node is under memory pressure.
  • A node runs out of available disk space.
  • An administrator drains a node for maintenance.
  • A higher-priority workload requires available resources.
  • The cluster performs infrastructure maintenance.

When an entire Pod fails, the Kubernetes Job controller can create a replacement Pod according to the Job's retry and failure policies.

However, the replacement Pod is a new application process. It does not inherit the previous Pod's in-memory variables, open connections, or temporary processing state.

For example:

C#
public async Task ProcessRecordsAsync(
    CancellationToken cancellationToken)
{
    var records = await GetRecordsAsync();

    foreach (var record in records)
    {
        await ProcessRecordAsync(
            record,
            cancellationToken);
    }
}

If the process stops after processing several thousand records, the next Pod may retrieve the same records and start again.

Kubernetes knows that the previous Pod failed. It does not know which business records were successfully processed.

The application must provide that information through durable storage.

Store Processing Progress Outside the Pod

The first step toward resumable Jobs is storing progress somewhere that survives Pod replacement.

A database is often a good choice because it can store job information, completed records, checkpoints, and processing status.

For example, consider a table that tracks the progress of a file import:

SQL
CREATE TABLE ImportJobs
(
    JobId BIGINT PRIMARY KEY,
    FileName VARCHAR(255) NOT NULL,
    LastProcessedId BIGINT NULL,
    Status VARCHAR(30) NOT NULL,
    UpdatedAt DATETIME2 NOT NULL
);

The LastProcessedId column records the last successfully processed record.

When a replacement Pod starts, it retrieves this value and continues from the next record.

C#
public async Task ResumeImportAsync(
    long jobId,
    CancellationToken cancellationToken)
{
    long lastProcessedId =
        await repository.GetLastProcessedIdAsync(jobId);

    while (!cancellationToken.IsCancellationRequested)
    {
        var records = await repository.GetNextBatchAsync(
            jobId,
            lastProcessedId,
            batchSize: 500,
            cancellationToken);

        if (records.Count == 0)
        {
            break;
        }

        foreach (var record in records)
        {
            await ProcessRecordAsync(
                record,
                cancellationToken);

            lastProcessedId = record.Id;
        }

        await repository.SaveCheckpointAsync(
            jobId,
            lastProcessedId,
            cancellationToken);
    }
}

This implementation processes records in batches and saves progress after each batch.

If the Pod is evicted, the replacement can retrieve the most recent checkpoint and continue processing.

However, checkpointing must be coordinated with the actual processing operation. Saving progress too early can cause records to be skipped, while saving it too late can cause records to be processed again.

Save Checkpoints Atomically

One of the most important decisions in a resumable job is when to save progress.

Consider this sequence:

  1. The worker processes a record.
  2. The worker updates the checkpoint.
  3. The Pod is terminated.

If the processing operation succeeded but the checkpoint update failed, the record may be processed again.

Now consider the opposite sequence:

  1. The worker updates the checkpoint.
  2. The worker starts processing the record.
  3. The Pod is terminated.

The replacement Pod may skip the record even though processing never completed.

For database operations, the business update and checkpoint update should normally happen within the same database transaction.

For example:

C#
public async Task ProcessRecordAsync(
    ImportRecord record,
    CancellationToken cancellationToken)
{
    await using var transaction =
        await dbContext.Database.BeginTransactionAsync(
            cancellationToken);

    var entity = await dbContext.Customers.FindAsync(
        [record.CustomerId],
        cancellationToken);

    if (entity != null)
    {
        entity.Name = record.CustomerName;
    }

    await repository.UpdateCheckpointAsync(
        record.JobId,
        record.Id,
        cancellationToken);

    await dbContext.SaveChangesAsync(
        cancellationToken);

    await transaction.CommitAsync(
        cancellationToken);
}

The example assumes that the business update and checkpoint use the same database connection and transaction.

If they belong to different systems, a normal database transaction cannot guarantee that both operations succeed together. In that situation, use idempotency keys, an outbox pattern, or a separate reconciliation process.

The goal is to make the processing result and its progress record consistent.

Use Persistent Storage for File-Based Processing

Not every background Job processes database records. Some workloads process large files, machine-learning datasets, generated reports, or intermediate results.

In these situations, the application may need to preserve both its progress information and intermediate files.

A container's writable filesystem is not a reliable place for data that must survive Pod replacement.

Kubernetes PersistentVolumes can provide storage beyond the lifetime of an individual Pod.

For example:

YAML
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: job-checkpoints
spec:
  accessModes:
    - ReadWriteOnce
  resources:
    requests:
      storage: 5Gi

A Job can mount the volume:

YAML
apiVersion: batch/v1
kind: Job
metadata:
  name: file-processing-job
spec:
  backoffLimit: 4
  template:
    spec:
      restartPolicy: Never
      containers:
        - name: processor
          image: mycompany/file-processor:latest
          volumeMounts:
            - name: checkpoint-storage
              mountPath: /app/checkpoints
      volumes:
        - name: checkpoint-storage
          persistentVolumeClaim:
            claimName: job-checkpoints

The application can store checkpoint files under /app/checkpoints.

A replacement Pod can access the same persistent storage when the volume can be attached to its new node.

However, storage access modes and the capabilities of the underlying storage provider matter. A ReadWriteOnce volume does not mean that multiple Pods can freely write to it from different nodes.

For distributed processing, object storage or a database may be more appropriate than a shared filesystem.

Also, a persistent volume does not automatically make checkpoint writes safe. The application still needs to write checkpoints atomically, validate them, and recover from incomplete files.

Use Indexed Jobs to Divide Large Workloads

Some background workloads can be divided into independent sections.

For example, a data import may contain ten files, and each file can be processed independently.

Kubernetes Indexed Jobs support this type of workload.

Each Pod receives a completion index that identifies its assigned portion of the work.

Consider this configuration:

YAML
apiVersion: batch/v1
kind: Job
metadata:
  name: data-import-job
spec:
  completions: 10
  parallelism: 3
  completionMode: Indexed
  backoffLimit: 5
  template:
    spec:
      restartPolicy: Never
      containers:
        - name: importer
          image: mycompany/data-importer:latest
          env:
            - name: JOB_INDEX
              valueFrom:
                fieldRef:
                  fieldPath: metadata.annotations['batch.kubernetes.io/job-completion-index']

The application can use the index to determine which portion of the workload it should process.

For example:

C#
string? indexValue =
    Environment.GetEnvironmentVariable("JOB_INDEX");

if (!int.TryParse(indexValue, out int jobIndex))
{
    throw new InvalidOperationException(
        "Job completion index is missing.");
}

await ProcessFileAsync(jobIndex);

Each index represents an independent completion unit.

If the Pod responsible for index 4 fails, Kubernetes can create another Pod for that index. The replacement application must still recover the progress of that particular unit if the work was only partially completed.

Indexed Jobs are useful for parallel workloads, but they do not provide automatic application-level checkpointing.

The application should store progress separately for each index.

Configure Kubernetes Retry Behavior

Kubernetes Jobs provide several options for controlling how failed Pods are handled.

The backoffLimit field controls how many Pod failures are allowed before the Job is considered failed.

For example:

YAML
apiVersion: batch/v1
kind: Job
metadata:
  name: report-generation-job
spec:
  backoffLimit: 4
  template:
    spec:
      restartPolicy: Never
      containers:
        - name: report-generator
          image: mycompany/report-generator:latest

The default failure backoff increases between retries, helping prevent repeated failures from creating excessive workload.

Kubernetes also supports podFailurePolicy, which allows different failure conditions to be handled differently.

For example, certain infrastructure disruptions can be ignored for the purpose of counting failures:

YAML
apiVersion: batch/v1
kind: Job
metadata:
  name: resilient-processing-job
spec:
  backoffLimit: 4
  podFailurePolicy:
    rules:
      - action: Ignore
        onPodConditions:
          - type: DisruptionTarget
  template:
    spec:
      restartPolicy: Never
      containers:
        - name: processor
          image: mycompany/processor:latest

This configuration distinguishes certain disruptions from ordinary application failures.

The PodFailurePolicy feature requires restartPolicy: Never.

Retry policies should not hide application defects. A Job that repeatedly fails because of invalid input or a programming error should eventually stop rather than retry forever.

Also, a replacement Pod may be created while the previous Pod is still terminating, depending on the Job's replacement policy. If overlapping workers could corrupt shared state, consider the podReplacementPolicy: Failed setting where supported, or use application-level leases and fencing to protect the work.

Make Resumed Processing Safe Against Duplicate Execution

A replacement Pod may repeat some operations when the previous Pod stops between completing an operation and saving its checkpoint.

This is normal in distributed processing.

For that reason, the processing logic should be idempotent.

For example, use a unique processing identifier:

SQL
CREATE TABLE CompletedImportRecords
(
    JobId BIGINT NOT NULL,
    RecordId BIGINT NOT NULL,
    ProcessedAt DATETIME2 NOT NULL,
    CONSTRAINT PK_CompletedImportRecords
        PRIMARY KEY (JobId, RecordId)
);

The application can use the unique key to prevent the same record from being committed twice.

When processing external operations, use stable idempotency keys if the external service supports them.

Do not rely only on checking whether a record was processed before starting. Two Pods could check at the same time and both decide to process it.

Use database transactions, unique constraints, or atomic claims to coordinate concurrent workers.

Test Recovery by Deliberately Evicting Pods

A resumable Job should be tested under failure conditions, not only when everything works correctly.

A useful test process is:

  1. Start a Job that processes a large dataset.
  2. Allow it to complete several batches.
  3. Delete its running Pod or simulate a node disruption.
  4. Wait for Kubernetes to create a replacement Pod.
  5. Verify that the replacement reads the last durable checkpoint.
  6. Confirm that completed records are not lost or duplicated.
  7. Verify that the Job eventually reaches the expected completion state.

Useful commands include:

Bash
kubectl get jobs

kubectl get pods -l job-name=data-import-job

kubectl describe job data-import-job

Inspect the logs of the replacement Pod:

Bash
kubectl logs <replacement-pod-name>

Also check the previous Pod's logs when available.

A production recovery test should include failures during processing, during checkpoint updates, and immediately after an external operation succeeds.

These scenarios reveal problems that ordinary successful executions may never expose.

Common Mistakes to Avoid

Mistake

Why it causes problems

Better approach

Assuming a replacement Pod resumes automatically

Kubernetes does not restore application memory

Store durable checkpoints

Saving progress only in local container storage

The replacement Pod may run on another node

Use a database, object storage, or suitable persistent volume

Updating checkpoints before processing completes

Records can be skipped

Coordinate processing and checkpoint updates

Ignoring duplicate execution

Retries can repeat business operations

Use idempotency and unique constraints

Using Indexed Jobs without per-index progress

A replacement may repeat an entire workload partition

Store checkpoints for each index

Allowing unlimited retries

Persistent application errors can consume resources

Configure suitable retry limits

Assuming one Job Pod always runs at a time

Replacement Pods can overlap during termination

Use appropriate replacement policies and application-level coordination

Best Practices for Production Applications

  1. Store job progress in durable storage rather than application memory.
  2. Process large workloads in manageable batches and save checkpoints regularly.
  3. Keep business updates and checkpoint updates in the same transaction whenever they share a database.
  4. Use PersistentVolumes only when the workload genuinely requires filesystem-based persistent state.
  5. Consider Indexed Jobs when work can be divided into independent partitions.
  6. Make processing idempotent so that retrying a completed operation does not create duplicate side effects.
  7. Configure backoffLimit and podFailurePolicy according to the expected failure scenarios.
  8. Protect shared processing state with atomic claims, leases, or database constraints.
  9. Test Pod replacement during different stages of processing.
  10. Monitor checkpoint progress, retry counts, failed Pods, and overall Job completion.

Summary

Kubernetes can recreate a Job Pod after eviction or failure, but it cannot automatically resume the application from the exact point where the previous process stopped.

To make Jobs resumable, applications must store progress outside the Pod, process work in batches, and save checkpoints reliably. Database transactions, persistent storage, and idempotent operations help prevent data loss and duplicate processing.

Indexed Jobs can divide large workloads into smaller independent units, while backoffLimit and podFailurePolicy provide control over infrastructure and application failures.

The most reliable design assumes that any Pod can disappear during processing. When a replacement Pod can retrieve durable progress and safely continue unfinished work, Kubernetes Jobs become much more resilient to eviction, node maintenance, and unexpected failures.