DEV Community

WadeSterling3125
WadeSterling3125

Posted on

Renewal Alerts: User Queue Retries, Dead-Letter Consumers, and Email Webhooks

Short answer: use a durable queue with a visible scheduled time, bounded retries, and a dead-letter state; make the consumer idempotent before choosing a queue product. For a renewal reminder that must wait until a business deadline, a database-backed schedule is usually the cheapest correctness anchor, while a managed broker is useful when delivery latency and throughput matter more than operational simplicity.

The job sounds small: send an email or webhook when an account reaches its renewal window. The failure modes are not small. A worker can crash after the provider accepts a message, a webhook endpoint can return HTTP 429, or a customer can move the deadline while a message is already in flight. I care about revenue per hour, so I want the system to spend complexity only where a missed reminder would cost more than the engineer maintaining it.

A choice matrix for deadline-driven reminders

Option Best fit Main trade-off
Database table plus polling worker Low to moderate volume, strict audit trail Polling adds bounded latency and needs lock discipline
Delayed queue with visibility timeout Predictable delivery windows and bursty work Broker semantics and retention become another operating surface
Workflow or scheduler service Long waits, calendar rules, human review More moving parts and a higher fixed cost
In-process timers Local experiments only Process restarts lose timers and make retries unsafe

My default is the first row, with an option to move the delivery step to a broker later. Store the reminder intent, not just a transient job. That record gives support a timeline, lets a reconciler find stuck work, and makes a changed renewal deadline explicit.

There is no universal best queue. The right answer depends on how late a reminder may be and what a duplicate send costs. A one-minute delay might be fine for a weekly renewal digest; it is not fine for a contract that expires at 09:00 in the customer's local time.

That boundary matters.

What should a queue do for user reminders, retries, dead letters, and email failures?

Treat each reminder as a small state machine. A useful set is scheduled, ready, delivered, and dead_letter. Keep attempt_count, next_attempt_at, a stable dedupe_key, and the last provider response beside it. The dead-letter state is a business decision: it means an operator or an automated review must decide what to do next, not that the system should retry forever.

The queue should release work only when next_attempt_at <= now(). In PostgreSQL, workers can claim a batch without waiting on rows held by another worker:

import { Pool } from "pg";

const pool = new Pool({ connectionString: process.env.DATABASE_URL });

export async function claimReminders(limit = 50) {
  const client = await pool.connect();
  try {
    await client.query("BEGIN");
    const result = await client.query(
      `SELECT id, dedupe_key, channel, payload
       FROM reminder_jobs
       WHERE state = 'ready' AND next_attempt_at <= now()
       ORDER BY next_attempt_at, id
       FOR UPDATE SKIP LOCKED
       LIMIT $1`,
      [limit],
    );
    await client.query(
      `UPDATE reminder_jobs
       SET state = 'processing', lease_until = now() + interval '2 minutes'
       WHERE id = ANY($1::uuid[])`,
      [result.rows.map((row) => row.id)],
    );
    await client.query("COMMIT");
    return result.rows;
  } catch (error) {
    await client.query("ROLLBACK");
    throw error;
  } finally {
    client.release();
  }
}
Enter fullscreen mode Exit fullscreen mode

SKIP LOCKED prevents two workers from claiming the same row in one pass, but it does not make the external send exactly once. The lease must expire, and a reconciler should return expired processing rows to ready. Keep that reconciliation job boring. It is insurance against a worker disappearing between the provider call and the database update.

Retries need classification. Network timeouts, HTTP 429, and most 5xx responses are usually retryable; a malformed address or a rejected authentication token needs a dead-letter path or an alert. Honor a provider's Retry-After value when present. Otherwise use exponential backoff with jitter, for example 30s, 2m, 8m, 32m, capped by the business deadline. After the final attempt, preserve the payload and response so a replay is an intentional action.

How do idempotent consumers stop duplicate webhook and email sends?

The consumer owns the duplicate problem. Put a unique constraint on the dedupe key, then record an outbound attempt before acknowledging the queue message. The key can be account_id + renewal_date + channel; include a revision if changing the message should create a new delivery.

type Reminder = {
  id: string;
  dedupeKey: string;
  channel: "email" | "webhook";
  payload: Record<string, unknown>;
};

export async function deliver(reminder: Reminder) {
  const inserted = await db.query(
    `INSERT INTO delivery_log (dedupe_key, status)
     VALUES ($1, 'started')
     ON CONFLICT (dedupe_key) DO NOTHING
     RETURNING dedupe_key`,
    [reminder.dedupeKey],
  );

  if (inserted.rowCount === 0) return "already-started";

  const response = await sendToProvider(reminder.channel, reminder.payload);
  await db.query(
    `UPDATE delivery_log
     SET status = 'accepted', provider_id = $2, accepted_at = now()
     WHERE dedupe_key = $1`,
    [reminder.dedupeKey, response.id],
  );
  return "sent";
}
Enter fullscreen mode Exit fullscreen mode

There is still a narrow crash window: the provider may accept the request while the process dies before accepted is stored. A provider-side idempotency key closes that window when available. If it is not available, choose a conservative policy: mark the job for review instead of blindly sending again. Duplicate email is a customer-facing incident; a delayed email is often recoverable.

I once assumed a retry count was enough. It was not. The useful signal was the combination of dedupe_key, provider response, and the deadline that was in force when the job was created. That data made a replay explainable in a support ticket.

The failure timeline is the real design

Create the reminder in the same transaction as the renewal event, using an outbox row if the event originates in another service. A scheduler promotes rows to ready shortly before their due time. The worker claims a lease, sends with a stable key, and records the result. A reconciler scans leases and deadlines every few minutes. The important part is the timeline: at 08:55 the job is still scheduled, at 08:59 it is ready, at 09:00 the provider call starts, and at 09:00:03 the process can vanish before the database write. Those four moments need different recovery actions, and collapsing them into one sent boolean hides the exact state support will need when a customer asks why a reminder arrived twice. A short lease, an immutable attempt log, and a deadline revision let the next worker distinguish a slow provider from a lost process without guessing.

The business deadline belongs in the retry rule. If the next backoff would pass the deadline, stop waiting and route the job according to policy: send immediately, notify an operator, or suppress it. Make that choice visible in metrics. Track scheduled-to-ready lag, provider latency, attempts per delivery, dead-letter age, and duplicate suppression count. Alert on a growing dead-letter age, not just on worker CPU.

Use a fake clock in tests. Advance it across daylight-saving transitions and a customer's timezone boundary. Assert that two workers cannot claim one row, that a 429 honors Retry-After, and that replaying the same message does not create a second delivery record. In production, sample full payloads carefully; a reminder may contain contract data that should not land in logs.

Ship the smallest loop first. A weekly release cadence is easier when the queue contract is a plain table and the provider adapter is replaceable. Outsource the undifferentiated transport only after the state machine and audit fields are stable.

When a database queue is the wrong tool

The catch is latency at scale. Polling every few seconds creates load and still gives a worst-case delay equal to the polling interval. Choose a broker with delayed delivery when you need tighter latency, high fan-out, or built-in retention and redrive controls. Choose a workflow engine when reminders wait for months, depend on calendars, or require human approval.

Stay with the database approach when volume is modest, auditability is central, and your team cannot justify another always-on service. It is not suitable when one region must process millions of due messages in a narrow minute or when the provider requires specialized streaming semantics.

Your mileage may vary. Measure the deadline miss rate and operator minutes for a real week before migrating. The queue is only one part of the promise; idempotency, deadline policy, and recovery records decide whether a reminder is trustworthy.

References

Top comments (0)