How to monitor Kubernetes CronJobs and catch missed or failed runs

Kubernetes CronJobs fail quietly: skipped schedules, pods that error out, jobs that hang. How to inspect them with kubectl and alert with a heartbeat ping.

· 7 min read · By the Spot Downtime team

A Kubernetes CronJob looks like a more reliable cron: it is declarative, it logs, and it retries. It still fails quietly. A job that errors out leaves a failed pod and nothing else. A CronJob that was suspended, or whose schedule was skipped, leaves no trace at all. Nobody gets a message unless you build one.

This post covers how a CronJob turns into pods, the settings that decide what happens when something goes wrong, the kubectl commands to investigate, and how to add an alert that fires when a run does not report success.

CronJob, Job, Pod: where failures happen

A CronJob creates a Job on schedule, and the Job creates pods. A failure can occur at each level:

  • The CronJob never creates a Job. It is suspended, the schedule is wrong, or the controller skipped the run.
  • The Job is created but the pod never runs. The pod is stuck in Pending (no capacity, an unbound volume) or ImagePullBackOff.
  • The pod runs and fails. A non-zero exit, an out-of-memory kill or a crash. The Job retries up to backoffLimit times and then is marked failed.
  • The pod runs and never finishes. It hangs on a lock or a network call. Without a deadline it runs forever.

A CronJob with sensible limits

yaml
apiVersion: batch/v1
kind: CronJob
metadata:
  name: nightly-report
spec:
  schedule: "0 2 * * *"
  timeZone: "Etc/UTC"
  concurrencyPolicy: Forbid
  startingDeadlineSeconds: 600
  successfulJobsHistoryLimit: 3
  failedJobsHistoryLimit: 5
  jobTemplate:
    spec:
      backoffLimit: 2
      activeDeadlineSeconds: 3600
      template:
        spec:
          restartPolicy: Never
          containers:
            - name: report
              image: example/report:1.8.0
              command: ["/app/run-report"]
  • timeZone pins the schedule. Without it, the schedule is read in the time zone of the controller manager, which is usually UTC but is not something you set. See cron time zone and DST pitfalls.
  • concurrencyPolicy: Forbid skips a run if the previous one is still active. Allow (the default) starts overlapping runs, and Replace kills the old one. Pick on purpose; see overlapping cron runs.
  • startingDeadlineSeconds is how late a run may start before it counts as missed. If the controller was down or the cluster was busy past that window, the run is skipped and not retried.
  • activeDeadlineSeconds kills a Job that runs too long, so a hung pod cannot block every future run under Forbid.
  • The history limits control how many finished Jobs are kept. Keep a few failed ones so you can read their logs.

Investigate with kubectl

bash
# Is the CronJob suspended? When did it last schedule a run?
kubectl get cronjob nightly-report
# NAME            SCHEDULE    TIMEZONE   SUSPEND   ACTIVE   LAST SCHEDULE   AGE

# Recent Jobs it created
kubectl get jobs --sort-by=.metadata.creationTimestamp

# Why did a Job fail? Look at Events and the pod status
kubectl describe job nightly-report-28831200

# Logs of the pods a Job ran, including failed ones
kubectl logs job/nightly-report-28831200 --all-containers

# Run the job right now from the CronJob template
kubectl create job --from=cronjob/nightly-report manual-test-1

Read the output top-down. A true in SUSPEND explains a job that never runs. A LAST SCHEDULE that is old means the CronJob is not creating Jobs. If Jobs exist, kubectl describe job and its pods show events such as BackoffLimitExceeded or DeadlineExceeded, and kubectl describe pod shows scheduling and image-pull problems and the Last State of the container (for example OOMKilled, exit code 137).

kubectl create job --from=cronjob/... is the quickest way to reproduce a failure and to test your alert, without waiting for the next schedule.

Common causes

  • Pod stuck Pending: resource requests that no node can satisfy, or a PersistentVolumeClaim that is not bound.
  • ImagePullBackOff: a wrong tag, or missing registry credentials in imagePullSecrets.
  • OOMKilled: the memory limit is lower than the job needs. Compare with Linux out of memory.
  • Works in a shell, fails in the pod: missing environment variables, secrets or network policies. It is the same family of problem as cron jobs that work manually but fail in cron.

Why cluster-side signals are not enough

You can alert on metrics such as failed Job counts, if you run a metrics stack that exposes them. That catches jobs that run and fail. It does not catch a CronJob that was suspended, one deleted by a bad deploy, or a cluster that is down, because there is nothing to count. The failure is an absence, and absences are only visible from outside.

Add a heartbeat ping

Have the job report success to an external endpoint that alerts when a report does not arrive on time. This is the same approach as in how to monitor cron jobs. In Spot Downtime, a heartbeat monitor gives you a ping URL; the job requests it on success and requests the same URL with /fail appended on failure. See how to set up a heartbeat monitor for the details.

yaml
containers:
  - name: report
    image: example/report:1.8.0
    env:
      - name: HEARTBEAT_URL
        valueFrom:
          secretKeyRef: { name: heartbeat, key: url }
    command: ["/bin/sh", "-c"]
    args:
      - |
        if /app/run-report; then
          curl -fsS -m 10 --retry 3 "$HEARTBEAT_URL"
        else
          code=$?
          curl -fsS -m 10 "$HEARTBEAT_URL/fail" || true
          exit $code
        fi

The ping happens only when the report command succeeds, and the original exit code is preserved so Kubernetes still records the Job as failed. The image needs curl (or wget); if you use a minimal image, a second container is awkward because containers in a Job pod run concurrently, so add curl to the image or call the URL from your application code.

Set the monitor's expected interval to the CronJob's schedule and the grace period to longer than the normal run time plus startup delay, since a pod may wait for scheduling or an image pull. Heartbeat grace period and interval covers how to choose them.

Test both failure paths

Run kubectl create job --from=cronjob/nightly-report manual-test-1 with the command temporarily failing and check that the /fail ping alerts at once. Then suspend the CronJob with kubectl patch cronjob nightly-report -p '{"spec":{"suspend":true}}' and confirm the missed heartbeat alerts after the grace period. Set suspend back to false afterwards.

Checklist

  • The CronJob sets timeZone, concurrencyPolicy, startingDeadlineSeconds and activeDeadlineSeconds.
  • Failed Jobs are kept long enough to read their logs.
  • The job pings a heartbeat on success and on failure.
  • The heartbeat interval and grace period match the schedule and the run time.
  • You have tested a failed run and a suspended CronJob.

Check the schedule first

Cron expression explainerPaste the schedule from your CronJob and read in plain language when it will run.

Get new guides by email

Practical posts on monitoring, outages, error fixes and on-call, when they're published. No spam.

Unsubscribe from any email with one click. See our privacy policy.

Keep reading