Automatic Cleanup for Finished Jobs

A Job has finished its work, yet the Job and all its Pods are still there in the cluster. How long do they stay there, from which moment is the wait counted, and what removes the Pods along with the Job?

Play the animation 5 steps, animated, plays on a computer or a tablet

Automatic Cleanup for Finished Jobs, Kubernetes diagram

Automatic Cleanup for Finished Jobs, step by step

  1. Both Pods exit 0, so the Job condition becomes Complete and .status.completionTime is stamped at that instant. Finishing removes nothing. The Job object and both Pods stay in the API by default, so kubectl logs and kubectl describe still answer once the run is over. A CronJob prunes its finished Jobs by count, while a bare Job like this one has no such limit.

    Play from step 1
  2. The ttl-after-finished controller inside kube-controller-manager watches Jobs, and it only looks at ones that have already finished. This Job now reports Complete, so it is picked up, while a Job that is still running is passed over whatever the spec says. With the field at 0, a Job is eligible the moment it finishes. With it unset, this controller never touches the Job.

    Play from step 2
  3. The timer starts when the Job finishes, not when it was created. With ttlSecondsAfterFinished at 100, the Job becomes eligible for removal 100 seconds after the completion stamp of 12:00:31, which is 12:02:11. It is 12:01:04 now, 33 of those 100 seconds have gone, and nothing happens yet.

    Play from step 3
  4. At 12:02:11 the controller compares its own clock against the timestamp stored in the Job, finds the TTL expired and deletes the Job through the API. That comparison makes the TTL sensitive to time skew: clocks should differ very little, but skew in the cluster can make the control plane clean a Job up at the wrong time.

    Play from step 4
  5. The delete asks for propagationPolicy Foreground, a cascading deletion. Both Pods carry an ownerReference back to Job pi, so the garbage collector deletes them first and removes the Job object only once they are gone. Neither Pod was counted or aged on its own here: they go because their owner is being deleted. The run leaves kubectl get pods and nothing of it remains on the Node.

    Play from step 5

Sources