Skip to content

Kubernetes CronJob duplicates: protect the business period

Treat the timer as a reconciliation wake-up; carry tenant-period identity through duplicate execution, commit acknowledgement loss and a conflicting input revision.

Dopstack Engineering

· 10 min read

Original conceptual illustration: converging paper trails into a single stamped receipt; ivory and vermilion.

Quick answer

Kubernetes `concurrencyPolicy: Forbid` controls overlap between Jobs created by the same CronJob. It does not turn a business operation into a single execution. Give each logical reporting period a durable identity, commit its database effect with a receipt, and make retries reuse that identity. Keep scheduler evidence separate from evidence that the business work completed.

Kubernetes concurrencyPolicy: Forbid controls overlap between Jobs created by the same CronJob. It does not turn a business operation into a single execution. Give each logical reporting period a durable identity, commit its database effect with a receipt, and make retries reuse that identity. Keep scheduler evidence separate from evidence that the business work completed. [1][2][4]

Why can a non-overlapping CronJob still repeat work?#

Scenario: a fictional subscription service builds a daily usage statement for each tenant. A CronJob wakes a worker, which finds closed reporting periods and writes statements into Postgres. An operator sees duplicate statements after a replacement Pod starts. The CronJob already uses Forbid, so changing the same field again cannot explain the incident. The question is which operation repeated, and what made it eligible to repeat.

The timer, Job, Pod and statement writer each own a different part of the failure. The CronJob controller creates Jobs; a Job manages Pods; the process inside a Pod performs application work. Kubernetes explicitly documents that a program can sometimes start twice even with a single completion, single parallelism and a Never restart policy. Its CronJob documentation also asks applications to tolerate imperfect scheduling. A successful controller configuration therefore cannot establish uniqueness of an application write. [1][2]

Start by separating overlapping Jobs from repeated processes within a Job and repeated business periods across Jobs. A second CronJob with a different name has a separate concurrency policy. A manual recovery process is another producer. A worker can also repeat a period after losing the acknowledgement of an earlier database commit. Those cases need different operational repairs, but the statement identity should protect all of them. [1][2]

For the statement writer, the acceptance rule is: for a tenant and a closed reporting period, the accepted statement revision has a single durable record. Job names, Pod UIDs and process start times remain useful evidence. They are poor business keys because replacements deliberately acquire new execution identities. Changing a key when a retry starts makes the retry look like new work.

Which evidence distinguishes a scheduler problem from a repeated effect?#

Collect the CronJob manifest, relevant Job owner references, Job status, Pod owner references and application logs before deleting objects. Job deletion also removes its Pods, which can erase the easiest route to the execution history. Keep logs according to your retention policy rather than relying on the current object list. [2]

bash
# Read-only investigation; replace the namespace and object names.
kubectl -n reporting get cronjob usage-statements -o yaml
kubectl -n reporting get jobs -o json
kubectl -n reporting get pods -o json
kubectl -n reporting logs job/RELEVANT_JOB --all-containers=true

The broad Job and Pod reads are intentional: compare owner UIDs instead of inferring ownership from similar-looking names. In a large namespace, export a bounded incident window through your observability system. Record the logical reporting period alongside each execution identity. Logs that say only “started” and “finished” cannot establish whether separate processes handled the same tenant-period.

CronJobs on supported Kubernetes versions annotate created Jobs with batch.kubernetes.io/cronjob-scheduled-timestamp; the documentation identifies this behavior from Kubernetes v1.32. That timestamp describes the intended scheduling instant. It is useful for identifying lateness and duplicate scheduling evidence, but it is not automatically the application's billing date or reconciliation boundary. [1]

Do not assume that a Job annotation is automatically present on its Pod. The Downward API exposes selected fields of the Pod itself. Injecting a Pod annotation reads the Pod annotation, not an arbitrary field from its owning Job. If the worker needs controller metadata, provide it through an explicit supported mechanism with appropriate permissions, or keep scheduler correlation in the observer. [3]

For this example, the application does not need the scheduled timestamp to choose work. It queries a durable list of closed periods that still need statements. The timer is a wake-up signal. This makes a delayed wake-up less dangerous than deriving a period from the process's current date, which can change between the original attempt and its retry.

Put the receipt and statement in the same transaction#

The following schema is an illustrative design for a database-only effect. The inputs are an immutable tenant identifier, a date representing a closed period, and a statement payload calculated from a separately defined stable input snapshot. The schema uses a composite primary key so that execution identity cannot silently become statement identity. Postgres enforces that key through its constraint machinery. [6]

sql
CREATE TABLE statement_receipt (
  tenant_id text NOT NULL,
  period_end date NOT NULL,
  input_revision text NOT NULL,
  PRIMARY KEY (tenant_id, period_end)
);

