DEV Community

ColbyHayes3521
ColbyHayes3521

Posted on

Schedule Property User Reminders: Minute Polling, Queue Workers, Idempotent Webhooks

A reminder system should optimize for recovery, not perfect timing. For property-management webhooks, the practical default is a PostgreSQL due_at ledger, a minute poller that leases due rows, and a queue worker that sends each delivery with a stable idempotency key. A timer alone cannot tell an operator what was missed after a deploy or process restart.

Choice Recovery after interruption Duplicate boundary Best fit
Database ledger + minute poller + queue Due rows remain queryable; expired leases can be reclaimed Stable key at the webhook receiver Default for operationally important reminders
Queue-native delayed messages Recovery lives in queue tooling Depends on the consumer contract Very high volume with mature queue operations
One in-process timer per reminder Process memory is the schedule Usually application-specific Small, disposable tasks where loss is acceptable

Recommendation: keep schedule state in PostgreSQL, use cron only as a wake-up signal, and let a bounded worker pool perform delivery. The catch is that this design adds a table, a queue, and a reconciliation loop. If reminders are disposable and a missed process timer has no business cost, that machinery isn't justified.

Rehearse the crash before choosing a schema

Consider one scheduled inspection reminder, rem_018F, due at 09:00. The dispatcher claims it at 09:00:12 and publishes a job. A worker posts the webhook at 09:00:19. The receiving property system commits the notice, but the worker exits before it can mark the local row as sent. At 09:02:12, the lease expires.

What happens next is the design test. Dropping the row loses an acknowledged customer promise. Retrying with a new identity can create a second notice. Retrying the same logical delivery with the same idempotency key lets a cooperative receiver recognize the prior effect. The local ledger also tells an operator why that retry exists. This single crash window determines the schema, worker contract, and recovery procedure; cron syntax doesn't.

That's the problem.

How should Node.js schedule user reminder notifications with minute polling and PostgreSQL idempotency?

Treat due_at as data, not as a command to execute at an exact instant. Every minute, one or more Node.js schedulers claim a small batch of pending rows whose due_at has passed. A claim writes a short lease before publishing job IDs to the queue. Workers then load the current row, deliver the webhook, and record the outcome.

Cron has one job: wake the dispatcher. It doesn't own correctness.

That distinction matters during the dull failures that consume a solo founder's week: a deploy overlaps the minute boundary, queue publication stops halfway through a batch, or a worker exits after the remote property system accepts a request but before the local status update commits. The database still shows what is due, what is leased, and what has completed. An operator can answer "what happened to lease-renewal reminder rem_018F?" without reconstructing process logs. This is the revenue-per-hour lens I use for infrastructure decisions: recovery should be a query and a replay, not a forensic project.

A one-minute poll interval also defines timing precision. A reminder may be claimed nearly a minute after due_at, plus queue and delivery time. I'm not sure tighter precision creates user value for every reminder type; rent-payment nudges and inspection notices rarely need second-level dispatch. If the product promise requires sub-minute delivery, measure the full lag distribution and shorten the interval or move to delayed queue messages. Your mileage may vary.

Recovery criterion: can an interrupted batch explain itself?

A recoverable design needs durable states. pending means eligible once due_at and next_attempt_at pass. A live lease_until temporarily assigns work. sent is terminal. dead means automated retries have stopped and an operator must inspect the delivery. Keep the original payload or a stable payload reference beside that state so a replay doesn't silently build a different event.

Use a lease rather than flipping directly from pending to processing. A permanent processing flag strands work when a dispatcher dies. A lease expires. Another dispatcher can then claim the row.

The claim must be one database operation. FOR UPDATE SKIP LOCKED lets concurrent dispatchers choose different due rows, while the outer update records ownership and returns the claimed jobs. Batch limits protect PostgreSQL and the downstream property-management endpoint from a recovery surge. Start small. Shipping weekly is easier when capacity is an explicit knob instead of an accidental side effect of adding replicas.

Two timestamps deserve separate meanings. due_at is the user's requested schedule and should not move during retries. next_attempt_at is delivery policy. Combining them destroys the audit trail because a retry looks like the user rescheduled the reminder.

Operational recovery also needs a sweeper. It can use the same claim query because an expired lease makes an unfinished row eligible again. Add counts for overdue pending rows, oldest due age, active leases, attempts, and terminal failures. Alert on age, not merely queue depth: ten reminders overdue by 40 minutes can matter more than ten thousand future reminders.

Duplicate criterion: where does idempotency actually end?

A queue normally gives at-least-once work, which is the useful guarantee here. Exactly-once webhook delivery cannot be created solely by the sender: the worker can send a request successfully and terminate before it records sent. On recovery, it has to try again.

So the business boundary belongs at the receiver. Derive one stable key from the logical delivery ID, such as property-reminder:rem_018F, and reuse it for every attempt. The receiver stores that key under a unique constraint in the same transaction as its business effect. If the key already exists, it returns the prior success semantics without applying the effect twice. No new key per retry.

This is the hard line.

If you don't control the receiver and it offers no idempotency contract, you can reduce duplicates but cannot promise their absence. A local sent flag prevents ordinary repeats, yet it cannot close the crash window between the remote side effect and the local commit. For SMS, email, or a third-party webhook without receiver-side deduplication, state that limitation in the product behavior and choose a retry policy that balances missed reminders against duplicates.

Rate limiting is a separate outcome, not proof of delivery. HTTP 429 Too Many Requests indicates that the client sent too many requests in a period, and the response may include Retry-After. Honor that value when it is present; otherwise apply capped exponential backoff with jitter. Don't let one property integration consume every worker slot. Partition concurrency by destination or account, then place exhausted jobs in a dead-letter path for inspection. The AWS SQS documentation describes dead-letter queues as targets for messages that were not processed successfully after a configured number of receives; the same operational concept applies even when the queue implementation differs.

