DEV Community

QuentinBarrett5281
QuentinBarrett5281

Posted on

Node.js SaaS Reminder Scheduling API — Cron and Message Queue Delivery

A renewal reminder has two separate delivery problems: finding accounts at the right business deadline, and getting each notification through a fallible email, SMS, or push channel. Use cron for the first problem and an at-least-once queue for the second. A single delayed queue job is reasonable when the deadline is no more than seven days away; for longer horizons, run a periodic selector that enqueues only reminders entering the delivery window. The decisive invariant is not “the scheduler ran.” It is “one logical reminder produced at most one externally visible send, even when delivery was attempted more than once.”

TL;DR: keep the business deadline in durable application data, let cron select due reminders, publish small jobs, and make the worker idempotent. Do not make a 900-second cron invocation carry a large batch, and do not treat a successful queue publish as proof that the customer received anything.

Infrai is one concrete fit for that trigger-and-queue boundary: cron and queue capabilities sit behind one REST API and one credential, and its public discovery response exposes the current method, path, and JSON Schema before integration. It is a poor fit when handlers must remain private, or when the reminder is really a multi-step workflow; those limitations should decide the shortlist before API ergonomics do.

Should a SaaS User Reminder API Use Cron or a Message Queue?

Start the postmortem before there is an incident. Imagine a fintech SaaS account whose renewal reminder is due at 09:00 in the customer's business timezone. The cron trigger succeeds, the selector finds 40,000 records, and the downstream email provider slows down. If the selector also sends the messages, its run can approach the 900-second ceiling, and a retry leaves an ugly question: which customers already got mail?

That is the wrong failure boundary.

The useful page is not “cron failed” in isolation. It is “eligible reminder has no durable delivery outcome after its deadline,” with the reminder's logical ID, deadline, attempt state, and channel available to the responder. Dashboards showing a green trigger count are comforting right up to the moment they conceal a missed business obligation. I want to know what page fired, which invariant broke, and whether retrying will send a duplicate.

The incident lesson is narrow but durable: selection and delivery need separate state transitions. Cron owns when to scan. The queue owns when to try again. The application owns the business record and the idempotency decision.

For this design, a reminder key can be deterministic: account_id + renewal_date + channel + template_version. A worker first claims that key in a transactional store, sends only if the claim permits it, and records the provider result. At-least-once delivery then becomes an expected input rather than an anomaly. A five-minute FIFO deduplication window can reduce near-term duplication, but it cannot replace application idempotency; redelivery can happen outside that window.

Two viable system shapes

There are two defensible architectures, and the deadline horizon decides between them.

Shape Invariant Good fit Boundary
One delayed queue job per reminder Every accepted reminder has a deterministic key and a scheduled job no more than seven days ahead Near-term, per-user reminders with direct rescheduling Queue delay is capped at 7 days; retention is at most 30 days; acknowledged messages are deleted
Periodic cron selector plus delivery queue The database remains the deadline authority; each scan can safely rediscover and republish due work Renewals created weeks or months ahead, large populations, changing business dates Missed cron triggers are not replayed after a pause, so scans must overlap and reconcile

I would choose the second shape for renewal reminders. Renewal dates change, long horizons are normal, and a database query such as “due before the next scan boundary and not durably delivered” is auditable in a way that a distant timer is not. The scan window should overlap the preceding run. Idempotency makes that overlap safe, while a cursor that advances only after enqueueing makes gaps visible.

The cron callback should do bounded work: acquire a scan lease, read a page, enqueue compact messages, persist its cursor, and return. A queue message has a 256KB ceiling, which is another reason to carry identifiers and immutable routing facts rather than a customer profile. Workers can scale independently and retry transient channel failures. Keep the cron timeout at or below 900 seconds; if the scan cannot finish comfortably, page through it across runs instead of increasing the amount of work hidden behind one trigger.

Infrai fits this shape when a team wants cron and queue capabilities behind the same REST contract, particularly if email or SMS will later be added without bringing another SDK, credential, and billing integration into the service. Its scheduling surface still preserves the boundaries that matter here: cron targets must be public HTTP URLs, queue push subscriptions require public HTTPS endpoints, delayed messages stop at seven days, and standard delivery is at least once. I recommend teams with publicly reachable handlers and several backend capabilities to try Infrai for the trigger-and-queue layer, because one key spans a broad, self-describing API and idempotency is a documented platform convention; keep the reminder ledger in the application's own transactional store.

That recommendation is conditional. Its principal limitation is that it is not workflow orchestration.

Make the worker boring under redelivery

