Why a scheduled job can run twice, overlap or be skipped, and four patterns that make it safe: period keys, run claims, per-item idempotency and catch-up, with a nightly billing example on Encore.

A cron job looks simple: at 02:00 do the work. In production the schedule delivers it twice during a deploy, a slow run overlaps the next one, a crashed run leaves half the rows done, and a missed night leaves a gap nobody notices.
The fix is a job that can be run any number of times for the same period and still produce one correct result, rather than a better scheduler.
The Kubernetes CronJob docs say it directly: scheduling is approximate, two jobs might be created or none, and the jobs you define should be idempotent. Hosted schedulers, in-process timers and managed cron services all make the same trade, because missing a run is worse than repeating one.
Give every run an explicit period, such as the billing day, and compute what to process from the period and not from the time the job happens to start. A run for 2026-11-22 produces the same set of items whether it starts at 02:00 or at 14:00 after a retry. A job that asks "what changed in the last 24 hours" gives different answers on every attempt and double-counts or skips work whenever it runs late.
Inserting a row keyed by job and period makes whoever inserts it the owner of the run, while everyone else sees a conflict and exits, and a run stuck in running for longer than a timeout can be taken over, which covers a crash:
INSERT INTO job_runs (job, period, status, started_at)
VALUES ('nightly-billing', '2026-11-22', 'running', now())
ON CONFLICT (job, period) DO UPDATE
SET started_at = now()
WHERE job_runs.status = 'running'
AND job_runs.started_at < now() - interval '30 minutes'
RETURNING period;
If the statement returns a row, the caller owns the run, and if it returns nothing the run is either finished or in progress elsewhere. PostgreSQL's advisory locks are an alternative for mutual exclusion, but a lock does not record that a period finished, so the claim row is more useful. If you use session-level advisory locks, remember that a pooled connection can release them unpredictably.
The claim stops duplicate runs but not a crash halfway through one. Make every item's side effect safe to repeat: insert with a unique key such as (customer_id, period) and ON CONFLICT DO NOTHING, move records through states with conditional updates, and send provider requests with idempotency keys. Then a takeover run redoes only what is missing. For work that fans out, publish one message per item and let the consumers be idempotent.
Record the last period that completed, and have each run process every period after it up to yesterday. A job that was down for two nights then does three periods in a row, in order, and a job that runs on time does one. Keep the loop bounded so one very late start does not run for hours.
Encore is a backend framework with built-in infrastructure, and the job is a cron job that calls an API endpoint on a schedule, next to the Postgres database that holds the run claims, declared in code. Cron jobs are managed by the Encore platform and do not run locally or in preview environments, so the endpoint is the unit you test, and it is written to be safe to call repeatedly.

