Kubernetes Jobs and CronJobs: Batch Workloads Done Right
Kubernetes Jobs and CronJobs run finite batch work to completion instead of keeping Pods alive forever. This guide sets the production contract for completions, parallelism, backoffLimit, deadlines, TTL cleanup, CronJob concurrency, and idempotent retries, with a decision table, valid YAML, and a troubleshooting matrix for busy engineers.
Introduction
Kubernetes Jobs and CronJobs run work that must finish, not services that must stay up. A Job creates Pods until a required number exit successfully, and a CronJob creates Jobs on a schedule. Set completions, retries, deadlines, cleanup, and overlap rules explicitly, or defaults will decide production behaviour for you.
Consider an illustrative composite drawn from common production reviews, not a named incident. A team runs a nightly export as a Deployment with one replica because that was the manifest they already had. The export finishes, the container exits with code 0, and the Deployment starts it again. The second run appends a second copy of the data, the third run does the same, and the morning report reads duplicated rows. Nothing crashed, no alert fired, and every Pod looked healthy. The failure was a controller mismatch: the team asked for a process that stays up when the work needed a process that ends.
The scheduled version of the same composite is quieter. A CronJob fires a billing sync every hour with default settings. One slow run takes seventy minutes, the next scheduled run starts anyway, and both write to the same tables. A week later the control plane is briefly unavailable, several schedules are missed, and nobody notices until a customer asks why an invoice is missing. Both stories share one root cause. Batch work has a definition of done, a retry budget, a time budget, and an overlap rule, and none of those were written down.
This is lesson 7 of the Kubernetes Roadmap Series, in Module 3 on workload controllers. The previous lesson covered Kubernetes Pod lifecycle: Pending, Running, CrashLoop and termination, which explains what a Pod phase means while work runs. This lesson builds on that foundation: once you can read a Pod lifecycle, the next question is who counts a successful exit, who retries a failure, and who stops the work when it runs too long. That counting and stopping is exactly what the Job and CronJob controllers do.
The 5-minute takeaway
A Job wants a number of successful Pod exits; a CronJob wants Jobs on a timetable. Write the contract before you ship: completions and parallelism for how much work runs at once, backoffLimit for how many failures you tolerate, activeDeadlineSeconds for how long one run may take, ttlSecondsAfterFinished so finished work cleans itself up, and a restartPolicy you chose on purpose. For scheduled work, add a timezone, a concurrencyPolicy that matches whether runs may overlap, and a startingDeadlineSeconds so missed schedules do not pile up. Then make the code idempotent, because retries and duplicate schedule ticks are normal behaviour, not rare accidents. Alert on the age of the last successful run, not only on failed Pods.
1. Kubernetes Jobs and CronJobs: define done before you pick a controller
Choose Kubernetes Jobs and CronJobs when a successful exit is the goal. Use a Job for one finite run, a CronJob for the same run on a timetable, a Deployment for a process that must keep serving, and a queue worker when work arrives continuously and each item needs individual acknowledgement.
The single question that selects the controller is what an exit code 0 means. For a web server, a Pod that exits is a failure to repair, so a Deployment replaces it. For a database migration, a Pod that exits with code 0 is the point of the exercise, so a Job counts it and stops. Teams get this wrong in both directions. A migration wrapped in a Deployment reruns forever. A queue consumer wrapped in a Job stops after the first Pod exits cleanly and never drains the next batch of messages. The manifest can look almost identical in both cases; the difference is the promise the controller makes about Pod exits.
A Job promises a count of successes. It creates Pods from a template, watches them, and keeps creating replacements until the required number have terminated successfully or the failure budget is spent. A CronJob promises a timetable. It holds a cron schedule and a Job template, and for each tick it creates a Job, which then makes the same success-counting promise. That two-level structure matters during incidents: a CronJob problem is usually a scheduling problem, while a Job problem is usually an execution problem, and the fix lives in different fields.
A queue worker is the fourth option teams forget. When work arrives continuously, items are independent, and each item needs its own retry and acknowledgement, a long-running Deployment pulling from a queue is usually a better fit than a Job with a fixed completion count. Jobs suit work with a known total: process these files, migrate this schema, render these shards. Queues suit work with no natural total. Choosing between them is an architecture decision about where the work list lives, not a YAML preference. The controller comparison for always-on workloads is covered separately in Deployment vs StatefulSet vs DaemonSet; this article stays on batch semantics.
| Controller | Goal | Pod exits with code 0 | Use it for | Watch out for |
|---|---|---|---|---|
| Job | A set number of successful completions, then stop | Counted toward completions | Migrations, backfills, one-off imports, sharded processing | Retries repeat side effects unless the code is idempotent |
| CronJob | One Job per schedule tick | The Job completes; the next tick creates a new Job | Nightly backups, reports, syncs, cleanup tasks | Overlapping runs and missed schedules need explicit policy |
| Deployment | A set number of Pods running at all times | Treated as a Pod to replace | APIs, web servers, always-on consumers | Finished batch work restarts forever |
| Queue worker (Deployment) | Drain a queue continuously | Restarted; per-item state lives in the queue | Message processing, webhooks, event handling | Needs queue-level retries, visibility timeouts, and dead-letter handling |
Read the table from the second column. If your work has a finish line you can state in one sentence, a Job expresses it. If that finish line recurs on a timetable, a CronJob expresses it. If there is no finish line, stop reaching for batch controllers and run a service.
2. Kubernetes Jobs and CronJobs: the Job contract field by field
A production entry in Kubernetes Jobs and CronJobs needs five explicit decisions: how many successes finish the work, how many Pods run at once, how many failures end it, how long one run may take, and how long finished objects stay around for inspection afterwards.
The manifest below is the smallest honest Job contract. Every field is there because a default would otherwise make the decision silently. The image name is an example; replace it with your own registry path and a pinned tag or digest your pipeline controls.
Walk the fields in the order an incident will ask about them. completions: 1 says one successful Pod exit finishes the Job. parallelism: 1 says at most one Pod runs at a time. backoffLimit: 3 says three failed attempts mark the Job Failed instead of retrying forever; the documented default is 6, which is a long time to wait before a human hears about a broken export. activeDeadlineSeconds: 3600 gives the whole Job a one-hour wall-clock budget; past that, the Job fails and its Pods are terminated. ttlSecondsAfterFinished: 86400 deletes the finished Job and its Pods after one day, so logs stay readable through the next business day and objects do not accumulate forever.
The Pod template carries two decisions people miss. restartPolicy must be Never or OnFailure in a Job; Always is rejected because a Job Pod that succeeds must not restart. Resource requests matter more for batch work than for services, because the scheduler uses them to decide whether a large export Pod fits alongside production traffic. A batch Pod with no requests is a Pod that can land anywhere and starve anything. If the declarative style itself is new, the earlier series lesson on your first Kubernetes Deployment, imperative vs declarative covers how templates and selectors work; the Job template follows the same rules with a different controller promise.
Two habits separate reliable batch manifests from fragile ones. First, name outputs deterministically. The export above writes to a path containing the run date, so a retry overwrites the same destination instead of inventing a second one. Second, pass the run identity as an argument or environment variable rather than reading the wall clock inside the container. A retried Pod that computes "today" at runtime can process a different partition from the attempt that failed, and the Job will report success for the wrong day.
3. Kubernetes Jobs and CronJobs: completions and parallelism patterns
In Kubernetes Jobs and CronJobs, completions counts required successes and parallelism caps concurrent Pods. One completion with one Pod is a single run, many completions with capped parallelism is fixed batch work, and parallelism without completions is a work queue drained until empty.
Three patterns cover nearly every batch workload. The single-run pattern sets completions: 1 and parallelism: 1. One Pod runs the migration, the import, or the report; failures retry within the backoff budget. Most production Jobs are this pattern, and most production mistakes come from dressing a single run up as something parallel before the work is actually partitionable.
The fixed-count pattern sets a total and a concurrency cap, for example completions: 12 with parallelism: 3. The controller runs three Pods at a time and starts a replacement as each succeeds, until twelve successes accumulate. This pattern needs the work split into twelve equivalent units, and each Pod must know which unit it owns. Without that assignment, twelve Pods all process the same first unit and the Job reports success over duplicated work.
Indexed Jobs solve the assignment problem. With completionMode: Indexed, each Pod receives a stable index from 0 to completions minus 1, exposed through the JOBCOMPLETIONINDEX environment variable and the Pod hostname pattern. Pod 4 processes shard 4, every time, including on retries. That stability is what makes sharded backfills and parallel file processing safe to retry: a replacement Pod redoes its own shard, not a random one.
The work-queue pattern drops completions and sets only parallelism. Pods pull items from an external queue, and the Job succeeds when at least one Pod exits successfully and no Pods remain running, which signals the queue is drained. This pattern fits finite queues: a list of files to convert, a table of rows to reprocess, a bucket prefix to scan. If the queue never empties because producers keep adding work, you have built a service with extra steps, and a Deployment-based worker with queue-level acknowledgement is the honest design.
Size parallelism against the downstream system, not against your cluster. Twelve parallel Pods against a database that tolerates four concurrent writers is not twelve times faster; it is a self-inflicted load test with retries. Start from the downstream limit, subtract the load your services already place on it, and set parallelism to what remains. Raise it only with measurements from the downstream side.
4. Kubernetes Jobs and CronJobs: retries, backoffLimit, and restartPolicy
Retries in Kubernetes Jobs and CronJobs are bounded by backoffLimit, which counts failed attempts before the Job is marked Failed. The default is six, delays grow between attempts, and restartPolicy decides whether a retry is a new Pod or a container restart in place.
backoffLimit is a budget, not a suggestion. Each failed Pod consumes part of it, and when the budget is spent the Job stops creating Pods and reports Failed with the reason BackoffLimitExceeded. Between attempts the controller waits with an exponential delay, starting around ten seconds and growing toward a cap, so a broken Job does not hammer a downstream system in a tight loop. The default budget of six suits transient faults: a node drain, a brief network partition, a downstream restart. It is the wrong budget for a deterministic bug, where six attempts simply repeat the same stack trace six times and delay the page by several minutes.
Choose the budget from the failure you expect. A migration that fails on a schema error will fail identically on every retry, so backoffLimit: 0 or 1 fails fast and puts a human in the loop while the release window is still open. An export that reads from a flaky object store earns a budget of three or four. A long backfill with indexed shards can tolerate a higher budget because one shard hitting a transient fault should not fail eleven healthy shards. The number belongs in code review next to the reason for it, the same way a timeout does.
restartPolicy decides who performs the retry. With Never, a failed Pod stays in place with its logs intact and the Job controller creates a replacement Pod. That preserves evidence: you can read the exact output of attempt two after attempt three succeeds. With OnFailure, the kubelet restarts the container inside the same Pod, and restarts count toward the backoff budget. The Pod list stays short, but earlier attempts' output is harder to separate. For work you debug from logs, Never is usually the better default. For short, noisy tasks where Pod sprawl is the bigger annoyance, OnFailure is defensible. What is not defensible is choosing neither and discovering the behaviour during an incident.
A Job Pod that keeps failing is related to, but distinct from, a service Pod in CrashLoopBackOff. The service Pod restarts forever because its controller wants it alive; the Job Pod retries a bounded number of times because its controller wants a success count. If the underlying container fault is the mystery, the diagnosis path in Kubernetes CrashLoopBackOff troubleshooting applies to reading exit codes and previous logs. The batch-specific question comes after: was this failure worth retrying at all, and did the retry repeat any side effects?
That last question is the bridge to idempotency, and it is where most batch incidents actually live. The controller retrying is correct behaviour. Code that inserts rows without a uniqueness guard, appends to a file without truncation, or sends notifications without a deduplication key turns correct retries into duplicated production effects.
5. Kubernetes Jobs and CronJobs: deadlines and TTL cleanup
Deadlines in Kubernetes Jobs and CronJobs come in two kinds: activeDeadlineSeconds bounds how long a Job may run, and ttlSecondsAfterFinished bounds how long finished Jobs and Pods remain afterwards. Set both on every production workload, or stuck work runs forever and finished work accumulates without any limit.
activeDeadlineSeconds is a wall-clock budget measured from the Job start time. When it expires, the Job is marked Failed with the reason DeadlineExceeded and its running Pods are terminated. It takes precedence over the retry budget: a Job inside its deadline can keep retrying, but no retry extends the deadline. Size it from the slowest legitimate run, with headroom for a slow downstream day, and then treat a deadline breach as a signal worth paging on. A Job with no deadline is a Job that can hold a database lock, a node, or a concurrency slot indefinitely while looking merely slow.
Deadline sizing interacts with the schedule for CronJobs. If a job runs hourly and its deadline is three hours, one stuck run can still be active when the next two ticks arrive, and your concurrency policy becomes the only thing standing between you and three overlapping writers. A practical rule is to keep the deadline below the schedule interval for sequential work, so a single run cannot outlive its slot. Where a run legitimately needs longer than the interval, the overlap question must be answered deliberately in the concurrency section, not discovered in production data.
ttlSecondsAfterFinished handles the other end of the lifecycle. Finished Jobs and their Pods are not deleted automatically; they remain so you can read logs and inspect status. Without a TTL they remain forever, and a namespace running frequent CronJobs accumulates thousands of completed Pods that slow down list calls and bury the one failure you need. With a TTL, the Job becomes eligible for automatic deletion that many seconds after it finishes, whether it completed or failed. Setting it to zero deletes immediately, which destroys the evidence you need after a failure. One to seven days is the usual range: long enough to debug the last bad run, short enough to keep the namespace readable.
Choose the TTL from your debugging window, not from tidiness. If failures are investigated on the next business day, a 24-hour TTL deletes Friday night's evidence before Monday's engineer arrives. If logs are shipped to a central system and Job objects are only a convenience, a shorter TTL is safe. The same logic applies to CronJob history limits in the next sections: retention is an observability decision wearing a cleanup costume.
Suspension is the manual version of these controls. Setting suspend: true on a Job stops the controller creating Pods and deletes active Pods, which is a sharp tool for pausing a runaway backfill. Suspending a CronJob stops future schedule ticks without touching Jobs already created. Know both before you need them, because the middle of an incident is a poor time to learn which one kills running work.
6. Kubernetes Jobs and CronJobs: make retries safe with idempotency
Idempotency in Kubernetes Jobs and CronJobs means running the same work twice produces the same result as running it once. Retries, duplicate schedule ticks, and manual reruns all execute your code again, so batch code must tolerate repetition by design, not by luck.
Kubernetes does not promise exactly-once execution for batch work. A Job Pod can fail after writing half its output, and the retry starts against a world the first attempt already changed. A CronJob tick can occasionally create two Jobs, or none. These are documented behaviours of a distributed scheduler, not defects to wait out. The contract you control is the code: given the same inputs and the same run identity, a second execution must converge to the same end state instead of doubling it.
Four techniques cover most batch code. Write outputs to deterministic locations keyed by run date or partition, so a retry overwrites its own previous output instead of appending beside it. Prefer upserts with a natural key over blind inserts, so reprocessing a record updates it rather than duplicating it. Stage results and publish atomically: write to a staging prefix or table, validate row counts, then swap or rename into place, so readers never see a half-written export. Record a run key in the destination system and check it before applying effects, so a duplicate execution can detect that this exact run already completed and exit successfully without repeating side effects.
Notifications and external calls need the same treatment. A job that sends a digest email, posts to a webhook, or charges a payment method must carry a deduplication key the receiver honours, or record the send in the same transaction as the work that triggered it. The failure mode is specific: attempt one sends the email and dies before recording completion; attempt two sends it again; your users learn about your retry policy from their inbox.
Test idempotency the way production will. Run the job twice against a staging dataset and diff the outputs. Kill a Pod mid-run and let the retry finish, then check row counts and checksums against a clean run. These are cheap tests that catch the expensive class of batch bug, the one where every individual run looks successful and the data is quietly wrong. Senior review of a batch change asks one question before all others: show me what happens when this runs twice.
7. Kubernetes Jobs and CronJobs: CronJob schedules, timezone, and history
A CronJob in Kubernetes Jobs and CronJobs is a Job factory on a timetable: a five-field cron schedule, a timezone, and a Job template. Set the timezone explicitly, bound the history you keep, and remember the Job template carries the full execution contract from earlier sections.
The schedule "15 2 *" means 02:15 every day, but only inside a timezone. Without timeZone, the schedule is read in the controller manager's timezone, which on most clusters is effectively UTC. A team that writes 02:15 meaning local time and gets 02:15 UTC has scheduled its backup during the morning traffic peak and will blame the database for slow queries. Set timeZone to an IANA name such as Asia/Karachi on every CronJob, even when UTC is what you want, so the intent survives a cluster migration.
History limits control how many finished Jobs the CronJob keeps for inspection: successfulJobsHistoryLimit defaults to 3 and failedJobsHistoryLimit defaults to 1. One retained failure is rarely enough when you are comparing a bad run against the previous good one, so raising the failed limit to two or three is cheap insurance. These limits interact with the Job TTL: whichever mechanism deletes first wins, so set them as one retention decision rather than two independent numbers.
The nesting is the other common trip hazard. A CronJob contains a Job template, which contains a Pod template. backoffLimit and activeDeadlineSeconds belong to the Job level inside jobTemplate.spec; restartPolicy belongs to the Pod level inside jobTemplate.spec.template.spec. A field placed one level too high is either rejected or silently not where you think it is. When a CronJob behaves as if a setting does not exist, check the indentation before you check the controller.
Finally, treat the schedule itself as a capacity decision. Fifteen CronJobs all firing at midnight is a thundering herd you scheduled yourself. Stagger start times, keep heavy jobs away from peak traffic and away from each other, and remember that every scheduled run competes for the same nodes, database connections, and object-store throughput as your services.
8. Kubernetes Jobs and CronJobs: concurrencyPolicy and overlapping runs
Overlap in Kubernetes Jobs and CronJobs is governed by concurrencyPolicy, which decides what happens when a schedule tick arrives while the previous run still executes. Allow stacks runs, Forbid skips the new tick, and Replace terminates the running Job and starts fresh.
The default is Allow, and it is the right choice less often than teams assume. Allow suits independent, cheap, idempotent work: a cache warmer, a metrics snapshot, a cleanup that deletes by age and tolerates concurrent execution. It is dangerous for anything that writes shared state. A slow export plus a punctual schedule compounds load exactly when the system is already struggling, and two writers racing on the same partition produce results neither run can explain.
Forbid skips the new tick while a previous run is active. For sequential batch work such as backups, billing runs, syncs, and reports, Forbid is the safer default: a skipped run is visible in the CronJob status and recoverable by a manual trigger, while two concurrent runs corrupt quietly. The cost of Forbid is a missed slot when a run overruns, which is why it pairs with a deadline below the schedule interval and an alert on last-success age. A skipped tick you know about beats a duplicated write you discover from a customer.
Replace terminates the running Job and starts a new one. It fits work where only the freshest result matters and a stale run has no value: rebuilding a search index from current data, refreshing a snapshot that the next run fully supersedes. It is a poor fit for work with side effects that cannot be safely interrupted mid-write, because termination is not a graceful pause; the Pod receives the termination signal and your code must handle partial output.
Concurrency policy only compares Jobs created by the same CronJob. A Job an operator creates by hand, or a second CronJob pointing at the same data, starts regardless of policy. Where two writers must never overlap, combine Forbid with an application-level guard such as a database advisory lock or a run-key check, so the protection holds across every entry point. Policy narrows the race; idempotency and locking close it.
9. Kubernetes Jobs and CronJobs: missed schedules and startingDeadlineSeconds
Missed schedules in Kubernetes Jobs and CronJobs happen when the controller cannot create a Job at its tick. startingDeadlineSeconds bounds how late a run may still start, and without it a long outage can leave a CronJob unable to schedule at all.
The controller tracks the last scheduled time and counts how many ticks it missed. If more than 100 schedules were missed, it refuses to start the Job and logs an error about too many missed start times. A CronJob on a one-minute schedule blocked for two hours crosses that line. So does a CronJob suspended for a week and then resumed, because suspended ticks count as missed. The symptom looks like a schedule that silently stopped firing, and teams often debug the cron expression while the real cause sits in the controller log.
startingDeadlineSeconds changes the accounting. With a deadline set, the controller measures how late a run would start and skips executions that are too old, so ancient misses stop accumulating toward the lockout. A run skipped for lateness counts as failed for that tick, and future ticks proceed normally. Set the value from the work's freshness requirement: a nightly report can tolerate a 900-second late start, while a five-minute sync should skip rather than run stale. Avoid values under ten seconds, because the controller evaluates schedules on a roughly ten-second cadence and an overly tight deadline can mean the Job never starts.
Resuming a suspended CronJob deserves the same care. Without a starting deadline, missed ticks may be created immediately on resume, firing a pile of stale runs at once. With a deadline, only a recent tick can still start. Decide which behaviour you want before the maintenance window, not after it. For work where every missed run must eventually execute, such as processing dated partitions, neither behaviour is sufficient on its own: the job itself should detect which partitions are missing and process those, making the schedule a trigger rather than the source of truth.
Clock behaviour is the quiet variable in this section. Schedules are evaluated against controller time, and a timezone field only helps if the named zone matches the business expectation, including daylight-saving transitions where they apply. When a CronJob fires an hour early twice a year, the schedule is usually correct and the timezone assumption is not.
10. Kubernetes Jobs and CronJobs: resources, placement, and downstream limits
Capacity in Kubernetes Jobs and CronJobs is set by resource requests, node placement, and downstream tolerance for concurrent work. A batch Pod without requests can starve services, and parallelism beyond a downstream limit turns a healthy job into a load incident with retries attached to it.
Batch Pods compete with services for the same nodes. Resource requests are how the scheduler knows a backfill Pod needs a full core and a gigabyte of memory; without them, the Pod is scheduled as if it were free and then throttled or evicted under pressure. Set requests from observed usage on a representative run, and set limits where a runaway Pod must not consume a node. Memory limits deserve special care in batch work: a Pod killed for exceeding its memory limit mid-export looks like a flaky job until someone reads the termination reason.
Placement controls decide where batch work may run. Node selectors, affinity, and taints can steer heavy jobs onto dedicated nodes or away from latency-sensitive services. Priority classes let the scheduler preempt low-priority batch Pods when production traffic needs the capacity, which is the correct trade for most clusters: the report can rerun, the checkout flow cannot. Use these controls deliberately rather than letting batch work drift onto whichever node has room at 02:00.
The downstream limit is the constraint teams measure last. Every parallel Pod opens connections, issues queries, and writes objects. The database, queue, or object store on the receiving end has a concurrency budget shared with your services, and batch parallelism spends from it. The shared production hygiene for requests, limits, and placement is covered in Kubernetes best practices; the batch-specific step is to size parallelism from the downstream budget and verify with downstream metrics during the first runs, not from cluster CPU graphs alone.
Retries multiply downstream load at the worst moment. When a downstream system slows down, Pods fail, the controller retries them, and the retry wave arrives while the downstream is still recovering. Backoff delays soften this, and a modest backoffLimit caps it, but the structural fix is headroom: parallelism set so that even a full retry wave stays inside the downstream budget.
11. Kubernetes Jobs and CronJobs: monitoring, alerting, and manual runs
Observability for Kubernetes Jobs and CronJobs starts with one alert: the age of the last successful run for each schedule. Failed Pods matter, but a schedule that stopped firing produces no failures at all, so staleness detection is what catches silent batch outages before users notice them.
Alert on three signals. First, time since last success per CronJob, with a threshold tied to the schedule: an hourly job silent for three hours is an incident even if every Pod exited cleanly. Second, Job failures, grouped by reason, so BackoffLimitExceeded and DeadlineExceeded route differently; one means the work kept failing, the other means it ran too long. Third, run duration trend, because a job drifting from twenty minutes toward its deadline is next month's skipped tick announcing itself early. The triage patterns for silent alerting failures and metric gaps are covered in production monitoring and alerting troubleshooting; batch work adds the staleness signal that service monitoring rarely needs.
Inspect a Job with the same commands every time, so the runbook is muscle memory:
describe shows the Job conditions, the completion counts, and recent events, which usually name the failure reason directly. Pod logs show the application's own account of the failure. Read both before changing fields; a Job failing on a missing secret and a Job failing on a downstream timeout need opposite responses, and the events separate them in seconds.
Manual runs are part of normal operations. Creating a Job from a CronJob template runs the scheduled work now, under the same contract, without waiting for the next tick:
Use manual runs to recover a skipped tick, validate a fix, or reprocess a partition. Remember that a manual Job ignores the CronJob concurrency policy, so check for an active scheduled run before triggering one against shared state. Give manual Jobs a dated name, keep the same idempotency guarantees as scheduled runs, and record why the manual run happened where the next engineer will find it.
12. Kubernetes Jobs and CronJobs: troubleshooting matrix and final checklist
Troubleshooting Kubernetes Jobs and CronJobs starts from the Job condition and the Pod termination reason, not from the schedule. BackoffLimitExceeded means retries ran out, DeadlineExceeded means time ran out, and a silent CronJob usually means missed schedules, suspension, or a timezone surprise.
| Symptom | Likely cause | First check | Fix |
|---|---|---|---|
| Job Failed, reason BackoffLimitExceeded | Deterministic code error or exhausted transient retries | Failed Pod logs and exit code | Fix the cause, then create a new Job; lower the budget for deterministic errors |
| Job Failed, reason DeadlineExceeded | Run exceeded activeDeadlineSeconds | Pod duration, downstream latency during the run | Raise the deadline from measured runtime or fix the slow step; alert on duration trend |
| Pods pending, Job never starts | Unschedulable requests, taints, or no capacity | Pod events from describe | Correct requests or placement; add capacity or a dedicated batch node pool |
| CronJob runs overlap | concurrencyPolicy Allow with slow runs | CronJob spec and active Jobs | Set Forbid for sequential work; add an application lock for shared state |
| CronJob stopped firing | More than 100 missed schedules, suspension, or controller downtime | Controller log message, CronJob status, suspend field | Set startingDeadlineSeconds; resume deliberately; trigger a manual Job to recover |
| CronJob fires at the wrong hour | Missing timeZone, schedule read in controller timezone | CronJob spec timeZone field | Set an explicit IANA timeZone |
| Duplicated rows after retries | Non-idempotent writes | Destination keys and run identity handling | Upsert by natural key, deterministic output paths, staging plus atomic publish |
| Namespace full of completed Pods | No TTL and generous history limits | Job age and count in the namespace | Set ttlSecondsAfterFinished and history limits from the debugging window |
| Pod killed, reason OOMKilled | Memory limit below working set | Pod termination reason and memory usage | Raise requests and limits from measured usage; stream data instead of loading it |
Work the matrix top-down by evidence, not by guess. The Job condition separates retry exhaustion from deadline expiry. Pod events separate scheduling problems from application problems. The CronJob status separates schedule problems from execution problems. Each layer has its own fields, and changing a field in the wrong layer is how a ten-minute fix becomes an afternoon.
Final checklist
- The work has a written definition of done, and the controller matches it: Job for one finite run, CronJob for a timetable, Deployment or queue worker for continuous work.
- completions and parallelism are set from the work shape and the downstream concurrency budget.
- backoffLimit is chosen from the expected failure type, with a reason recorded in review.
- restartPolicy is Never or OnFailure, chosen for log retention and retry behaviour.
- activeDeadlineSeconds bounds one run, and for sequential CronJobs it sits below the schedule interval.
- ttlSecondsAfterFinished and CronJob history limits match the debugging window.
- The code is idempotent under retries, duplicate ticks, and manual reruns, proven by a double-run test.
- timeZone is explicit, concurrencyPolicy matches the overlap rule, and startingDeadlineSeconds bounds late starts.
- Resource requests and limits come from measured runs, and placement keeps batch work from starving services.
- Alerts cover last-success staleness, Job failure reasons, and run-duration trend.
Next in the series, Module 4 moves from workload controllers to how Pods talk to each other: the CNI lesson in the Kubernetes roadmap, Module 4 on Kubernetes networking covers iptables, Calico, Cilium, and eBPF. Batch Pods still need the network to reach databases and object stores, and that lesson explains the machinery underneath every connection your jobs open.
Frequently Asked Questions
What is the difference between Kubernetes Jobs and CronJobs?
A Job creates Pods until a required number exit successfully, then stops. A CronJob holds a cron schedule and a Job template, and creates a new Job for each schedule tick. Use a Job for one finite run and a CronJob when that same finite run repeats on a timetable.
When should Kubernetes Jobs and CronJobs replace a Deployment?
Replace a Deployment when a successful exit is the goal rather than a failure. Migrations, backfills, exports, and reports belong in Jobs because a Deployment restarts finished Pods forever. Keep a Deployment for processes that must stay up and serve traffic, and use a queue worker when work arrives continuously.
How do completions and parallelism work in Kubernetes Jobs and CronJobs?
Completions is the number of successful Pod exits required to finish the Job. Parallelism is the maximum number of Pods running at once. Completions of 12 with parallelism of 3 runs three Pods at a time until twelve successes accumulate. Indexed mode gives each Pod a stable shard number.
What does backoffLimit do in Kubernetes Jobs and CronJobs?
BackoffLimit is the failure budget: the number of failed attempts tolerated before the Job is marked Failed with the reason BackoffLimitExceeded. The default is 6, with growing delays between attempts. Lower it for deterministic errors that fail identically on every retry, and keep it higher for transient faults.
How do Kubernetes Jobs and CronJobs prevent overlapping runs?
The CronJob concurrencyPolicy field decides. Allow lets runs stack, Forbid skips a tick while the previous run is active, and Replace terminates the running Job and starts a new one. For sequential work that writes shared state, Forbid plus an application-level lock is the safe combination.
Why did my Kubernetes Jobs and CronJobs schedule stop firing?
The usual cause is missed schedules. If the controller counts more than 100 missed ticks, it refuses to start the Job and logs an error. Suspension, controller downtime, and a missing startingDeadlineSeconds all lead there. Set startingDeadlineSeconds so old misses are skipped, and check the suspend field and timezone.
How do I clean up finished Kubernetes Jobs and CronJobs automatically?
Set ttlSecondsAfterFinished on the Job so it becomes eligible for deletion that many seconds after finishing, and set successfulJobsHistoryLimit and failedJobsHistoryLimit on the CronJob. Choose retention from your debugging window: long enough to read a failed run's logs, short enough that completed Pods do not accumulate.
Preparing for Senior Platform & SRE Interviews
Practice real-world cluster triage, RBAC debugging, and pod scheduling scenarios in our Kubernetes scenario interview questions hub.
Explore Interview Scenarios →