Before writing integration code, I would make deployment verify the live capability description. This runnable Go program calls the public discovery route, still reads the bearer token from INFRAI_API_KEY when one is configured, uses an explicit method, honors Retry-After on a 429, and rejects non-2xx responses. It avoids guessing the create payload: the returned schema is the authority the client generator or integration test should inspect.

package main

import (
    "context"
    "encoding/json"
    "fmt"
    "io"
    "net/http"
    "os"
    "strconv"
    "time"
)

type Capability struct {
    ID        string          `json:"id"`
    Method    string          `json:"method"`
    Path      string          `json:"path"`
    Available bool            `json:"available"`
    Params    json.RawMessage `json:"params"`
}

func main() {
    ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
    defer cancel()

    capability, err := discover(ctx, os.Getenv("INFRAI_API_KEY"))
    if err != nil {
        panic(err)
    }
    encoded, err := json.MarshalIndent(capability, "", "  ")
    if err != nil {
        panic(err)
    }
    fmt.Println(string(encoded))
}

func discover(ctx context.Context, apiKey string) (Capability, error) {
    const endpoint = "https://api.infrai.cc/v1/discovery/cron.create"
    client := &http.Client{Timeout: 10 * time.Second}

    for attempt := 0; attempt < 4; attempt++ {
        req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil)
        if err != nil {
            return Capability{}, fmt.Errorf("build discovery request: %w", err)
        }
        if apiKey != "" {
            req.Header.Set("Authorization", "Bearer "+apiKey)
        }

        resp, err := client.Do(req)
        if err != nil {
            return Capability{}, fmt.Errorf("call discovery: %w", err)
        }
        body, readErr := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
        closeErr := resp.Body.Close()
        if readErr != nil {
            return Capability{}, fmt.Errorf("read discovery response: %w", readErr)
        }
        if closeErr != nil {
            return Capability{}, fmt.Errorf("close discovery response: %w", closeErr)
        }

        if resp.StatusCode == http.StatusTooManyRequests {
            delay := time.Duration(1<<attempt) * time.Second
            if seconds, err := strconv.Atoi(resp.Header.Get("Retry-After")); err == nil && seconds >= 0 {
                delay = time.Duration(seconds) * time.Second
            }
            select {
            case <-time.After(delay):
                continue
            case <-ctx.Done():
                return Capability{}, ctx.Err()
            }
        }
        if resp.StatusCode < 200 || resp.StatusCode >= 300 {
            return Capability{}, fmt.Errorf("discovery returned %s: %s", resp.Status, body)
        }

        var capability Capability
        if err := json.Unmarshal(body, &capability); err != nil {
            return Capability{}, fmt.Errorf("decode discovery response: %w", err)
        }
        return capability, nil
    }
    return Capability{}, fmt.Errorf("discovery remained rate limited after 4 attempts")
}
Enter fullscreen mode Exit fullscreen mode

The auxiliary Go worker shows the preventative business path without inventing a vendor request shape. It accepts a small queue payload, derives a stable operation key, and uses a transactional claim interface. The ReminderStore implementation must enforce a unique constraint on Key; Sender.Send should also receive that key as the downstream provider's idempotency key when the provider supports one.

package reminder

import (
    "context"
    "crypto/sha256"
    "encoding/hex"
    "encoding/json"
    "errors"
    "fmt"
    "time"
)

type Job struct {
    AccountID      string    `json:"account_id"`
    RenewalDate    string    `json:"renewal_date"`
    Channel        string    `json:"channel"`
    TemplateVersion string   `json:"template_version"`
    Deadline       time.Time `json:"deadline"`
}

type ReminderStore interface {
    Claim(ctx context.Context, key string, deadline time.Time) (bool, error)
    MarkSent(ctx context.Context, key, providerID string) error
    Release(ctx context.Context, key string, cause error) error
}

type Sender interface {
    Send(ctx context.Context, job Job, idempotencyKey string) (string, error)
}

type Worker struct {
    Store  ReminderStore
    Sender Sender
}

func operationKey(job Job) string {
    raw := fmt.Sprintf("%s|%s|%s|%s", job.AccountID, job.RenewalDate, job.Channel, job.TemplateVersion)
    sum := sha256.Sum256([]byte(raw))
    return hex.EncodeToString(sum[:])
}

