Workloads: Deployments, rollouts and jobs · 5 MIN READ

Jobs and CronJobs: batch work with retries, deadlines and schedules

Run Jobs with completions, parallelism, backoffLimit and activeDeadlineSeconds, schedule them with CronJobs and a concurrency policy, trigger a run by hand, and write batch code that is safe to retry.

Not every workload serves requests. Reports, migrations, imports and cleanups run, finish and exit, and a Deployment would restart them forever. A Job runs Pods until enough of them succeed and gives up after a set number of failures or a deadline; a CronJob creates Jobs on a schedule. Both retry, so the code they run must tolerate running more than once.

kubernetes · A MAP OF THE IDEA

  1. Write an idempotent task
  2. Job: completions, backoffLimit
  3. Deadline and TTL
  4. CronJob: schedule, Forbid

Useful when

  • Retries, deadlines and history are declared, not scripted.
  • A CronJob can be run by hand with create job --from.

Watch out

  • A run can happen twice or not at all; design for both.
  • Finished Jobs pile up without TTLs or history limits.

Implementation & operation cost: Idempotent batch code, a retry budget and deadline per Job, and monitoring for failed and missed runs.

01

How a Job runs to completion

A Job creates Pods from its template until completions of them have exited with status 0, running at most parallelism at a time; both default to 1. completionMode: Indexed gives each Pod a JOB_COMPLETION_INDEX from 0 to completions minus 1, a simple way to shard work. The template must set restartPolicy to Never or OnFailure. With Never, a failed container leaves its Pod in Error and the Job creates a new Pod, so every failed attempt keeps its logs. With OnFailure, the kubelet restarts the container inside the same Pod, which is faster but keeps only the previous attempt's logs. A finished Job and its Pods stay until you delete them or ttlSecondsAfterFinished removes them.

02

Retries and deadlines

backoffLimit, 6 by default, is how many failures the Job tolerates; failed Pods and container restarts both count. Between attempts the controller waits with an exponential back-off of 10, 20, 40 seconds and so on, capped at six minutes. When the limit is exceeded, the Job gets the Failed condition with reason BackoffLimitExceeded and its running Pods are terminated. activeDeadlineSeconds bounds the whole run time regardless of retries and fails the Job with reason DeadlineExceeded, which protects you from a task that hangs forever. A podFailurePolicy can fail the Job at once on exit codes that retrying cannot fix, or ignore disruptions such as node drains.

yaml
apiVersion: batch/v1
kind: Job
metadata:
  name: report
spec:
  completions: 4
  parallelism: 2
  backoffLimit: 3
  activeDeadlineSeconds: 300
  ttlSecondsAfterFinished: 3600
  template:
    spec:
      restartPolicy: Never
      containers:
      - name: worker
        image: gopherforge/worker:v1
Read the code

Four successful Pods are needed, two run at a time, at most three failures are tolerated, and the whole Job must finish within five minutes. An hour after it finishes, the TTL controller deletes the Job together with its Pods, so completed runs do not pile up in the namespace.

03

CronJobs: schedule, concurrency and history

A CronJob creates a Job from jobTemplate whenever its schedule matches. The schedule has five fields, minute, hour, day of month, month and day of week, so */15 * * * * means every 15 minutes and 30 2 * * 1-5 means 02:30 on weekdays; macros such as @hourly and @daily work too. Without timeZone, the controller manager's time zone applies, usually UTC. concurrencyPolicy decides what happens if the previous run is still active: Allow runs both, Forbid skips the new one, Replace stops the old one. A run skipped by Forbid can still start late once the old Job ends, unless startingDeadlineSeconds has passed. startingDeadlineSeconds drops runs that could not start in time, for example after a control-plane outage. successfulJobsHistoryLimit (3) and failedJobsHistoryLimit (1) set how many finished Jobs are kept, and suspend: true pauses the schedule.

yaml
apiVersion: batch/v1
kind: CronJob
metadata:
  name: nightly-report
spec:
  schedule: "30 2 * * 1-5"
  timeZone: Europe/Berlin
  concurrencyPolicy: Forbid
  startingDeadlineSeconds: 600
  successfulJobsHistoryLimit: 3
  failedJobsHistoryLimit: 1
  jobTemplate:
    spec:
      backoffLimit: 2
      activeDeadlineSeconds: 3600
      template:
        spec:
          restartPolicy: OnFailure
          containers:
          - name: worker
            image: gopherforge/worker:v1
Read the code

The report runs at 02:30 Berlin time on weekdays, across daylight-saving changes, and never overlaps a run that is still going. If the controller cannot start it within ten minutes of the scheduled time, that run is skipped rather than started late. Each run may retry twice and must finish within an hour.

