DEV Community

ValerianBlack3895
ValerianBlack3895

Posted on

Node.js Daily Scheduled Email — Enqueue Renewal Jobs Beyond the Cron Handler

A property manager's daily scheduled email process should enqueue jobs for renewal reminders instead of sending the whole batch in its cron handler. That boundary gives each lease its own recoverable delivery record before the business deadline.

Short answer: enqueue each daily scheduled email as its own idempotent job instead of sending the whole batch in the cron handler; the queue makes unfinished work visible, while the idempotency key makes retries safe.

Choice Failure isolation Retry unit Best fit
Send the batch inside cron Whole run Usually the whole run Tiny, non-critical batches with manual recovery
Enqueue one job per reminder One recipient One reminder Deadline-bound mail where partial progress must survive
Reconcile intents, then enqueue One recipient plus a durable audit One reminder High-value deadlines or uncertain scheduler execution

For a weekly-shipping solo SaaS, the middle option is usually the sensible default. It outsources timing and retry mechanics without turning the mail feature into a workflow platform. The third option buys a stronger recovery story, but it also adds a ledger and reconciliation loop that someone must operate.

Why should a daily scheduled email cron handler enqueue jobs?

A cron process has one useful fact: it is time to consider today's work. It does not know that every downstream email can finish before its runtime limit, that the provider will accept a burst, or that a process restart won't land halfway through the recipient list. Sending in the handler couples admission and execution into one failure domain. If recipient 438 fails after 437 sends, a rerun needs durable knowledge of exactly what happened. An in-memory loop cannot supply it after the process exits.

The queue changes the unit of work. The cron handler selects eligible leases, creates stable job identities, and stops. Workers claim those jobs independently. A slow or rejected delivery no longer hides the status of the rest of the batch, and concurrency can be adjusted without changing the business rule that selected the recipients.

That's the real gain.

The property-management rule also belongs outside the transport worker. Suppose the daily report finds a lease whose renewal reminder is due at the property's local business deadline. Admission should calculate that deadline once, record the relevant lease and reminder version, and enqueue immutable data. The worker should not ask, hours later, whether the lease still matches a broad query; doing so can silently change the meaning of an already admitted job. If cancellation after admission is a requirement, model it explicitly with a status check or cancellation record.

The two criteria: recoverable admission and duplicate-safe delivery

First, decide what it means for cron to have succeeded. A log line saying started 812 reminders isn't enough. Success means each eligible reminder has a durable delivery intent or a durable job. The awkward boundary is the database-to-queue handoff: a database commit can succeed just before enqueueing fails, or enqueueing can succeed just before the process loses the acknowledgment. There is no honest try/catch that makes two independent systems atomic.

A transactional outbox handles that boundary. In one database transaction, write the reminder intent and an outbox row with a unique key. A separate publisher reads unpublished rows, enqueues them, and marks them published. Publishing may occur twice, so both the queue job and the delivery worker still need the same stable identity. A lighter design can skip the outbox and run a reconciliation query for intents with no job, but then recovery time depends on the reconciliation interval. I'm not sure which is cheaper for a given app until its deadline, acceptable delay, and operator response time are written down.

Second, define idempotency around the business action, not around a random attempt ID. A practical key is propertyId:leaseId:reminderType:dueDate:templateVersion. Put a unique constraint on it where delivery intent is stored. Retries reuse the key; a corrected template version can intentionally produce a new key. This blocks duplicate intent creation under overlapping cron runs.

It does not magically prove that an external mail provider sent exactly one message. A worker can submit a message successfully and crash before recording the result. If the provider accepts an idempotency key, pass the business key through. If it doesn't, the architecture is at-least-once at that boundary, and the product decision is whether a rare duplicate reminder is safer than a missed legal or commercial deadline. Delivery guarantees are end-to-end properties — queue marketing language can't settle that choice.

Keep retry policy narrow.

An HTTP 429 Too Many Requests response means the client sent too many requests in a period, and the response may include Retry-After. Honor that signal when present; otherwise apply capped exponential backoff with jitter. Don't retry permanent input failures under the same policy. After a bounded number of receives, move the job to a dead-letter queue for inspection instead of cycling forever. AWS documents this redrive pattern with maxReceiveCount, but the operational idea applies beyond one queue product.

A TypeScript admission and worker example

The interfaces below are deliberately generic. The important parts are the deterministic key, a transaction around intent creation, a queue payload that carries immutable identifiers, and a worker that separates accepted, retryable, and permanent outcomes.

interface RenewalCandidate {
  propertyId: string;
  leaseId: string;
  dueDate: string;
  templateVersion: number;
}

interface ReminderJob {
  key: string;
  intentId: string;
}

interface Queue {
  enqueue(job: ReminderJob, options: { jobId: string }): Promise<void>;
}

const reminderKey = (candidate: RenewalCandidate): string =>
  [
    candidate.propertyId,
    candidate.leaseId,
    "renewal",
    candidate.dueDate,
    candidate.templateVersion,
  ].join(":");

