Jobs and CronJobs: Batch Workloads, Retries, and Cleanup
Kubernetes cronjob and Job guide: backoffLimit, parallelism, deadlines, TTL clean-up, schedules, time zones and concurrency policy.
backoffLimit and activeDeadlineSeconds so failures stop, a pod failure policy so non-retryable errors do not retry, ttlSecondsAfterFinished so finished Jobs are cleaned up, and on CronJobs an explicit timeZone and concurrencyPolicy. The task itself must be idempotent, because Kubernetes guarantees at least once, not exactly once.
A nightly invoice export runs as a CronJob. One night the export takes longer than 24 hours because a database index was dropped, and the next night’s run starts while the first is still going. Both write to the same files. Another CronJob fails on a bad record, retries six times and sends six partial reports to finance. The cluster’s job history slowly fills with thousands of completed pods. Each problem is a default nobody revisited.
A Job is a workload that creates pods and tracks their successful completion, unlike a Deployment, which keeps pods running forever. A CronJob creates a Job from a template on a cron schedule. Both are built on the same controller model described in the workload model article.
A well-configured Job
apiVersion: batch/v1
kind: Job
metadata:
name: reindex-search-2024-08-20
namespace: search
spec:
backoffLimit: 3 # retry failed pods at most 3 times
activeDeadlineSeconds: 3600 # give up after an hour, however many retries remain
ttlSecondsAfterFinished: 86400 # delete the Job and its pods a day after it finishes
template:
spec:
restartPolicy: Never
containers:
- name: reindex
image: ghcr.io/acme/search-tools:3.2.0
command: ["python", "-m", "tools.reindex", "--batch-size", "500"]
resources:
requests: { cpu: 500m, memory: 512Mi }
limits: { memory: 1Gi }
| Setting | Default | Why change it |
|---|---|---|
backoffLimit |
6 | Six retries with exponential backoff may run for a long time and repeat side effects |
activeDeadlineSeconds |
None | Without it, a hung Job runs forever |
ttlSecondsAfterFinished |
None | Finished Jobs and their pods otherwise stay until someone deletes them |
restartPolicy |
Must be Never or OnFailure |
Never creates a new pod per retry, keeping logs of each failed attempt; OnFailure restarts the container in the same pod |
Retries that understand errors
Not every failure deserves a retry. A pod evicted during a node upgrade should simply run again; an invalid input file will fail every time. A pod failure policy, generally available in Kubernetes 1.31 released last week, lets you decide by exit code or pod condition:
spec:
backoffLimit: 3
podFailurePolicy:
rules:
- action: FailJob # do not retry bad input
onExitCodes:
containerName: reindex
operator: In
values: [2]
- action: Ignore # disruptions do not count against backoffLimit
onPodConditions:
- type: DisruptionTarget
Have your program exit with a distinct code for permanent failures, and the Job fails fast instead of burning retries. The Ignore rule means node drains and preemptions no longer use up the retry budget.
Parallel and indexed Jobs
spec:
completions: 20
parallelism: 5
completionMode: Indexed
This runs 20 pods in total, at most 5 at a time. With completionMode: Indexed, each pod receives a stable index from 0 to 19 in the JOB_COMPLETION_INDEX environment variable, so pod 7 can process shard 7 of the data without any external work queue. Indexed Jobs also support backoffLimitPerIndex, beta since 1.29, so one bad shard fails on its own without exhausting retries for all the others.
For work items that are not known in advance, run several workers with parallelism and let them pull tasks from a queue such as Redis, SQS or RabbitMQ until it is empty.
CronJobs
apiVersion: batch/v1
kind: CronJob
metadata:
name: invoice-export
namespace: billing
spec:
schedule: "30 2 * * *"
timeZone: "Asia/Kolkata"
concurrencyPolicy: Forbid
startingDeadlineSeconds: 600
successfulJobsHistoryLimit: 3
failedJobsHistoryLimit: 5
jobTemplate:
spec:
backoffLimit: 2
activeDeadlineSeconds: 7200
template:
spec:
restartPolicy: Never
containers:
- name: export
image: ghcr.io/acme/billing-api:2.0.0
command: ["node", "dist/jobs/export-invoices.js"]
timeZone, stable since Kubernetes 1.27, makes the schedule follow an IANA time zone. Without it, schedules run in the controller manager’s time zone, usually UTC, which is a classic source of “why did the 2 a.m. job run at 8:30?”concurrencyPolicy:Allow(the default) lets runs overlap;Forbidskips a run while the previous one is still going;Replacestops the old run and starts the new one. Most jobs that write data wantForbid.startingDeadlineSecondslimits how late a missed run may start, for example after a control plane outage. Without it, a CronJob that missed more than 100 schedules stops scheduling altogether and logs an error.- History limits keep the last few Jobs for debugging while cleaning up older ones.
To run a CronJob immediately, for testing or to rerun a failed night, create a Job from its template: kubectl create job invoice-export-manual --from=cronjob/invoice-export. Set suspend: true to pause a schedule without deleting it.
At least once, so be idempotent
Kubernetes can run a Job’s pod more than once: after a retry, after a node failure where the first pod’s fate is unknown, and in rare cases a CronJob can create two Jobs for one schedule. Design every batch task to be safe to repeat: upsert instead of insert, write output to a path keyed by the run date and replace it atomically, record completed work so a rerun skips it, and use idempotency keys when calling external APIs that send emails or charge cards.
Sidecars and Jobs
A Job is complete when all of its pods’ containers exit. Sidecars such as service mesh proxies or log shippers used to keep running forever, so the Job never finished. Native sidecar containers, enabled by default since Kubernetes 1.29, solve this: declare the sidecar as an init container with restartPolicy: Always, and Kubernetes stops it once the main container exits.
Monitoring batch work
A CronJob that silently stops running is one of the hardest failures to notice. Alert on two things, both available from kube-state-metrics: Jobs that end in a failed state, and the time since each CronJob’s last successful run exceeding its expected interval. The second catches suspended schedules, missed deadlines and jobs that were deleted by accident. For critical jobs, a dead man’s switch service that expects a ping at the end of each successful run is a simple extra layer.
Frequently Asked Questions
What is the difference between a Job and a CronJob in Kubernetes?
A Job runs one or more pods until a task completes successfully, retrying failures up to a limit. A CronJob creates a new Job from a template on a cron schedule, with controls for time zone, overlapping runs and history.
How do I stop CronJob runs from overlapping?
Set concurrencyPolicy: Forbid, which skips a scheduled run while the previous Job is still running, or Replace, which stops the running Job and starts the new one. The default, Allow, lets runs overlap.
How do I clean up completed Jobs automatically?
Set ttlSecondsAfterFinished on the Job, or in a CronJob’s jobTemplate, and Kubernetes deletes the Job and its pods that many seconds after it finishes. CronJobs also keep only as many Jobs as successfulJobsHistoryLimit and failedJobsHistoryLimit allow.
How do I run a CronJob manually?
Run kubectl create job NAME –from=cronjob/CRONJOB_NAME. It creates a Job from the CronJob’s template immediately without changing the schedule.
Finite work, explicit limits
Batch workloads fail differently from services: they hang, they overlap, they retry with side effects, and they quietly stop. Give every Job a retry budget, a deadline and a cleanup TTL, give every CronJob a time zone and a concurrency policy, make the task idempotent, and alert on the absence of success as well as the presence of failure. For the full reference, see the CronJob documentation and the Job documentation. Related reading on this site: StatefulSets and DaemonSets and requests and limits.
Originally posted on 20 August 2024 and post last modified on 20 August 2024