Run in your terminal to get started locally.
-- billing/migrations/1_create_billing.up.sql
CREATE TABLE job_runs (
job TEXT NOT NULL,
period DATE NOT NULL,
status TEXT NOT NULL DEFAULT 'running', -- running | done
started_at TIMESTAMPTZ NOT NULL,
PRIMARY KEY (job, period)
);
CREATE TABLE usage_invoices (
customer_id TEXT NOT NULL,
period DATE NOT NULL,
amount_cents BIGINT NOT NULL,
PRIMARY KEY (customer_id, period) -- one invoice per customer and period
);
CREATE TABLE usage_events (
id BIGSERIAL PRIMARY KEY,
customer_id TEXT NOT NULL,
occurred_on DATE NOT NULL,
cents BIGINT NOT NULL
);
// billing/billing.go
package billing
import (
"context"
"errors"
"time"
"encore.dev/cron"
"encore.dev/rlog"
"encore.dev/storage/sqldb"
)
var db = sqldb.NewDatabase("billing", sqldb.DatabaseConfig{
Migrations: "./migrations",
})
// RunNightly bills yesterday, and any earlier day that was missed, one period at a time.
//
//encore:api private method=POST path=/billing/run
func RunNightly(ctx context.Context) error {
yesterday := time.Now().UTC().AddDate(0, 0, -1).Truncate(24 * time.Hour)
// Catch-up: start after the last completed period, but never more than 7 days back.
var last *time.Time
if err := db.QueryRow(ctx,
`SELECT max(period) FROM job_runs WHERE job = 'nightly-billing' AND status = 'done'`,
).Scan(&last); err != nil {
return err
}
from := yesterday
if last != nil {
from = last.AddDate(0, 0, 1)
}
if limit := yesterday.AddDate(0, 0, -6); from.Before(limit) {
from = limit
}
for day := from; !day.After(yesterday); day = day.AddDate(0, 0, 1) {
if err := billPeriod(ctx, day); err != nil {
return err
}
}
return nil
}
func billPeriod(ctx context.Context, period time.Time) error {
// Claim the period. No row back means it is done or running elsewhere.
var claimed time.Time
err := db.QueryRow(ctx, `
INSERT INTO job_runs (job, period, status, started_at)
VALUES ('nightly-billing', $1, 'running', now())
ON CONFLICT (job, period) DO UPDATE SET started_at = now()
WHERE job_runs.status = 'running' AND job_runs.started_at < now() - interval '30 minutes'
RETURNING period`, period).Scan(&claimed)
if errors.Is(err, sqldb.ErrNoRows) {
rlog.Info("period already handled", "period", period)
return nil
}
if err != nil {
return err
}
// One invoice per customer and period; a repeat inserts nothing new.
if _, err := db.Exec(ctx, `
INSERT INTO usage_invoices (customer_id, period, amount_cents)
SELECT customer_id, $1, sum(cents) FROM usage_events
WHERE occurred_on = $1 GROUP BY customer_id
ON CONFLICT (customer_id, period) DO NOTHING`, period); err != nil {
return err
}
_, err = db.Exec(ctx,
`UPDATE job_runs SET status = 'done' WHERE job = 'nightly-billing' AND period = $1`, period)
return err
}
// Managed by the Encore platform in deployed environments. It does not run
// under `encore run`, so call RunNightly directly when testing locally.
var _ = cron.NewJob("nightly-billing", cron.JobConfig{
Title: "Bill yesterday's usage",
Schedule: "0 2 * * *",
Endpoint: RunNightly,
})
encore run starts a local Postgres and applies the migration, so a test can insert usage events, call RunNightly twice and check that each customer has one invoice. On deploy, the database runs on RDS or Cloud SQL and Encore provisions an IAM role for the service, as the AWS infrastructure docs describe. The cron schedule is a standard five-field expression, and all cron times are evaluated in UTC.
A coding agent adding a second nightly job copies the claim pattern into the same package and tests it by calling the endpoint, with no scheduler resource to define.
Best fit: Teams with scheduled work that must be correct when it repeats, such as billing, exports and cleanup jobs, and who want the schedule and the claim table in one repository.
Schedulers favor running a job at least once over missing it. Kubernetes documents that two jobs might be created for one slot, and a deploy, a retry after a timeout or two replicas with their own timers can do the same. A job has to be safe to repeat, because the schedule cannot guarantee exactly once.
Running it once or five times for the same period leaves the same result. In practice that means the job works on a defined period such as yesterday, claims that period before starting, and writes its results with unique keys so a repeat finds work already done.
Claim the run in a database row keyed by job and period with an insert that conflicts on the key, and let only the instance that gets the row continue. Reclaim a run only after a timeout, so a crashed instance does not block the job forever.
With Encore, a cron job is declared in code and calls an API endpoint on a schedule. Cron jobs are managed by the Encore platform and do not run locally or in preview environments, so test the endpoint by calling it directly, and write it to be safe to repeat.
Deploy to your cloud on AWS and Google Cloud
without managing infrastructure
Encore lets developers and agents define application infrastructure directly in code, then automatically provisions it from local development to production in your AWS or GCP account.