Kubernetes Jobs and CronJobs: Automate Batch Workloads in Production
Learning about Kubernetes Jobs and CronJobs with practical examples. Explore batch processing, parallel Jobs, retry policies, scheduling, time zones, failure handling, and production troubleshooting.
Compatibility: Kubernetes v1.35-1.37
Experiments can be executed on playgrounds available on https://killercoda.com/
Imagine you are the Kubernetes Admin managing multiple hundreds of micro services.
What happens when your app need to run only once?
- Generate monthly billing report
- Process x number customer records - here x can be thousands
- Nightly backup of Database
- Clearing app records
- Execute a data migration after a version release
- Generate daily security compliance reports
| Kubernetes Job types |
![]() |
| Kubernetes Job work flow |
| Use case | Example |
|---|---|
| Database operations | Schema migration |
| Data processing | CSV and JSON processing |
| Backup | Database backup |
| Reporting | Monthly billing reports |
| Maintenance | Expired-record cleanup |
| DevSecOps | Security and compliance scans |
Patterns for Job executions
---
apiVersion: batch/v1
kind: Job
metadata:
name: fibo-100
spec:
template:
spec:
containers:
- name: fib-container
image: truek8s/hundred-fibonaccis:1.0
restartPolicy: OnFailure
backoffLimit: 3
Let's create the Job from the above yaml:
kubectl create -f hundred-fibonaccis.ymlNow let's describe the job and explore what is going on it, if possible watch the pod status in other terminal:
kubectl describe job fibo-100
On the other terminal which is running in parallel, Observe the pod status change from Running to Completed:
kubectl get po -wPod still exists to get the logs but not in running state
kubectl logs [podname] -- [container]
| Fibonacci series printed from kubctl logs command |
Important Job Attributes
| Parameter | Purpose |
|---|---|
completions | Number of successful completions required |
parallelism | Maximum number of concurrently active Pods |
backoffLimit | Number of retries before the Job is considered failed |
activeDeadlineSeconds | Maximum duration of an active Job |
restartPolicy | Controls container restart behavior |
ttlSecondsAfterFinished | Automatic cleanup after Job completion |
---
apiVersion: batch/v1
kind: Job
metadata:
name: counter
spec:
template:
metadata:
name: count-pod-template
spec:
containers:
- name: count-container
image: alpine
command:
- "/bin/sh"
- "-c"
- "for i in 100 50 10 5 1; do echo $i; done"
restartPolicy: Never
To create the counter-job use the following command :
kubectl create -f counter-job.yamlCheck Job list:
kubectl get jobsCheck the Pod:
kubectl get poCheck the log to see the output of the echo command:
kubectl logs count-pod-xxx
| Counter Job execution output using kubectl logs |
kubectl describe jobs counterYou can observer the Start Time and Pod Statuses from the above command
kubectl delete jobs counter-jobno need to delete pod, When a Job deleted automatically removes the corresponding all its pods.
Controlling Job Completions
In some situations you need to run the same job multiple times, we need to define completions: number it under Job-> Specifications (spec section) ---
apiVersion: batch/v1
kind: Job
metadata:
name: hello-job
spec:
completions: 2
template:
spec:
containers:
- name: busybox-container
image: busybox
command: ["echo", "hello Kubernetes job!!!"]
restartPolicy: Never
Observe the number of the Completions on the
watch kubectl get all kubectl get pods kubectl delete job hello-job kubectl get podsOnce Job is deleted all its relavant resource will be cleaned up automaticall.
Parallel Processing of Jobs
---
apiVersion: batch/v1
kind: Job
metadata:
name: parallel-task
spec:
completions: 10
parallelism: 3
backoffLimit: 4
template:
spec:
restartPolicy: Never
containers:
- name: worker
image: busybox:1.37.0
command:
- sh
- -c
- echo Processing task; sleep 10
Apply this manifest file:
kubectl apply -f parallel-job.yamlMonitor the Pods:
kubectl get pods -wCheck Job status:
kubectl get job parallel-taskKubernetes will attempt to achieve 10 successful completions while allowing up to three active Pods at a time. The actual execution speed depends on cluster capacity, scheduling, and Pod completion time.
This approach is useful for data processing, report generation, and independent background tasks.
What happens when Job fails?
In production, batch tasks may fail for several reasons:- Database connectivity issues.
- External API failures.
- Invalid input files.
- Application exceptions.
- Insufficient resources.
- Temporary network failures.
spec: backoffLimit: 3 activeDeadlineSeconds: 600
- backoffLimit: 3 allows up to three counted Pod failures before the Job is marked failed.
- activeDeadlineSeconds: 600 limits the active Job duration to 10 minutes.
Working with CronJob
![]() |
| Kubernetes CronJob execution flow |
Let's do hands-on experiment the cron schedule to run the job every day 2 AM IST (time-zone we can change as per project), daily-report.yaml file
This report generation task simulate the realtime production requirement.
---
apiVersion: batch/v1
kind: CronJob
metadata:
name: daily-report
spec:
schedule: "0 2 * * *"
timeZone: "Asia/Kolkata"
concurrencyPolicy: Forbid
startingDeadlineSeconds: 300
successfulJobsHistoryLimit: 3
failedJobsHistoryLimit: 2
jobTemplate:
spec:
backoffLimit: 2
activeDeadlineSeconds: 600
ttlSecondsAfterFinished: 3600
template:
spec:
restartPolicy: Never
containers:
- name: report
image: busybox:1.37.0
command:
- sh
- -c
- echo Generating daily report; date
resources:
requests:
cpu: 50m
memory: 32Mi
limits:
cpu: 200m
memory: 64Mi
Creating the daily-report CronJob by running the following command:
kubectl create -f daily-report.yaml
Check the CronJob:
kubectl get cronjobInspect its configuration:
kubectl describe cronjob daily-reportThe next scheduled execution will occur at 2 AM Asia/Kolkata time. This can be adjustable as per the project needs.
Understanding the important production parameters
timeZoneSpecifies the time zone used to interpret the schedule. This field is stable from Kubernetes v1.27.
concurrencyPolicy: ForbidPrevents a new Job from starting if a previous Job created by the same CronJob is still running. The scheduled occurrence may be skipped.
startingDeadlineSeconds: 300Allows a missed execution to start within a five-minute window. Otherwise, that occurrence is skipped.
successfulJobsHistoryLimit: 3Retains three successful Job objects.
failedJobsHistoryLimit: 2Retains two failed Job objects.
ttlSecondsAfterFinished: 3600Requests automatic cleanup of a completed Job after one hour. The TTL controller handles cleanup of finished Jobs and their dependent Pods.
watch kubectl get allCheck the Pod logs: Use the Pod name to view the logs and see the output of the CronJob: kubectl get po ; kubectl logs PODNAME
FAQ on Job and CronJob
Q1. What happens if a Job Pod fails?
The Job controller can create replacement Pods according to its retry policy and backoff configuration. The number of counted failures is controlled by backoffLimit.
Q2. What is the difference between a Job and a CronJob?
A Job executes a finite task. A CronJob creates Jobs according to a recurring schedule.
Q3. Can a CronJob run every minute?
Yes. Take an example, */1 * * * * schedules a Job every minute. Consider execution duration, concurrency, API load, and resource consumption before using frequent schedules.
Q4. Why is my CronJob not running at the expected local time?
Check the .spec.timeZone field. If it is not specified, the schedule is interpreted using the local time zone of the kube-controller-manager.
Q5. How do I prevent multiple CronJob executions from overlapping?
Use concurrencyPolicy: Forbid. Also implement application-level locking if concurrent execution could corrupt data.
Q6. Does deleting a CronJob delete completed Jobs?
Deleting a CronJob does not automatically mean all Jobs it previously created are deleted. Review owner references and cleanup requirements.
Q7. What is the purpose of ttlSecondsAfterFinished?
It enables automatic cleanup of a finished Job and its dependent Pods after the specified number of seconds.
Q8. Does a CronJob guarantee exactly-once execution?
No. Scheduling is approximate. Duplicate or missed Job creation can occur under certain conditions. Design tasks to be idempotent and safe to retry.
Q9. What is the difference between backoffLimit and activeDeadlineSeconds?
backoffLimit controls the number of counted failures before the Job is considered failed. activeDeadlineSeconds limits how long the Job can remain active.
Q10. Can I execute a CronJob manually?
Yes. Use kubectl create job --from=cronjob/[name] to create an independent Job from its template.
Don't do these common mistakes:
- Assuming CronJobs provide exactly-once execution - no it is going to execute multiple times as per cron schedule.
- Allowing concurrent Jobs without understanding their impact - this may lead to deadlock situation if same object reffer by multiple jobs.
- Running unlimited retries for permanently failing tasks - Never comeout better to have a limit on retries.
- Forgetting to clean up completed Job objects and Pods - Human error, automate it.
- Using the cluster's implicit time zone instead of an explicitly defined time zone - to time zone conflicts.
| Design consideration | Recommendation |
|---|---|
| Application design | Make tasks idempotent |
| Retry management | Configure backoff limits |
| Execution timeout | Set active deadlines |
| Parallel execution | Set controlled parallelism |
| Scheduling | Configure explicit time zones |
| Overlapping runs | Choose concurrency policy |
| Security | Use dedicated service accounts and least privilege |
| Container security | Use approved, pinned images and restricted security contexts |
| Resource management | Define CPU and memory requests and limits |
| Cleanup | Configure history limits and TTL |
| Observability | Collect logs, events, duration, and failure metrics |
| External dependencies | Implement timeouts and retry handling |
| Recovery | Provide safe manual re-execution procedures |
Conclusion
Kubernetes Jobs and CronJobs are essential components of cloud-native batch processing.
They help platform engineering teams automate finite workloads without maintaining continuously running application Pods.
As a Cloud Native Architect, the important part is not just scheduling a task. It is designing a reliable execution strategy that considers retries, parallelism, time zones, concurrency, resource management, security, and recovery.
Whether you are running a database backup, processing millions of records, or generating compliance reports, Kubernetes Jobs and CronJobs provide a declarative way to manage these workloads.
Keep learning, keep automating, and keep orchestrating!



Comments