InsightsAutomation
Kubernetes CronJobs that run when they should and fail loudly
How to configure scheduled jobs on Kubernetes so that they run in the right time zone, never overlap, stop retrying when retrying cannot help, survive a skipped or doubled run, and raise an alert when they quietly stop succeeding.
Published October 24, 20269 min read
Every cluster collects scheduled jobs: a nightly export, a certificate check, a cleanup of old preview namespaces, a report someone in finance opens every Monday. They are usually written once from a copied example and then forgotten. The failure mode is not a loud crash. It is a job that has not succeeded for three weeks, a run that took longer than its interval and started overlapping with itself, or a schedule that moved by an hour when the clocks changed.
A Kubernetes CronJob has a field for most of these problems, but the defaults are permissive. This article goes through the settings that matter, how the job itself should be written, and how to find out when it stops working.
What a CronJob actually does
A CronJob is a template plus a schedule. At each scheduled time, the CronJob controller in kube-controller-manager creates a Job from spec.jobTemplate, and the Job controller creates Pods and retries them until the Job succeeds or gives up.
Two properties of this design shape everything else:
- Creation is approximate. The documentation says plainly that in some circumstances two Jobs may be created for one scheduled time, or none at all, and that Jobs should therefore be idempotent.
- Changes apply to new runs only. Editing a CronJob changes the template for Jobs created afterwards. A Job that is already running keeps its old spec.
A baseline manifest
This is a starting point for a nightly job. The sections below explain each part.
apiVersion: batch/v1
kind: CronJob
metadata:
name: invoice-export
spec:
schedule: "30 2 * * *"
timeZone: "Europe/Bucharest"
concurrencyPolicy: Forbid
startingDeadlineSeconds: 1800
successfulJobsHistoryLimit: 3
failedJobsHistoryLimit: 3
jobTemplate:
spec:
backoffLimit: 2
activeDeadlineSeconds: 3600
podFailurePolicy:
rules:
- action: FailJob
onExitCodes:
containerName: export
operator: In
values: [42]
- action: Ignore
onPodConditions:
- type: DisruptionTarget
template:
spec:
restartPolicy: Never
serviceAccountName: invoice-export
containers:
- name: export
image: registry.internal/billing/invoice-export:2.3.1
resources:
requests:
cpu: 250m
memory: 256Mi
limits:
memory: 512MiTime zones
Without timeZone, the schedule is interpreted in the local time zone of kube-controller-manager. On a managed control plane you cannot see or change that, and it is not something a schedule should silently depend on. spec.timeZone takes an IANA name such as Etc/UTC or Europe/Bucharest and has been stable since Kubernetes 1.27.
Putting CRON_TZ= or TZ= inside the schedule string was never officially supported, and the API server now rejects it with a validation error. Old manifests that still carry it will fail on the next apply, so search for them before an upgrade.
Choosing a local time zone means accepting daylight saving time. In most of Europe the clocks go back on the last Sunday of October, which in 2026 is 25 October: in Romania, local time runs from 03:00 to 04:00 twice that night, and in March the same hour is skipped. A job scheduled inside that hour can run twice or not at all on those nights. Either schedule outside the transition hour, or use Etc/UTC for anything that does not need to follow office hours.
Overlapping runs
concurrencyPolicy decides what happens when a run is due while the previous one is still going:
| Value | Behavior | Suits |
|---|---|---|
Allow (default) | Starts the new run alongside the old one | Independent, short tasks where overlap is harmless |
Forbid | Skips the new run while the previous one is active | Exports, backups, anything that writes the same data |
Replace | Stops the running Job and starts a new one | Work where only the latest run matters, such as refreshing a cache |
Allow is rarely what a team means. A job that usually takes ten minutes on an hourly schedule will, on a bad day, take seventy, and two copies then work on the same rows. Forbid is the safer default for anything with side effects. The policy only applies to Jobs from the same CronJob, so two CronJobs that touch the same data still need their own coordination, such as a database advisory lock.
Late and missed runs
If the controller cannot create a Job on time, for example during a control plane upgrade, startingDeadlineSeconds sets how late a run may still start. Past that, the run is skipped and counted as failed, and the next scheduled time proceeds as normal. Without the field there is no deadline, so a nightly export could start at 10:00 after an outage, in the middle of the working day.
The field also limits catch-up after long gaps. When the controller finds more than 100 missed schedules for a CronJob, it does not start the Job and logs too many missed start times. That is easy to hit with a schedule of every minute and a cluster that was down for two hours. A starting deadline bounds the window the controller looks at, which keeps the count low.
suspend: true pauses a CronJob without deleting it, which is useful during maintenance. Runs that fall due while it is suspended count as missed. If the CronJob has no starting deadline and is unsuspended, the missed runs are scheduled immediately, which is a surprise when someone unpauses a backup job at 14:00. Set a deadline on anything you expect to suspend.
Retries that make sense
The Job's retry settings apply to each run:
backoffLimitis the number of retries before the Job is marked failed. The default is 6, with an exponential delay between attempts that starts at 10 seconds and is capped at ten minutes. Six retries of a job that fails because a credential expired is half an hour of wasted attempts and log noise. Two or three is enough for most scheduled work.activeDeadlineSecondsbounds the whole run, retries included, and takes precedence overbackoffLimit. Set it below the schedule interval, so a hung run is stopped before the next one is due. WithForbid, a run with no deadline that hangs blocks every future run indefinitely.
podFailurePolicy, stable since Kubernetes 1.31, distinguishes between failures that are worth retrying and failures that are not. In the manifest above:
- Exit code
42fails the Job at once. The application uses it for errors that a retry cannot fix: invalid configuration, a missing permission, a schema it does not understand. - Pods that fail with the
DisruptionTargetcondition, such as a pod evicted during a node drain or preempted by a higher-priority workload, do not count againstbackoffLimit. A cluster upgrade should not burn a job's retry budget.
Rules are evaluated in order and the first match wins; anything that matches no rule is handled normally. A Pod failure policy requires restartPolicy: Never. That is the better choice for scheduled jobs anyway: each attempt becomes a separate Pod with its own logs and exit code, instead of a container restarting in place.
Writing the job to be rerun
Because a run can happen twice, not at all, or be retried halfway through, the work itself has to tolerate all three. The patterns from operational scripts that are safe to rerun apply directly. Two matter most for scheduled jobs:
- Process from a watermark, not from the clock. An export that takes "the last 24 hours" loses a day when a run is skipped and duplicates a day when it runs twice. An export that takes "everything since the last committed watermark" and advances the watermark in the same transaction as its output does neither.
- Write output so that a second write is harmless. Use deterministic object keys, upserts instead of inserts, and idempotency keys on calls to external systems.
Since Kubernetes 1.32, Jobs created by a CronJob carry the annotation batch.kubernetes.io/cronjob-scheduled-timestamp with the originally scheduled time in RFC 3339 format. It shows how late a run started, which is useful when investigating a delayed or duplicated run:
kubectl -n billing get jobs -l app=invoice-export \
-o custom-columns='JOB:.metadata.name,SCHEDULED:.metadata.annotations.batch\.kubernetes\.io/cronjob-scheduled-timestamp,STARTED:.status.startTime'The label selector assumes the Job template sets app: invoice-export in its metadata; add one if yours does not.
Keeping the evidence
successfulJobsHistoryLimit defaults to 3 and failedJobsHistoryLimit to 1. One failed Job is often not enough to see whether a failure is new or has happened every night this week, so keep a few. Old Jobs and their Pods are cheap, and their logs are what on-call reads first.
Avoid setting ttlSecondsAfterFinished in the template of a CronJob that already has history limits. The TTL controller deletes finished Jobs on its own timer, and a failed run can disappear before anyone looks at it, or before the metrics described below have been scraped. Ship logs to a central store so that the history limits are a convenience and not the only record.
Alerting when a job stops succeeding
A failed run is easy to notice. The dangerous case is a job that stops running at all: a suspended CronJob nobody unsuspended, a schedule the controller gave up on, an image that cannot be pulled. The reliable check is the age of the last success, which kube-state-metrics exposes as kube_cronjob_status_last_successful_time:
groups:
- name: cronjobs
rules:
- alert: CronJobNotSucceeding
expr: |
time() - kube_cronjob_status_last_successful_time{namespace="billing", cronjob="invoice-export"}
> 26 * 3600
labels:
severity: ticket
annotations:
summary: "invoice-export has not succeeded in over 26 hours"
- alert: CronJobRunFailed
expr: |
kube_job_failed{condition="true"}
* on (namespace, job_name) group_left (owner_name)
kube_job_owner{owner_kind="CronJob"}
> 0
labels:
severity: ticketSet the threshold per job from its schedule plus a margin: 26 hours for a nightly job, a little over an hour for an hourly one. A shared rule across all CronJobs needs that interval from somewhere, such as a label on the CronJob exported through --metric-labels-allowlist. The second rule catches individual failures as soon as they happen; on its own it says nothing about a job that has stopped running, which is why the first rule exists. Route both to the team that owns the job, not to a shared channel nobody reads.
Jobs that run outside the cluster, or whose success depends on something kube-state-metrics cannot see, such as a file actually arriving at a partner, are better covered by a heartbeat: the job calls a monitoring endpoint at the end of a successful run, and the monitor alerts when the call does not arrive in time.
Testing a change
Do not wait for 02:30 to find out whether a change works. Create a one-off Job from the CronJob's current template and watch it:
job="invoice-export-manual-$(date +%s)"
kubectl -n billing create job "$job" --from=cronjob/invoice-export
kubectl -n billing wait --for=condition=Complete "job/$job" --timeout=1h
kubectl -n billing logs "job/$job"A manual run uses the same template, service account and failure policy, so it is a faithful test. It is also a real run with real side effects, which is one more reason for the job to be idempotent.
Checklist
- Every CronJob sets
timeZone, and nothing is scheduled inside a daylight saving transition hour. - Jobs with side effects use
concurrencyPolicy: Forbid, andactiveDeadlineSecondsis shorter than the schedule interval. startingDeadlineSecondsis set, so late runs do not start at the wrong time of day and unsuspending does not trigger a surprise run.backoffLimitis low,restartPolicyisNever, and a pod failure policy stops retries on permanent errors and ignores disruptions.- The work processes from a watermark and writes idempotently, so a doubled or skipped run is harmless.
- Failed Jobs are kept long enough to investigate, and logs are shipped elsewhere.
- An alert fires when the last success is older than the schedule allows, and it goes to the owning team.