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:

C#
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:

SQL
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:

C#
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:

C#
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.

C#
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:

SQL
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.

C#
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.

Therefore, recovery must still work even when graceful shutdown does not complete.

Configure the Pod Termination Grace Period

Kubernetes provides terminationGracePeriodSeconds to control how long a Pod can remain in its graceful termination phase.

For example:

Code
apiVersion: apps/v1
kind: Deployment
metadata:
  name: background-worker
spec:
  replicas: 2
  selector:
    matchLabels:
      app: background-worker
  template:
    metadata:
      labels:
        app: background-worker
    spec:
      terminationGracePeriodSeconds: 60
      containers:
        - name: worker
          image: mycompany/background-worker:latest

In this example, Kubernetes allows up to 60 seconds for the Pod to terminate gracefully.

The application should be designed so that its shutdown process normally completes within this period.

Do not choose an extremely large grace period as a replacement for checkpointing. A worker that requires several minutes to finish one operation may still be interrupted by an infrastructure failure.

A better design uses bounded batches, regular checkpoints, and retry-safe operations.

Use Kubernetes Jobs for Work That Must Complete

Not every background task should run inside a continuously running Deployment.

A Deployment is suitable for workers that continuously consume messages or process available work.

For finite tasks that must run to completion, Kubernetes Jobs provide a more appropriate workload controller.

For example:

Code
apiVersion: batch/v1
kind: Job
metadata:
  name: customer-import
spec:
  backoffLimit: 4
  template:
    spec:
      restartPolicy: Never
      containers:
        - name: importer
          image: mycompany/customer-import:latest
          command:
            - dotnet
            - CustomerImport.dll

A Job manages Pods for a task that is expected to complete. If a Pod fails or is deleted because of a node failure, the Job controller can create a replacement Pod.

However, the Job controller does not know how much application work was completed before the failure.

The application must still maintain its own progress and make repeated execution safe.

Kubernetes Job retries are not equivalent to resuming application execution from the exact instruction where the previous Pod stopped.

Configure Pod Failure Policies for Infrastructure Disruptions

Kubernetes Jobs support podFailurePolicy, which provides more control over how failed Pods affect retry handling.

This is useful when a Job should retry after infrastructure disruptions without treating those disruptions as application failures.

For example:

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

The DisruptionTarget condition can identify certain Pod disruptions, such as preemption or API-initiated eviction.

The Ignore action prevents matching disruptions from incrementing the Job's backoff failure counter and allows a replacement Pod to be created.

This is useful when the workload should not exhaust its retry allowance because of infrastructure events.

Pod failure policies require restartPolicy to be Never.

They should also be designed carefully. An application failure caused by invalid data or a software defect should not be treated like an infrastructure disruption.

Kubernetes supports other actions, including Count, FailJob, and FailIndex for appropriate Job configurations.

Prevent Two Pods From Processing the Same Job

Another important problem occurs when a replacement Pod starts while the original worker has not completely stopped.

This can happen during node failures, network partitions, or delayed termination.

If both Pods believe they own the same job, they may process the same records simultaneously.

A simple status field is not always enough to prevent this.

Use a distributed locking or lease mechanism to coordinate ownership.

For example, a job record can contain:

SQL
ALTER TABLE BackgroundJobs
ADD
    LockedBy VARCHAR(100) NULL,
    LockExpiresAt DATETIME2 NULL,
    LockVersion BIGINT NOT NULL DEFAULT 0;

A worker acquires the job using an atomic database update.

SQL
UPDATE BackgroundJobs
SET
    LockedBy = @WorkerId,
    LockExpiresAt = DATEADD(SECOND, 60, SYSUTCDATETIME()),
    LockVersion = LockVersion + 1
WHERE Id = @JobId
  AND
  (
      LockExpiresAt IS NULL
      OR LockExpiresAt < SYSUTCDATETIME()
  );

The application must check the affected row count to confirm whether it successfully acquired the lock.

