Jobs and retries
A task that ends
A bookstore needs four inventory report shards once. A Deployment tries to keep its application running; a Job instead tracks successful execution of finite work. A Job creates Pods and tracks their progress. An exit code of zero normally signals successful execution, but it does not certify the report contents. The smallest example is a task that prints one line and exits; no Service is required just to run it. The following static fragment belongs inside a Job spec.
Read the indexed Job
In this full illustrative manifest, the controller targets four distinct completion indexes, numbered 0 through 3. The requested concurrency is two. If only one shard is unfinished, one useful attempt remains, although replacement and termination timing can affect observed Pod counts. The program reads its assigned index and prints its shard identity. Its output order is unspecified. The image is intentionally non-deployable; an approved image and lab namespace are prerequisites for any real run. Resource requests and limits bound this tiny task, and the Pod does not need an API token.
apiVersion: batch/v1kind: Jobmetadata: name: catalog-report namespace: batch-studyspec: completions: 4 parallelism: 2 completionMode: Indexed backoffLimit: 3 activeDeadlineSeconds: 120 ttlSecondsAfterFinished: 600 template: spec: restartPolicy: Never automountServiceAccountToken: false securityContext: runAsNonRoot: true runAsUser: 10001 seccompProfile: type: RuntimeDefault containers: - name: report image: example.invalid/bytemind/report:offline command: ["python3", "-c"] args: - 'import os; print("report shard=" + os.environ["JOB_COMPLETION_INDEX"])' securityContext: allowPrivilegeEscalation: false readOnlyRootFilesystem: true capabilities: drop: ["ALL"] resources: requests: cpu: 25m memory: 32Mi limits: cpu: 100m memory: 64MiCompletion is not concurrency
Completions describe the success target, parallelism describes desired simultaneous work. In the default non-indexed mode, successful Pods are interchangeable; indexed mode assigns a shard number. Suppose indexes 0 and 1 are finished and 2 and 3 are running. Two unique indexes remain. If index 1 runs twice successfully, it still represents only one finished shard. Indexed completion is stable from v1.24; modern supported versions provide the JOB_COMPLETION_INDEX environment variable. Check the actual cluster version and API before execution.
Retry boundaries and termination
With Never, a failed Pod is handled by the Job controller; OnFailure can restart a failed container within its Pod. A backoff limit constrains retry failure accounting, not an exact promise of total launches. The active deadline is a separate Job-wide execution boundary: for this unsuspended example, after 120 seconds the controller initiates failure and termination even if retry budget remains. A terminal Failed condition means the Job will not restart itself. For more selective handling, podFailurePolicy can classify failures (requires Never); per-index backoff is stable from v1.33 and can isolate failure budgets by shard. Check version-specific policy details before combining them.
Make the result safe to repeat
A retry can occur after writing a report but before the success status is recorded. Blindly appending a second row corrupts totals. Use a stable business key such as reporting date plus shard, and make writing the same result twice harmless. In a real store, atomic uniqueness or transactional upsert is needed; a dictionary is only an offline illustration. The sample events produce 8 units, not 11, because shard 0 appears twice. Conflicting values for the same key require explicit handling rather than silently overwriting.
rows = {}for key, value in [("day1-0", 3), ("day1-1", 5), ("day1-0", 3)]: if key in rows: assert rows[key] == value rows[key] = valueprint(sum(rows.values())) # 8Inspect and clean up
For an approved future lab, inspect the Job conditions and each Pod associated with its generated job-name label. Check output as well as successful execution. A completion condition indicates controller success, not business correctness. A finished Job can become eligible for removal after its TTL; this example sets ten minutes. Capture diagnostic evidence before cleanup because dependent Pods can be removed too. The following read-only commands are illustrative, require an approved explicit lab context, and were not executed.
kubectl --context bytemind-lab -n batch-study get job catalog-reportkubectl --context bytemind-lab -n batch-study describe job catalog-reportkubectl --context bytemind-lab -n batch-study get pods -l batch.kubernetes.io/job-name=catalog-reportPractice
Use job-cases.json to count unique successful indexes. Then explain why one successful process exit does not establish an accurate report. For a periodic report, the next lesson adds a CronJob schedule to a bounded Job template.
Documentation for further reading: https://kubernetes.io/docs/concepts/workloads/controllers/job/ and https://kubernetes.io/docs/concepts/workloads/controllers/ttlafterfinished/. Examples are static; actual cluster behavior is not tested.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Jobs and retries — knowledge check
Apply the chapter concepts using synthetic offline scenarios.
A report needs six successful shards but only two simultaneous workers. Which settings express that intent?
Indexes 0, 1, 1 and 3 have succeeded for a four-index Job. Which index remains?
A Job reaches its active deadline with unused retry budget. What is expected?
An attempt commits a report and then fails before recording success. What design prevents a repeated effect?
A finished Job has TTL 600. What should an operator infer?