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?

Your stakeholder teams approaching you for different automation requirements such as:
  • 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
For all the above requirements cannot be done with deployment 
Workloads have different execution pattern, they need to start, perform specific task and terminate successfully. Kubernetes provides us two important workload controllers for these scenarios: Job and CronJob  tasks 


All these tasks need to be performed 
A Job object will be used to create one or more Pods and the Job ensures that a specified number of Pod instances will be created and terminates after completion of the Job. There could be finite jobs which will run within given certain timeout values. Job tracks for 'Successful' completion of the required task. Jobs can be run in two variants they can be parallel and also non-parallel.

Kubernetes Job types



There are 3 types of jobs non-parallel jobs [single pod jobs - unless it fails. creates replacement pod when pod goes down] parallel jobs with a fixed completion count parallel jobs with task queue 
Job process life cycle
Kubernetes Job work flow


Use cases of Kubernetes Job:

Use caseExample
Database operationsSchema migration
Data processingCSV and JSON processing
BackupDatabase backup
ReportingMonthly billing reports
MaintenanceExpired-record cleanup
DevSecOpsSecurity and compliance scans

Patterns for Job executions

Kubernetes Jobs can be implemented in 3 different execution patterns    
1. Non-parallel Jobs - A single task runs until it completes successfully.
Example: Generation of Fibonacci number series, execute a database migration, or generate report.
2. Parallel Jobs with fixed completion - A job has predefined number of successful tasks to complete
Example: A process 100[x number] of independent customer order records
3. Parallel Job with Work Queue - Multiple Pods process tasks from a shared work queue.
Example: Several workers (ecommerce) process messages from a queue until all tasks are completed.
The application must coordinate with the queue and determine when the work finished. 

##Example type 1: hundred-fibonaccis.yml
---
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.yml
Now 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
where in the Job description you can observe the attributes such as completion, parallelism 1 means single task, Pod Statuses.
 
On the other terminal which is running in parallel, Observe the pod status change from Running to Completed:
kubectl get po -w 
Pod still exists to get the logs but not in running state
kubectl logs [podname] -- [container] 
We can see the Fibonacci number series printed out from the container logs because it take some time to execute the job.

Fibonacci series printed from kubctl logs command

Important Job Attributes


ParameterPurpose
completionsNumber of successful completions required
parallelismMaximum number of concurrently active Pods
backoffLimitNumber of retries before the Job is considered failed
activeDeadlineSecondsMaximum duration of an active Job
restartPolicyControls container restart behavior
ttlSecondsAfterFinishedAutomatic cleanup after Job completion

For Job, use restartPolicy: Never or OnFailure. choose the policy based on your retry and troubleshooting requirements.

##Example type 2: parallel-job.yaml
---
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.yaml
Check Job list:
kubectl get jobs
Check the Pod:
kubectl get po 
Check the log to see the output of the echo command:
kubectl logs count-pod-xxx 
Counter Job execution output using kubectl logs



Now let's see the interesting part describe the job counter :
kubectl describe jobs counter 
You can observer the Start Time and Pod Statuses from the above command 
 Don't forget to cleanup, that is must do actiondelete job:
kubectl delete jobs counter-job 
no 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 pods 
Once Job is deleted all its relavant resource will be cleaned up automaticall.

Parallel Processing of Jobs

Now let's simulates batch processing scenario. Assume you have 10 independent tasks that need to be processed. We want to run Kubernetes maximum 3 pods concurrently.
Create parallel-job.yaml file as show below:
---
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.yaml
  
Monitor the Pods:
  kubectl get pods -w
  
Check Job status:
kubectl get job parallel-task
Kubernetes 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.

 
Kubernetes Job parallel process
Kubernetes Parallel process of Job -> Pod -> Task -> Completions

 
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.

 Kubernetes provides retry controls through the Job specification. 
 For example: 
spec:
  backoffLimit: 3
  activeDeadlineSeconds: 600
  
  
Here: 
  • 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. 
The Job controller uses exponential backoff when retrying failed Pods. 

Production consideration: Kubernetes retries do not guarantee exactly-once execution. Your application should be idempotent so that repeating an operation does not create duplicate transactions or corrupt data.

Working with CronJob


Job that works like a crontab in Linux systems. Any task that needs to be executed based on the scheduled time then we can use this Kubernetes Object.


Kubernetes CronJob execution flow
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.
##Example CronJob
---
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 cronjob
Inspect its configuration:
kubectl describe cronjob daily-report
The 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
timeZone
Specifies the time zone used to interpret the schedule. This field is stable from Kubernetes v1.27.
concurrencyPolicy: Forbid
Prevents a new Job from starting if a previous Job created by the same CronJob is still running. The scheduled occurrence may be skipped.
startingDeadlineSeconds: 300
Allows a missed execution to start within a five-minute window. Otherwise, that occurrence is skipped.
successfulJobsHistoryLimit: 3
Retains three successful Job objects.
failedJobsHistoryLimit: 2
Retains two failed Job objects.
ttlSecondsAfterFinished: 3600
Requests automatic cleanup of a completed Job after one hour. The TTL controller handles cleanup of finished Jobs and their dependent Pods.
Open in new terminal and run the following command to watch continuously:
watch kubectl get all 
Check the Pod logs: Use the Pod name to view the logs and see the output of the CronJob: kubectl get po ; kubectl logs PODNAME

kubernetes logs cronjob run pod



The schedule field is set to "* * * * *", which means the job will run every minutes.
The job runs a busybox container that prints the given text message.

Check the pods section in the above output

Kubernetes CronJob

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:

  1. Assuming CronJobs provide exactly-once execution - no it is going to execute multiple times as per cron schedule.
  2. Allowing concurrent Jobs without understanding their impact - this may lead to deadlock situation if same object reffer by multiple jobs.
  3. Running unlimited retries for permanently failing tasks - Never comeout better to have a limit on retries.
  4. Forgetting to clean up completed Job objects and Pods - Human error, automate it.
  5. Using the cluster's implicit time zone instead of an explicitly defined time zone - to time zone conflicts.
If you are doing Production design checklist -> Cloud Native Architect point of view:

Design considerationRecommendation
Application designMake tasks idempotent
Retry managementConfigure backoff limits
Execution timeoutSet active deadlines
Parallel executionSet controlled parallelism
SchedulingConfigure explicit time zones
Overlapping runsChoose concurrency policy
SecurityUse dedicated service accounts and least privilege
Container securityUse approved, pinned images and restricted security contexts
Resource managementDefine CPU and memory requests and limits
CleanupConfigure history limits and TTL
ObservabilityCollect logs, events, duration, and failure metrics
External dependenciesImplement timeouts and retry handling
RecoveryProvide 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

Popular Articles

DevOps Weapons

Ansible URI Module Tutorial: Real-World Application Health Checks, REST API Validation and DevOps Automation

Kubernetes cluster configuration in a Virtualbox with vagrant