A TypeScript claim-and-deliver example

The example below keeps SQL inside TypeScript so the control flow is visible in one place. The queue carries only the delivery ID. That avoids stale payload copies and makes the PostgreSQL row the authority during replay.

The ID is enough.

type Delivery = {
  id: string;
  targetUrl: string;
  payload: unknown;
  attempts: number;
};

type Db = {
  query<T>(sql: string, values?: unknown[]): Promise<{ rows: T[] }>;
};

type Queue = { publish(job: { deliveryId: string }): Promise<void> };

async function claimDue(db: Db, limit = 100): Promise<Delivery[]> {
  const result = await db.query<Delivery>(
    `
      UPDATE reminder_deliveries AS d
      SET lease_until = NOW() + INTERVAL '2 minutes',
          attempts = attempts + 1
      WHERE d.id IN (
        SELECT id
        FROM reminder_deliveries
        WHERE status = 'pending'
          AND due_at <= NOW()
          AND next_attempt_at <= NOW()
          AND (lease_until IS NULL OR lease_until < NOW())
        ORDER BY due_at, id
        FOR UPDATE SKIP LOCKED
        LIMIT $1
      )
      RETURNING
        d.id,
        d.target_url AS "targetUrl",
        d.payload,
        d.attempts
    `,
    [limit],
  );

  return result.rows;
}

async function dispatchMinute(db: Db, queue: Queue): Promise<void> {
  const claimed = await claimDue(db);
  await Promise.all(
    claimed.map((delivery) =>
      queue.publish({ deliveryId: delivery.id }),
    ),
  );
}
Enter fullscreen mode Exit fullscreen mode

The two-minute lease is an example policy, not a universal constant. Set it longer than normal queue-publication time, then watch lease-expiry counts. If publication fails midway, published jobs may run and unpublished rows become claimable after lease expiry. Duplicate publication is fine because the worker rechecks state and preserves the same idempotency key.

Delivery code should classify outcomes rather than retry everything. This abbreviated worker treats any 2xx response as accepted, reschedules a 429 using Retry-After when possible, and sends other non-success responses through the retry policy. The database update methods should use conditional updates so a stale worker cannot overwrite a newer terminal state.

type Store = {
  loadPending(id: string): Promise<Delivery | null>;
  markSent(id: string): Promise<void>;
  reschedule(id: string, nextAttemptAt: Date): Promise<void>;
  markDead(id: string, reason: string): Promise<void>;
};

function retryAt(header: string | null, attempts: number): Date {
  if (header && /^\d+$/.test(header)) {
    return new Date(Date.now() + Number(header) * 1_000);
  }

  const capMs = 15 * 60_000;
  const baseMs = Math.min(capMs, 2 ** attempts * 1_000);
  const jitterMs = Math.floor(Math.random() * Math.max(1, baseMs / 4));
  return new Date(Date.now() + baseMs + jitterMs);
}

async function deliver(store: Store, deliveryId: string): Promise<void> {
  const delivery = await store.loadPending(deliveryId);
  if (!delivery) return;

  const response = await fetch(delivery.targetUrl, {
    method: 'POST',
    headers: {
      'content-type': 'application/json',
      'idempotency-key': `property-reminder:${delivery.id}`,
    },
    body: JSON.stringify(delivery.payload),
  });

  if (response.ok) {
    await store.markSent(delivery.id);
    return;
  }

  if (delivery.attempts >= 8) {
    await store.markDead(delivery.id, `HTTP ${response.status}`);
    return;
  }

  const retryAfter = response.status === 429
    ? response.headers.get('retry-after')
    : null;
  await store.reschedule(
    delivery.id,
    retryAt(retryAfter, delivery.attempts),
  );
}
Enter fullscreen mode Exit fullscreen mode

There is a deliberate omission: this sample doesn't pretend queue publication and a PostgreSQL update share a transaction. If losing that handoff window is unacceptable, add a transactional outbox. Insert an outbox row in the same transaction that creates the reminder, then have the minute dispatcher publish from that outbox and mark it published. The consumer still remains idempotent because an outbox publisher can repeat work after a crash.

Test the failure boundaries, not only the happy path. Freeze time around due_at; run two claimers concurrently; terminate a dispatcher after 37 of 100 publishes; deliver the same queue job twice; return 429 with Retry-After: 120; and stop a worker after the receiver commits but before markSent. The expected result is boring: every due row is eventually visible for recovery, while each cooperative receiver applies one business effect per delivery key.

When is the runner-up a better choice?

Stick with queue-native delayed delivery when reminder volume makes minute polling wasteful, the queue supports the delay horizon you need, and the team already operates queue replay, retention, and dead-letter workflows. It removes the polling query from the hot path. The trade-off is that schedule inspection and correction now depend more heavily on queue capabilities, so keep a durable application record of the intended due_at even if the queue owns wake-up timing.

An in-process scheduler is suitable when work is genuinely disposable: local cache refreshes, temporary previews, or development fixtures. It is not suitable for tenant notices whose absence creates support work. Process restarts and deploys are normal operations, so memory cannot be the only record of a customer promise.

Use the database-led pattern when operational recovery is the deciding axis. It costs more moving parts than a timer and less specialized operational knowledge than making a queue the system of record. Most important, it leaves an inspectable ledger: what should have happened, what is leased, what was retried, and what needs human attention. Outsource the undifferentiated delivery transport if that saves time, but keep those business facts under application control.

References

Top comments (0)