async function admitDailyReminders(runDate: string): Promise<void> {
  const candidates = await db.findRenewalsDueByBusinessDeadline(runDate);

  for (const candidate of candidates) {
    const key = reminderKey(candidate);
    await db.transaction(async (tx) => {
      const intent = await tx.reminderIntents.insertIfAbsent({
        key,
        propertyId: candidate.propertyId,
        leaseId: candidate.leaseId,
        dueDate: candidate.dueDate,
        templateVersion: candidate.templateVersion,
        state: "pending",
      });

      await tx.outbox.insertIfAbsent({
        key: `reminder:${key}`,
        topic: "renewal-reminder",
        payload: { key, intentId: intent.id },
      });
    });
  }
}
Enter fullscreen mode Exit fullscreen mode

The outbox publisher may be interrupted at any point, so it treats publish as repeatable. A queue's unique job ID can suppress some duplicate jobs, but the database uniqueness rule remains the authority because queue retention and deduplication windows vary by implementation.

async function publishOutboxRow(row: OutboxRow, queue: Queue): Promise<void> {
  const job = row.payload as ReminderJob;
  await queue.enqueue(job, { jobId: row.key });
  await db.outbox.markPublished(row.id);
}

class RetryableDeliveryError extends Error {
  constructor(readonly retryAfterMs?: number) {
    super("Delivery should be retried");
  }
}

async function deliverRenewal(job: ReminderJob): Promise<void> {
  const intent = await db.reminderIntents.get(job.intentId);
  if (intent.state === "sent") return;

  const response = await mailer.send({
    idempotencyKey: job.key,
    templateVersion: intent.templateVersion,
    leaseId: intent.leaseId,
  });

  if (response.status === 429) {
    throw new RetryableDeliveryError(parseRetryAfter(response.headers));
  }

  if (response.status >= 400) {
    await db.reminderIntents.markPermanentFailure(intent.id, response.status);
    return;
  }

  await db.reminderIntents.markSent(intent.id, response.messageId);
}
Enter fullscreen mode Exit fullscreen mode

parseRetryAfter needs tests for both the seconds form and the HTTP-date form. Test the less comfortable boundaries too: two scheduler instances admitting the same lease, a publisher interruption after enqueue but before markPublished, a worker interruption after provider acceptance, and a 429 sequence that eventually reaches the dead-letter policy. These tests are more valuable than a happy-path screenshot because they exercise the promises the architecture is supposed to make.

Operating the deadline, not merely the queue

Queue depth is useful, but it is not the service objective. Track the age of the oldest ready renewal job and the distance to its business deadline. Also record counts for admitted, published, claimed, accepted, permanently rejected, and dead-lettered intents. Those stages let an operator distinguish a scheduler that selected nothing from workers that are falling behind.

Alert on time remaining, not on a generic red dashboard. A backlog of 300 jobs may be harmless six hours before the deadline and urgent with six minutes left. Concurrency should respect the mail provider's rate limits; blindly adding workers can create more 429 responses and lengthen recovery. This is where the revenue-per-hour lens matters: one actionable deadline alert beats a dozen infrastructure charts that require interpretation during an incident.

Deployment deserves the same restraint.

Keep the scheduler stateless so overlapping deploys are harmless under the unique intent key. Drain workers before termination, use a visibility timeout longer than normal delivery latency, and ensure a lost worker makes its claim available again. Retain dead-lettered jobs long enough for the actual support cadence. AWS recommends setting a dead-letter queue retention period longer than the source queue's retention period; copying a default without comparing those periods can erase the evidence needed for recovery.

For capacity, estimate recipients per deadline window, provider throughput, retry headroom, and the time needed to drain the worst credible backlog. Your mileage may vary because property portfolios cluster around local business hours. Measure that distribution before choosing worker concurrency. Ship weekly, but rehearse one forced retry and one dead-letter recovery before calling the reminder path done.

When is direct cron sending or a workflow engine better?

The catch is that a queue creates operational inventory. Someone must inspect dead letters, define retention, tune retries, and reconcile intent state. Direct sending in cron is a reasonable runner-up when the list is tiny, duplicate or delayed mail has little consequence, the process has ample runtime, and a human can safely rerun the whole batch. In that case, an outbox plus workers can cost more engineering time than the failure is worth.

At the other extreme, a plain queue is not suitable when renewals require multi-day waits, approvals, cancellations, or several compensating actions. Use a durable workflow engine when the domain is a state machine and operators need to see or alter that state. Stick with a database-backed outbox and queue when the flow is short — admit, publish, deliver, record — and the main problem is isolating retries.

The decision is about guarantees, not fashion. For deadline-bound renewal email, make cron produce durable, uniquely identified work and let workers consume it. Then write down the one unavoidable uncertainty: what happens if provider acceptance succeeds but local acknowledgment does not. That sentence tells you whether provider-side idempotency, tolerance for duplicates, or a more involved reconciliation mechanism is required.

References

Further reading

Start with the two primary references above, then document the deadline, retry ceiling, and duplicate policy for your own reminder domain. Those local decisions determine the design more than a queue brand does.

Top comments (0)