CREATE TABLE usage_statement (
  tenant_id text NOT NULL,
  period_end date NOT NULL,
  input_revision text NOT NULL,
  payload jsonb NOT NULL,
  PRIMARY KEY (tenant_id, period_end)
);

input_revision is deliberately not part of the primary key. In this scenario, changing an input revision must not quietly produce another accepted statement for the same period. A correction requires an explicit revision workflow. If the product instead allows multiple statement revisions, introduce that domain identity and its rules deliberately; do not smuggle it into a retry key.

The receipt is inserted first, and its returned row is the only permission to insert the statement. The example uses positional parameters supplied by the database driver; they are placeholders, not interpolated SQL. Postgres supports ON CONFLICT as an alternative to raising a uniqueness error. [4]

sql
BEGIN;

WITH accepted AS (
  INSERT INTO statement_receipt
    (tenant_id, period_end, input_revision)
  VALUES ($1, $2, $3)
  ON CONFLICT (tenant_id, period_end) DO NOTHING
  RETURNING tenant_id, period_end, input_revision
)
INSERT INTO usage_statement
  (tenant_id, period_end, input_revision, payload)
SELECT tenant_id, period_end, input_revision, $4::jsonb
FROM accepted
RETURNING tenant_id, period_end;

COMMIT;

The process must commit before reporting success. If it fails before commit, neither the receipt nor the statement should become durable. If it commits and loses its connection before seeing the acknowledgement, the next attempt uses the same tenant-period key. A missing returned row then means that this attempt did not acquire the insertion permission. It does not, by itself, mean the input revision matches the accepted result.

After the transaction completes, read the existing receipt and statement by the key. Compare their revision with the requested revision and classify the outcome as an already completed identical request, a revision conflict, or an integrity incident. Do not overwrite a different revision as a convenient conflict handler. Keep that comparison explicit in application code so an operator can distinguish a harmless retry from a changed business request.

At Postgres's default Read Committed isolation, concurrent statements have snapshot rules that matter. In particular, an ON CONFLICT DO NOTHING can decline an insertion because of another transaction whose effects were not visible in that statement's snapshot. A later read must be a new statement, and the transaction's chosen isolation and retry policy must be understood. Do not append a same-statement fallback read and assume it always sees the competing receipt. [5]

This design depends on protecting the receipt and statement from unrelated deletion or mutation. If another process can remove a receipt while retaining its statement, the simple acquisition rule no longer tells the complete story. Restrict writers, define retention and corrections together, and alert when the expected paired records disagree. A uniqueness constraint is a mechanism; the surrounding lifecycle remains an application responsibility. [4][6]

What does the CronJob policy still protect?#

Forbid remains useful when overlapping runs would overload a dependency or compete for the same batch. It controls admission by that CronJob, while the application receipt controls acceptance of a logical result. Choose both from the workload's failure behavior. Kubernetes also considers startingDeadlineSeconds when deciding whether a delayed schedule remains eligible. [1]

ControlUseful protectionEvidence it does not provide
ForbidSuppresses overlapping runs from the same CronJobUnique accepted tenant-period results
Job retry settingsBounds selected retry behaviorProof that an earlier attempt did no work
Database receiptArbitrates the defined business keyDelivery of an external email or payment
Period reconciliationFinds closed periods without resultsPermission to rerun changed inputs silently
Scheduler admission, accepted database effects and completeness answer different questions. Controller behavior is documented by Kubernetes; the receipt and reconciliation method are this article's proposed application design. [1][2]

Scenario: an older run is still healthy when the next scheduled wake-up arrives. Skipping that wake-up may be acceptable because the next worker scans all eligible closed periods. It would be unacceptable if each wake-up represented an irreplaceable event with no durable backlog. In the latter design, repair the work inventory before treating Forbid as a complete reliability policy.

Replace changes a different trade-off: it terminates the previous Job to admit a newer run. Termination cannot reverse a committed statement or prove that an external action never happened. Use it for workloads whose interruption semantics are understood, rather than as a duplicate-removal feature. [1][2]

How should you test crash, retry and missing-run branches?#

Use a disposable database and an application fixture with known closed periods. The expected outcome should be a result set, not a count of green Pods. Include a repeated identical key, concurrent attempts, a different input revision, a transaction that aborts, and a commit whose acknowledgement the client loses. Record which environment actually executed the tests.

For the commit-acknowledgement case, verify durable state from a new connection before retrying. Reuse the original key and inspect the stored revision. For the pre-commit failure, verify that another attempt can acquire the key and create the statement. A connection exception cannot tell the worker whether the commit became durable; the new connection supplies that evidence.

Test the missing-run branch separately. Leave a closed period incomplete, start a later worker and verify that it discovers the old period without changing its identity. Then test the business limit: an open period must remain ineligible. Completeness and uniqueness are distinct obligations, and a system that prevents duplicates can still omit work indefinitely.