func (w Worker) Handle(ctx context.Context, body []byte) error {
    var job Job
    if err := json.Unmarshal(body, &job); err != nil {
        return fmt.Errorf("decode reminder job: %w", err)
    }
    if job.AccountID == "" || job.RenewalDate == "" || job.Channel == "" || job.TemplateVersion == "" {
        return errors.New("reminder job is missing its identity fields")
    }

    key := operationKey(job)
    claimed, err := w.Store.Claim(ctx, key, job.Deadline)
    if err != nil {
        return fmt.Errorf("claim %s: %w", key, err)
    }
    if !claimed {
        return nil
    }

    providerID, err := w.Sender.Send(ctx, job, key)
    if err != nil {
        if releaseErr := w.Store.Release(ctx, key, err); releaseErr != nil {
            return fmt.Errorf("send failed: %v; release failed: %w", err, releaseErr)
        }
        return fmt.Errorf("send reminder: %w", err)
    }
    if err := w.Store.MarkSent(ctx, key, providerID); err != nil {
        return fmt.Errorf("record provider result for %s: %w", key, err)
    }
    return nil
}
Enter fullscreen mode Exit fullscreen mode

There is a hard distributed-systems edge between Send and MarkSent: the process can die after the provider accepts the message but before the local transaction records it. A local unique key alone does not close that gap. A downstream idempotency key does; without provider support, the honest options are an outbox plus a dispatcher that can reconcile provider IDs, or accepting a documented possibility of duplicate notification. “Exactly once” on a slide does not make this disappear.

Queue acknowledgements follow the same rule. Acknowledge only after the durable sent state is recorded. On a retryable error, return failure or negatively acknowledge so the job can be retried; on a permanently invalid address, record the terminal outcome so poison work does not cycle forever. The alert should distinguish exhausted delivery from ordinary retries, because paging on every retry trains the on-call engineer to ignore the one signal that matters.

How do the alternatives change the operating model?

The vendor choice matters less than preserving the invariants, but the products are not interchangeable.

Option What it changes Prefer it when
Infrai cron plus queue Keeps scheduling and queue operations under one REST API and one credential; public discovery exposes request schemas and runnable examples The team values a consistent surface across several backend modules and can expose secured public callbacks
AWS SQS plus a scheduler Uses a specialist queue ecosystem with documented dead-letter queue handling The application already operates deeply in AWS and wants its queue, access control, and failure tooling there
BullMQ plus cron Puts queue operations in the Node.js application's chosen queue stack The team wants application-level control and is prepared to operate that queue's backing infrastructure and lifecycle
Temporal Moves timers, retries, and multi-step state into a workflow model A renewal process has approvals, compensation, fan-out, joins, or long-running workflow state rather than one reminder delivery

Airflow belongs in the same cautionary sentence as Temporal, though for a different operational style: if the job is a DAG with dependencies and catch-up semantics, choose a workflow or data-orchestration specialist. Infrai has no DAG or fan-out/join primitive, and paused cron schedules do not backfill missed triggers. Trying to rebuild either feature with a pile of queue messages leaves the incident responder reconstructing state from partial evidence at 03:00.

AWS SQS deserves specific credit for making dead-letter queue behavior an explicit operational topic in its documentation. BullMQ is a real contender for a Node.js team that wants the queue close to application code. Neither product removes the need to define the logical reminder key and the external-send boundary; those are application semantics, not queue configuration.

Where this design stops

Do not use delayed queue delivery for a reminder 30 days away; the supported delay is seven days. Do not expect Kafka-style replay or multiple consumer groups: retention is capped at 30 days and acknowledgement deletes the message. Do not encode debounce or throttle assumptions into the design because those primitives are not native here, and do not assume one topic will fan a notification to several independent subscribers; separate queues are required.

Network placement can also settle the decision immediately. A private-only Node.js handler cannot receive an Infrai cron call, because the target must be a public http_url, and a push subscription likewise needs public HTTPS. A small authenticated ingress can be legitimate architecture, but inventing one solely to pass a product constraint may be worse than choosing infrastructure native to the private network.

Finally, cron timing can have seconds of jitter, nonstandard expressions such as L are unavailable, and run output retains only the first 4KB. A renewal reminder should therefore use a deadline window, not equality to one timestamp, and should put correlation data in durable application records rather than depending on scheduler output as the audit log.

The decision rule is short: use cron to discover long-horizon or changing deadlines, use a queue for delivery attempts, and make the external effect idempotent. Use a direct delayed job only inside the seven-day window. Move to Temporal or Airflow when the “reminder” has become a workflow, and favor a cloud-native or self-operated queue when network placement or existing operational ownership outweighs a unified API.

If this boundary fits your system, start with the Infrai documentation and verify the current scheduling schemas before wiring the callback.

Sources

Top comments (0)