04

Write batch work that is safe to repeat

Jobs promise at least one attempt, not exactly one. A Pod can be retried after a partial run, a node failure can leave a Pod running while its replacement starts, and the CronJob documentation warns that a schedule can occasionally create two Jobs or none. Make every run idempotent: key the work by its scheduled period, record completion in the same transaction as the work, prefer upserts to blind inserts, and pass idempotency keys to external APIs. Exit non-zero on any failure so the Job retries, and with 0 only after the results are committed. Handle SIGTERM, which arrives on a drain, a deadline or a Replace.

go
// runReport builds the report for one day at most once, however often it runs.
func runReport(ctx context.Context, db *sql.DB, day string) error {
	tx, err := db.BeginTx(ctx, nil)
	if err != nil {
		return err
	}
	defer tx.Rollback()

	res, err := tx.ExecContext(ctx,
		`INSERT INTO report_runs (day) VALUES ($1) ON CONFLICT (day) DO NOTHING`, day)
	if err != nil {
		return err
	}
	if n, _ := res.RowsAffected(); n == 0 {
		return nil // an earlier run already committed this day
	}
	if err := buildReport(ctx, tx, day); err != nil {
		return err
	}
	return tx.Commit()
}
Read the code

The marker row and the report are committed together, so a crash before Commit leaves neither and the retry starts cleanly, while a duplicate run finds the marker and returns without doing the work twice. main calls it with the scheduled day and exits with status 1 on an error, leaving retries to backoffLimit.

05

Try it in the lab terminal

Run a Job that needs four completions two at a time, then a Job whose image always fails, then a CronJob that fires every minute. cluster tick 3m advances virtual time by three minutes, so the schedule fires without waiting. The last command starts a run from the CronJob's template immediately, which is how you test a CronJob or rerun a night that failed.

bash
kind create cluster
cat > report.yaml <<'EOF'
apiVersion: batch/v1
kind: Job
metadata:
  name: report
spec:
  completions: 4
  parallelism: 2
  backoffLimit: 3
  activeDeadlineSeconds: 300
  template:
    spec:
      restartPolicy: Never
      containers:
      - name: worker
        image: gopherforge/worker:v1
EOF
kubectl apply -f report.yaml
kubectl get pods -l job-name=report
kubectl wait --for=condition=Complete job/report --timeout=120s
kubectl get job report
cat > flaky.yaml <<'EOF'
apiVersion: batch/v1
kind: Job
metadata:
  name: flaky
spec:
  backoffLimit: 2
  template:
    spec:
      restartPolicy: Never
      containers:
      - name: worker
        image: gopherforge/worker:fail
EOF
kubectl apply -f flaky.yaml
kubectl wait --for=condition=Failed job/flaky --timeout=180s
kubectl get pods -l job-name=flaky
kubectl events --for job/flaky
cat > cleanup.yaml <<'EOF'
apiVersion: batch/v1
kind: CronJob
metadata:
  name: cleanup
spec:
  schedule: "*/1 * * * *"
  concurrencyPolicy: Forbid
  successfulJobsHistoryLimit: 2
  failedJobsHistoryLimit: 1
  jobTemplate:
    spec:
      backoffLimit: 1
      activeDeadlineSeconds: 50
      template:
        spec:
          restartPolicy: OnFailure
          containers:
          - name: worker
            image: gopherforge/worker:v1
EOF
kubectl apply -f cleanup.yaml
cluster tick 3m
kubectl get cronjob,jobs
kubectl create job cleanup-manual --from=cronjob/cleanup
Read the code

report starts two Pods named report-<id>, and once wait returns, get job shows Complete 4/4. flaky leaves three Pods in Error, the first attempt plus two retries, and its events end with BackoffLimitExceeded: Job has reached the specified backoff limit. After the tick, the CronJob's LAST SCHEDULE is seconds old and its Jobs are named cleanup-<number>, each Complete 1/1; in a real cluster the number is the scheduled time in minutes since the Unix epoch. create job --from prints job.batch/cleanup-manual created.

TAKE THIS WITH YOU

A Job retries Pods until enough succeed, within backoffLimit and activeDeadlineSeconds; a CronJob creates such Jobs on a schedule with an explicit concurrency policy. Because any run may happen twice, design batch work to be idempotent.

Check your understanding

A CronJob runs every 10 minutes with concurrencyPolicy: Forbid. At 00:10 the run that started at 00:00 is still active. What happens at 00:10?

Go to the source

Progress stays in this browser. No account needed.