Course contentsShow
← Cloud and Infrastructure
Lesson 1194 of 2,98923. Kubernetes WorkloadsFree lesson

Job TTL and Automatic Cleanup

Use ttlSecondsAfterFinished to automatically clean up completed or failed Jobs and prevent cluster resource accumulation.

What You'll Learn

You'll learn how to configure automatic cleanup for completed or failed Kubernetes Jobs so they don't clutter your cluster indefinitely.


Why Jobs Need Cleanup

When Jobs finish running—whether they succeed or fail—Kubernetes doesn't delete them automatically by default. This means the Job objects and their associated Pods remain in your cluster. Over time, hundreds or thousands of completed Jobs can accumulate, consuming memory in etcd (the cluster database) and making it harder to monitor active workloads.

Think of it like leaving finished task cards on your desk forever—eventually, you can't find the work that still matters.


The ttlSecondsAfterFinished Field

Kubernetes provides a built-in solution: the TTL (Time To Live) controller. You configure it using the ttlSecondsAfterFinished field in your Job specification.

This field defines how many seconds after a Job finishes (completes successfully or fails) before Kubernetes automatically deletes it along with its Pods.

How It Works

apiVersion: batch/v1
kind: Job
metadata:
  name: cleanup-example
spec:
  ttlSecondsAfterFinished: 100  # Delete 100 seconds after finishing
  template:
    spec:
      containers:
      - name: worker
        image: busybox
        command: ["echo", "Task complete"]
      restartPolicy: Never

In this example, once the Job completes (or fails), it will exist for 100 more seconds before being automatically removed.


Choosing a TTL Value

  • Short TTL (60-300s): Good for frequent, disposable tasks where you don't need logs
  • Longer TTL (3600s+): Allows time to inspect logs and debug issues
  • No TTL set: Jobs remain forever until manually deleted

Key Takeaway: Use ttlSecondsAfterFinished in Job specs to automatically clean up completed or failed Jobs, preventing resource accumulation and keeping your cluster tidy.