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:
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:
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.
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:
- The worker processes a record.
- The worker updates the checkpoint.
- 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:
- The worker updates the checkpoint.
- The worker starts processing the record.
- 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:
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:
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: job-checkpoints
spec:
accessModes:
- ReadWriteOnce
resources:
requests:
storage: 5GiA Job can mount the volume:
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-checkpointsThe 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.
Join the conversation! Your thoughts help the community grow.