Sub topic 12
Designing tasks that tolerate retries and duplicates
This chapter assumes you can write a Job and a CronJob manifest, and that you know how backoffLimit, concurrencyPolicy, and startingDeadlineSeconds behave. Kubernetes gives batch work at-least-once execution, not exactly-once. Your task has to handle that.
Why the same work runs twice
A task can run more than once for several reasons:
- A Pod fails after doing part of its work, and the Job starts a replacement. The replacement repeats the work from the start.
- A Pod finishes its work but is evicted or loses its node before Kubernetes records success.
- A CronJob with
concurrencyPolicy: Allowstarts a run while the previous one is still going. - The CronJob controller creates two Jobs for one schedule slot. The Kubernetes documentation says this can happen in rare cases.
A task can also not run at all. A run is skipped when the controller misses the slot and startingDeadlineSeconds has passed. It is also skipped when Forbid is set and the previous run is still active.
concurrencyPolicy: Forbid reduces overlap but does not guarantee it never happens. Treat it as a first line of defense only.
Principles
- Key work by its input, not by the clock. Process "the report for 2026-12-04", not "everything since now". A rerun then computes the same result.
- Write results so a repeat overwrites. Use an upsert, or write to a deterministic file name. Avoid blind inserts and appends.
- Make output appear atomically. Write to a temporary name and rename it, or commit a database transaction. A reader never sees half a result.
- Keep state outside the Pod. The container filesystem is gone after a failure. Store progress markers in a database, object store, or queue.
- Catch up on missed runs. Because a run can be skipped, let the next run process any unfinished windows. Don't assume it only covers its own slot.
Worked example: an idempotent daily total
This PostgreSQL statement sums the previous day's orders. The report_date primary key plus ON CONFLICT makes running it twice safe.
CREATE TABLE IF NOT EXISTS orders (
id bigserial PRIMARY KEY,
created_at timestamptz NOT NULL,
amount numeric NOT NULL
);
CREATE TABLE IF NOT EXISTS daily_totals (
report_date date PRIMARY KEY,
total numeric NOT NULL
);
INSERT INTO daily_totals (report_date, total)
SELECT (now() AT TIME ZONE 'UTC')::date - 1,
COALESCE(SUM(amount), 0)
FROM orders
WHERE created_at >= ((now() AT TIME ZONE 'UTC')::date - 1)::timestamp AT TIME ZONE 'UTC'
AND created_at < ((now() AT TIME ZONE 'UTC')::date)::timestamp AT TIME ZONE 'UTC'
ON CONFLICT (report_date) DO UPDATE SET total = EXCLUDED.total;The date range is anchored to "yesterday", so a retry an hour later still computes the same window. The same CronJob can then use a low-risk configuration. This example assumes a Secret named db-credentials holds the connection settings, and a ConfigMap named report-sql holds the SQL above under the key report.sql.
apiVersion: batch/v1
kind: CronJob
metadata:
name: daily-total
spec:
schedule: "15 1 * * *"
timeZone: "Etc/UTC"
concurrencyPolicy: Forbid
startingDeadlineSeconds: 3600
jobTemplate:
spec:
backoffLimit: 3
template:
spec:
restartPolicy: Never
containers:
- name: report
image: postgres:16
command: ["psql", "-v", "ON_ERROR_STOP=1", "-f", "/sql/report.sql"]
envFrom:
- secretRef:
name: db-credentials
volumeMounts:
- name: sql
mountPath: /sql
volumes:
- name: sql
configMap:
name: report-sqlON_ERROR_STOP=1 makes psql exit non-zero on a SQL error. Without it, the Pod could report success after a failed statement.
Exercise
A Job's Pod inserts one row per processed file with a plain INSERT, then crashes at the end. The Job retries and the table now has duplicate rows. Name two changes that make the task safe to retry.
Show answer
Give each row a deterministic unique key, such as the file name, and use an upsert (INSERT ... ON CONFLICT) so a repeat overwrites instead of duplicating. Alternatively, wrap all inserts for a run in one transaction so a crash leaves no partial rows, and have the next attempt start clean.