The worker should renew the lease while processing.

The LockVersion value can also be used as a fencing token. Operations that update shared job state should verify that the worker still holds the current version.

This is important because an expired worker may continue running temporarily even after another worker has acquired the lease.

A distributed lock alone does not guarantee that external side effects cannot be duplicated. Combine ownership control with idempotency and transactional processing.

Monitor Interrupted and Repeated Background Jobs

Reliable recovery also requires visibility into what happens when a worker stops.

A production worker should log important events such as:

  • Job started.
  • Batch processing started.
  • Checkpoint saved.
  • Shutdown requested.
  • Job ownership acquired or lost.
  • Processing failed.
  • Job resumed.
  • Job completed.

For example:

C#
logger.LogInformation(
    "Processing job {JobId} from checkpoint {LastId}",
    jobId,
    lastProcessedId);

Include a stable job identifier and worker identifier in logs so that events from different Pods can be connected.

Kubernetes provides useful commands for investigating workload status:

Bash
kubectl get pods -o wide

To inspect a particular Pod:

Bash
kubectl describe pod <pod-name>

To inspect the previous container instance's logs when a container has restarted:

Bash
kubectl logs <pod-name> --previous

For Jobs, inspect their status and associated Pods:

Bash
kubectl get jobs

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

Application-level metrics should also track processing duration, failed batches, retry counts, checkpoint age, and jobs that have not made progress.

These indicators help distinguish a worker that is processing slowly from one that is repeatedly restarting without making progress.

Common Mistakes to Avoid

MistakeWhy it causes problemsBetter approach
Keeping progress only in memoryPod termination loses the processing positionStore checkpoints externally
Assuming a replacement Pod resumes automaticallyKubernetes recreates Pods, not application execution stateImplement application-level recovery
Ignoring duplicate processingRetried operations may create duplicate side effectsUse idempotency keys and unique constraints
Relying only on graceful shutdownInfrastructure failures may prevent shutdown handlers from completingMake every batch recoverable
Using a very long termination grace periodDoes not protect against unexpected node failureUse bounded work and regular checkpoints
Running multiple workers without coordinationTwo Pods may process the same jobUse leases, ownership checks, and fencing
Treating all failures equallyInfrastructure disruptions and software defects need different handlingConfigure appropriate retry policies

Best Practices for Production Applications

  1. Store job state and processing checkpoints in a database or durable message-processing system.
  2. Divide long-running work into bounded batches so that interrupted work can be resumed without repeating everything.
  3. Make processing operations idempotent, particularly when they interact with payment providers, external APIs, or notification services.
  4. Handle cancellation tokens in .NET BackgroundService implementations and stop accepting new work during shutdown.
  5. Configure terminationGracePeriodSeconds according to the application's actual shutdown requirements.
  6. Use Kubernetes Jobs for finite workloads and Deployments for continuously running workers.
  7. Configure podFailurePolicy when infrastructure disruptions should not consume the normal failure retry allowance.
  8. Use distributed leases and fencing tokens when multiple Pods may compete for the same work.
  9. Monitor checkpoints, retries, processing duration, and worker ownership.
  10. Test recovery by deliberately terminating Pods during processing and verifying that the application neither loses work nor creates duplicate side effects.

Summary

Kubernetes can replace a Pod when its node becomes unavailable or when the workload is interrupted. However, replacing a Pod does not automatically restore the application state that existed before termination.

Reliable background processing requires application-level recovery. Store progress outside the container, process work in manageable batches, and make operations safe to execute more than once.

.NET workers should also handle cancellation signals, save progress when possible, and stop accepting new work during graceful shutdown. Kubernetes Jobs and podFailurePolicy can improve infrastructure-level retry behavior, while distributed leases help prevent multiple workers from processing the same task simultaneously.

The most important principle is to treat every Pod as replaceable. When a worker can stop at any point and another worker can safely continue its work, the application becomes much more resilient to node failures, maintenance, and Kubernetes scheduling changes.