Background jobs are an important part of many distributed applications. They process scheduled tasks, generate reports, send notifications, import data, clean up records, and perform operations that should not block incoming user requests.
In Kubernetes, these workloads commonly run inside Pods managed by Deployments, Jobs, or CronJobs.
However, a Pod does not have a permanent location in the cluster. Kubernetes may terminate it because of node maintenance, resource pressure, node failure, or scheduling changes. A replacement Pod may then start on another node.
This creates an important challenge for background processing.
What happens if a background job is halfway through processing 10,000 records when its Pod is terminated? Does the replacement Pod start from the beginning? Can the same records be processed twice? What happens if the original Pod completes an operation but fails before recording that completion?
Kubernetes can recreate Pods, but it does not automatically preserve application-level job progress.
To handle these situations safely, background workers need reliable checkpointing, idempotent operations, controlled shutdown, and a way to recover unfinished work.
Understand What Happens When Kubernetes Moves a Pod
Kubernetes schedules Pods onto available nodes based on resource requirements, scheduling rules, and cluster conditions.
A Pod can stop running on its original node for several reasons:
- A node is drained during maintenance.
- A node becomes unavailable.
- The node experiences memory or disk pressure.
- A Pod is evicted because of resource constraints.
- An administrator deletes the Pod.
- A Deployment creates replacement Pods during an update.
A Pod is an ephemeral workload instance. Its local memory and writable container filesystem should not be treated as permanent storage.
For example, consider a background worker that processes customer records:
public class CustomerWorker
{
public async Task ProcessAsync(
CancellationToken cancellationToken)
{
var customers = await GetPendingCustomersAsync();
foreach (var customer in customers)
{
await ProcessCustomerAsync(
customer,
cancellationToken);
}
}
}If the Pod is terminated after processing 400 out of 1,000 customers, the application may lose its in-memory progress.
When another Pod starts, it may retrieve the same pending records and begin processing them again.
This can result in duplicate emails, repeated payments, incorrect database updates, or unnecessary processing.
The solution is to store progress outside the Pod and make each operation safe to retry.
Store Job Progress Outside the Pod
The most important rule for reliable background processing is to avoid keeping the only copy of job progress in application memory.
A worker should be able to stop and restart without losing its understanding of what has already been completed.
A database can be used to maintain job status and processing progress.
For example, consider a table named BackgroundJobs:
CREATE TABLE BackgroundJobs
(
Id BIGINT PRIMARY KEY,
Status VARCHAR(30) NOT NULL,
LastProcessedId BIGINT NULL,
StartedAt DATETIME2 NULL,
CompletedAt DATETIME2 NULL,
UpdatedAt DATETIME2 NOT NULL
);The worker can periodically update LastProcessedId after successfully processing a batch.
A simplified processing method might look like this:
public async Task ProcessJobAsync(
long jobId,
CancellationToken cancellationToken)
{
long lastProcessedId =
await repository.GetLastProcessedIdAsync(jobId);
while (!cancellationToken.IsCancellationRequested)
{
var records = await repository.GetNextBatchAsync(
lastProcessedId,
batchSize: 100);
if (records.Count == 0)
{
break;
}
foreach (var record in records)
{
await ProcessRecordAsync(
record,
cancellationToken);
lastProcessedId = record.Id;
}
await repository.SaveCheckpointAsync(
jobId,
lastProcessedId,
cancellationToken);
}
}If the Pod stops, the next worker can retrieve the last saved checkpoint and continue from that position.
However, checkpointing must be designed carefully.
If the application processes a record successfully but terminates before saving its checkpoint, that record may be processed again.
This is why checkpointing alone is not enough. The processing operation must also be idempotent.
Make Background Operations Idempotent
An idempotent operation produces the same intended result when the same request is executed more than once.
This is essential in distributed systems because failures can happen between performing an operation and recording its completion.
Consider a payment-processing worker.
A dangerous implementation might be:
await paymentGateway.ChargeAsync(order);
await repository.MarkOrderAsPaidAsync(order.Id);Suppose the payment succeeds, but the Pod is terminated before MarkOrderAsPaidAsync completes.
The replacement worker may find the order still marked as pending and attempt another payment.
A safer approach uses an idempotency key that remains the same across retries.
await paymentGateway.ChargeAsync(
order,
idempotencyKey: $"order-{order.Id}");The payment provider must support idempotency keys for this approach to prevent duplicate charges.
For database operations, a unique constraint or transaction can help prevent duplicate processing.
For example:
CREATE TABLE ProcessedMessages
(
MessageId UNIQUEIDENTIFIER PRIMARY KEY,
ProcessedAt DATETIME2 NOT NULL
);Before processing a message, the application checks whether its identifier has already been recorded.
The actual business update and insertion of the processed-message record should be performed within the same database transaction when they belong to the same database.
This prevents the application from committing one operation without recording the corresponding completion.
For external services, database transactions cannot guarantee atomicity across both systems. Use provider-supported idempotency, transactional outbox patterns, or explicit reconciliation where necessary.
Handle Kubernetes Shutdown Signals Gracefully
Kubernetes normally gives a container an opportunity to shut down before forcibly terminating it.
When a Pod is deleted or terminated, Kubernetes initiates a graceful shutdown process. The container receives a termination signal, commonly SIGTERM, and the Pod has a termination grace period before it can be forcibly stopped.
.NET applications should respond to this signal through their hosted-service cancellation mechanism.
A BackgroundService can use the stopping cancellation token to stop accepting new work and finish or safely abandon the current operation.
public class OrderWorker : BackgroundService
{
private readonly ILogger<OrderWorker> logger;
public OrderWorker(
ILogger<OrderWorker> logger)
{
this.logger = logger;
}
protected override async Task ExecuteAsync(
CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
try
{
await ProcessNextBatchAsync(stoppingToken);
}
catch (OperationCanceledException)
when (stoppingToken.IsCancellationRequested)
{
break;
}
catch (Exception exception)
{
logger.LogError(
exception,
"Background processing failed.");
await Task.Delay(
TimeSpan.FromSeconds(5),
stoppingToken);
}
}
logger.LogInformation(
"Background worker is stopping.");
}
private Task ProcessNextBatchAsync(
CancellationToken cancellationToken)
{
// Process a bounded batch of work.
return Task.CompletedTask;
}
}The worker should not start another batch after shutdown has been requested.
It should also pass the cancellation token to database operations and external service calls that support cancellation.
A graceful shutdown is an opportunity to save progress and release resources. It is not a guarantee that the application will always finish its current operation.
A node can fail suddenly, a process can crash, or the container can reach its termination deadline.
Join the conversation! Your thoughts help the community grow.