This article's SQL is documentation-reviewed; no Kubernetes cluster or concurrent Postgres session was executed for this publication. A local receipt-state model can illustrate commit and abort branches, but it cannot certify database locking, driver behavior or the actual CronJob controller. Run the integration tests with your database version, isolation level and deployment configuration before adopting the design. [1][4][5]

What if the backlog is larger than a single worker can finish?#

Scenario: the statement worker returns after an outage and finds many eligible tenant-periods. A receipt prevents duplicate acceptance, but it does not make a large backlog cheap. Keep the reporting unit small enough to retry independently. Commit each accepted tenant-period under the same identity rule rather than holding an entire recovery batch inside a long transaction.

Define the input boundary before splitting work. The example assumes that a closed period's input revision identifies stable source data. If late usage is allowed to change that period, the product needs an adjustment or supersession rule. Otherwise different attempts can calculate different payloads while believing they are harmless retries. A receipt that preserves the first accepted result is only useful when that acceptance policy matches the business requirement.

Let a bounded batch query choose candidate periods, but allow the acceptance operation to arbitrate duplicates. A candidate list can become stale while another worker runs. Treating the earlier list as exclusive ownership creates a race; treating a uniqueness conflict as a reason to retry with a new key defeats the receipt. Record the outcome against the original period and compare the accepted revision. [4][5]

Separate a retryable infrastructure error from a permanent input failure. A malformed closed-period record should be marked for investigation with its original identity, not retried forever as if the database were temporarily unreachable. A database connection failure should retain enough context to reconcile a possible commit. Those classifications belong in the worker's result record, so a later process can choose the next action without interpreting free-form logs.

Monitor pending eligible work alongside worker failures. A CronJob can keep finishing successfully while a selection bug skips a tenant, and a receipt can keep uniqueness intact while a failed period never completes. For this design, the useful completeness query compares the closed-period inventory with accepted statements, then explains each missing result as pending, failed for a recorded reason, or outside the current processing limit. Green Jobs alone cannot supply that reconciliation.

An outbox can bridge a committed database result to later delivery, but it changes the problem. Follow the existing transactional outbox guide for that boundary. Keep the CronJob incident focused on establishing what repeated and which result the application accepted.

Does Forbid guarantee that my program runs once?
No. Its scope is concurrent Jobs created by the same CronJob. Kubernetes also documents repeated program starts within Job execution. Use an application key and an appropriate durable acceptance mechanism for business effects. [1][2]
Should the scheduled timestamp be my business key?
Only when the business contract actually identifies work by that instant. A reporting period usually needs an explicit domain key. Preserve the scheduled timestamp as operational evidence, and make recovery reuse the original business identity. [1]
Can I commit a receipt and then send an email?
That leaves a failure gap between the database commit and the external send. A crash can retain the receipt without delivering the email. Use a delivery protocol with reconciliation and recipient-side deduplication where available.
Is an empty RETURNING result automatically success?
It only establishes that this attempt did not insert the receipt. Read durable state in a later statement, compare the accepted input revision, and distinguish a completed retry from a conflicting request or broken record lifecycle. [4][5]

Technologies

  • Kubernetes
  • PostgreSQL

Sources

  1. [1]
    CronJob, Kubernetes

    Read 2026-11-05T08:09:04.443560+00:00; publication/update date not listed unless stated in the article. Supports: Concurrency scope is limited to the same CronJob.

  2. [2]
    Jobs, Kubernetes

    Read 2026-11-05T08:09:04.588544+00:00; publication/update date not listed unless stated in the article. Supports: Job deletion removes associated Pods.

  3. [3]
    Downward API, Kubernetes

    Read 2026-11-05T08:09:04.929245+00:00; publication/update date not listed unless stated in the article. Supports: Downward API field availability is limited.

  4. [4]
    INSERT, PostgreSQL

    Read 2026-11-05T08:09:05.236635+00:00; publication/update date not listed unless stated in the article. Supports: ON CONFLICT supplies an alternative to a uniqueness error.

  5. [5]
    Transaction isolation, PostgreSQL

    Read 2026-11-05T08:09:05.262667+00:00; publication/update date not listed unless stated in the article. Supports: Read Committed is the default isolation.

  6. [6]
    Unique constraints, PostgreSQL

    Read 2026-11-05T08:09:05.255627+00:00; publication/update date not listed unless stated in the article. Supports: Unique constraints create enforcement indexes.

Written by

Dopstack Engineering

Engineering team

The engineering team at Dopstack. Illustrative scenarios are composites written to explain a pattern, not accounts of client work.

All articles Website

Get new articles by email

Engineering notes on AI, cloud and SaaS. Occasional, never sold or shared.

Send me new Dopstack Insights articles by email. I can unsubscribe at any time. We’ll email you once to confirm. Privacy

Continue reading