Short answer: a daily report scheduler should record one durable, idempotent delivery job per intended recipient and let bounded workers send those jobs, because a cron handler cannot make a remote email acceptance and its own completion record atomic.
The constraint is easy to miss: a report run has an accounting obligation, not merely a start time. At the end of the run, an operator needs to reconcile the recipient snapshot against durable outcomes: created, already known, delivered, deferred, and terminally rejected. A process that loops over recipients, sends email, and exits with status zero cannot provide that evidence after a restart, a timeout, or a throttled downstream service. Keep the clock-driven handler narrow; it creates the obligation, while a delivery worker owns each external side effect.
The scheduler is not the delivery engine.
Why should a daily scheduled email enqueue jobs instead of sending in the cron handler?
The cron handler has one useful job: determine the report date, take a stable view of eligible recipients, and insert a delivery intention for each (report_date, recipient_id, report_version) tuple. The insertion needs a database uniqueness constraint, because a preliminary read can race when two scheduler instances observe the same missing row. A second invocation then becomes harmless accounting: it finds the existing logical job rather than creating another one.
Sending in the handler widens the failure boundary to include enumeration, rendering, remote I/O, backoff, and batch completion. A mail call that stalls can overlap the next schedule. A restart loses an in-memory cursor. HTTP 429 Too Many Requests says the client has exceeded a rate limit and may include Retry-After; waiting in the coordinator holds the entire batch hostage even though only some recipients need deferral. With jobs, one worker can reschedule a throttled item while another works on an eligible one within a deliberate concurrency limit.
This separation does not promise literal exactly-once execution. Email delivery crosses two systems that do not share a transaction, so a worker can lose its acknowledgement after the remote side accepts a message but before the local row is marked delivered. The correct response is a stable identity, repeated on every attempt, plus an audit trail that makes the uncertain interval visible. Small boundary. Large consequence.
Retries are not proof.
The catch is that a job-based design has a real cost: leases, queue or table maintenance, workers, backlog alerts, and an operational recovery procedure. It is not suitable for a tiny internal list when a single process with durable per-recipient checkpoints is sufficient, or for work that must remain inside one local database transaction. Stick with the checkpointed process in those cases, but retain the checkpoint and reconciliation record; moving a loop to a queue does not remove responsibility for correctness.
Model the job as an auditable obligation
Treat the job table or message payload as a ledger of intent, rather than as a transient implementation detail. Its identity is derived from the business event, not from an attempt: report date, recipient identity, and the report definition version. This protects a rerun and preserves an explanation for why a particular recipient received a particular version.
An explicit state model also prevents a common monitoring error: treating a successful scheduler exit as proof of a complete batch. A useful model distinguishes pending, leased, delivered, deferred, and terminal. Each transition records an attempt number, a timestamp, and a redacted outcome class. Keep report bodies and email addresses out of routine logs unless retention and access controls have been reviewed for the applicable privacy and compliance obligations. Opaque identifiers are usually enough for an audit join.
| Question | Evidence to retain | Why it matters |
|---|---|---|
| Was the recipient in scope? | Snapshot identifier and report version | Separates source selection from delivery |
| Was one logical job created? | Unique business key and creation result | Makes duplicate schedule runs reconcilable |
| What happened on each attempt? | Attempt count, classification, timestamps | Distinguishes delay from permanent rejection |
| Can a worker safely retry? | Stable idempotency key and lease state | Keeps a replay tied to the same obligation |
The most difficult state is remote acceptance followed by a lost local update. Do not keep a database transaction open while calling the mail service in an effort to solve it; network latency then holds locks without creating a shared commit. If the mail interface accepts an idempotency key, send the logical job ID every time. If it does not, the system must record the ambiguity, apply a documented replay policy, and reconcile with whatever delivery evidence is available. The important claim is narrower than exactly once: the application never invents a new logical email merely because execution repeated.
Consider the sequence carefully. A worker claims job J, commits a two-minute lease, and hands J to the mail interface as its idempotency key. The interface can accept the message, while a network interruption prevents the worker from learning that acceptance; the lease later expires, and another worker claims J. Repeating J is defensible because it names the same delivery obligation, while generating a new key would create a second business event out of one uncertainty. If the remote interface cannot deduplicate, there is no technical incantation that converts this into exactly-once delivery. The operator needs a documented policy for that narrow ambiguity, an audit record for the attempted handoff, and a reconciliation path that can identify it without exposing report content. This distinction is more useful than a generic retry count: it tells a reviewer which outcome is known, which is inferred, and which requires investigation.
A Go example with claiming and idempotent retries
This example uses a database job ledger. The unique index is the concurrency control for the scheduler, while FOR UPDATE SKIP LOCKED lets workers claim distinct due jobs. The lease commits before the remote call, so rendering and delivery never hold a row lock.
package reportmail import ( "context" "errors" "time" "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/pgxpool" ) var ErrNoJob = errors.New("no due report email job") type Job struct { ID string ReportDate time.Time RecipientID string Attempts int } type Mailer interface { SendReport(context.Context, string, time.Time, string) (string, error) } func EnqueueDay(ctx context.Context, db *pgxpool.Pool, day time.Time, version string) error { _, err := db.Exec(ctx, ` INSERT INTO report_email_jobs (id, report_date, recipient_id, report_version, status, available_at) SELECT gen_random_uuid(), $1, r.id, $2, 'pending', now() FROM report_recipients r WHERE r.daily_report_enabled ON CONFLICT (report_date, recipient_id, report_version) DO NOTHING`, day, version) return err } func ClaimOne(ctx context.Context, db *pgxpool.Pool) (Job, error) { tx, err := db.BeginTx(ctx, pgx.TxOptions{}) if err != nil { return Job{}, err } defer tx.Rollback(ctx) var job Job err = tx.QueryRow(ctx, ` SELECT id, report_date, recipient_id, attempts FROM report_email_jobs WHERE status = 'pending' AND available_at <= now() ORDER BY available_at, id FOR UPDATE SKIP LOCKED LIMIT 1`).Scan(&job.ID, &job.ReportDate, &job.RecipientID, &job.Attempts) if errors.Is(err, pgx.ErrNoRows) { return Job{}, ErrNoJob } if err != nil { return Job{}, err } _, err = tx.Exec(ctx, ` UPDATE report_email_jobs SET status = 'leased', attempts = attempts + 1, lease_until = now() + interval '2 minutes' WHERE id = $1`, job.ID) if err != nil { return Job{}, err } return job, tx.Commit(ctx) } func Deliver(ctx context.Context, db *pgxpool.Pool, mailer Mailer, job Job) error { messageID, err := mailer.SendReport(ctx, job.RecipientID, job.ReportDate, job.ID) if err != nil { return err } _, err = db.Exec(ctx, ` UPDATE report_email_jobs SET status = 'delivered', provider_message_id = $2, delivered_at = now(), lease_until = NULL WHERE id = $1 AND status = 'leased'`, job.ID, messageID) return err } The code intentionally leaves classification at the boundary around Deliver. Retry a timeout or a 429 after observing Retry-After, using capped backoff and jitter; keep the same job ID. Treat malformed recipient input as terminal until the data changes. After a bounded number of attempts, isolate the job for inspection rather than letting it silently consume worker capacity. Dead-letter queues are intended for messages that are not processed successfully, although systems with strict ordering requirements need to consider the ordering effect before adopting that pattern.
Choose the boundary before choosing the mechanism
A durable job ledger, a managed queue, and a self-hosted broker can all implement the same ownership model. The decision is operational: where can the team observe backlog age, expire leases, control delayed delivery, and replay a specific logical job without creating a fresh identity? For a moderate daily report workload that already depends on a transactional database, a job table can keep the audit trail close to the recipient snapshot. A separate queue can be appropriate when workers need independent scaling or the backlog must be isolated from the primary database. Neither choice makes remote side effects transactional.
Test the design by forcing the transitions that production will eventually produce. Run the scheduler twice. Stop a worker after it receives a lease. Simulate a throttle response, an invalid recipient, and a lost acknowledgement after remote acceptance. Then ask a reconciliation query whether every snapshot row is represented exactly once among created, duplicate, delivered, deferred, and terminal results. This is the test that matters, because it checks the accounting invariant rather than a favorable happy-path log.
Metrics should mirror the state model: snapshot size, jobs inserted, uniqueness conflicts, oldest pending age, leased count, delivery latency, retry classifications, and terminal count. Alert on the age of unfinished work and on a reconciliation mismatch, not just on worker process liveness. A worker can be healthy while it repeats a permanent error.
Roll out without widening the blast radius
Start by generating the daily recipient snapshot and job rows while retaining the existing delivery path as the source of record. Compare the snapshot count, successful inserts, and duplicate count until they reconcile. Next, enable workers for a small, clearly bounded cohort and verify that a replay uses the same job identity and produces a complete audit trail. Only then move the remaining cohort, with a documented procedure for pausing claims and reaping expired leases.
The final operational contract is compact: the scheduler records intent, workers execute one owned effect at a time, and the ledger explains every intended recipient. That contract is useful at low volume and high volume alike because it supplies evidence when delivery is uncertain.
