DEV Community

EvanShepherd8274
EvanShepherd8274

Posted on

Daily Report Email Dispatch: Rate Limits, Queue Backpressure, and HTTPS Push Boundaries

Short answer: put daily report email work in a durable sending queue, pace workers to the provider's rate limit, and treat a public HTTPS subscriber as a delivery adapter rather than the queue itself. That keeps a slow recipient from holding the scheduler hostage while preserving a simple retry story.

I run a one-person SaaS, so the useful metric is revenue per hour, not how many components I can diagram. A daily report is a fan-out job: one schedule can create thousands of sends, and the rate-limited worker pool must drain them without turning a temporary 429 into a duplicate email storm. Ship weekly. Outsource the undifferentiated queue mechanics.

Can a daily report email queue serve public HTTPS subscribers safely?

Design Latency behavior Cost and operations Use it when
In-process loop from the scheduler Fast for tiny batches; blocked by one slow send Lowest setup cost, weakest recovery Fewer sends than one run's time budget and no strict retry requirement
Durable queue with paced workers Predictable drain time; backlog is visible One queue plus worker state to operate The normal choice for rate-limited daily reports
Queue plus public HTTPS subscriber Adds network hop and endpoint auth Good separation, more moving parts A separate service owns email credentials or scaling

The middle row is the sensible default. Keep the scheduler responsible for finding due reports and enqueueing immutable jobs. Let workers own pacing, retry classification, and acknowledgement. Add an HTTPS subscriber only when an ownership boundary justifies it; “public” should describe reachability, not an unauthenticated endpoint.

Start small.

Queue telemetry: measure before increasing worker count

Start with a durable record for each intended recipient. Give it a stable deliveryId, a scheduled time, an attempt count, and a status such as pending, sent, or dead. The queue message carries the same ID. A worker claims one message, sends it, records the result, and acknowledges only after the record is durable.

That order matters. At-least-once queues can redeliver after a process crash. The email adapter must therefore accept an idempotency key, or the worker must atomically record a send token before handing off. The exact mechanism varies by provider, but the invariant does not: a retry may run twice; the recipient should observe one report.

For pacing, use a token bucket or a fixed inter-send delay. If the allowed rate is 20 requests per second, a 50 ms spacing is a useful first approximation; measure the provider's response headers and adjust. A 429 is not a permanent failure. Requeue it with exponential backoff and jitter, cap the delay, and stop after a bounded attempt count. A malformed address is permanent and belongs in a dead-letter path. In a real run, that policy also has to account for a report with 8,000 recipients, a provider window that resets every minute, and a deploy that pauses workers for 30 seconds: the queue should retain the due timestamp, spread work across the remaining window, and expose the resulting age rather than silently dropping the tail.

Here is the core loop in TypeScript. It is deliberately an interface, so the same policy can sit above a hosted queue, a database table, or a small self-hosted broker.

type Job = {
  deliveryId: string;
  payload: { reportId: string; recipient: string };
  attempt: number;
};

type SendResult = "sent" | "retry" | "dead";

const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));

function backoff(attempt: number): number {
  const base = Math.min(60_000, 1_000 * 2 ** attempt);
  return Math.round(base * (0.8 + Math.random() * 0.4));
}

async function drain(
  next: () => Promise<Job | null>,
  send: (job: Job, idempotencyKey: string) => Promise<SendResult>,
  retry: (job: Job, delayMs: number) => Promise<void>,
  deadLetter: (job: Job) => Promise<void>,
  ratePerSecond: number,
): Promise<void> {
  const interval = 1_000 / ratePerSecond;
  for (;;) {
    const job = await next();
    if (!job) return;

    const result = await send(job, job.deliveryId);
    if (result === "retry" && job.attempt < 6) {
      await retry({ ...job, attempt: job.attempt + 1 }, backoff(job.attempt));
    } else if (result === "dead" || job.attempt >= 6) {
      await deadLetter(job);
    }
    await sleep(interval);
  }
}
Enter fullscreen mode Exit fullscreen mode

The loop intentionally does not sleep before a retry is scheduled; the queue's availableAt timestamp owns that delay. That makes a restart safe and lets several workers share one global limit when the queue supports a distributed rate limiter. If it does not, run one pacing worker for this stream or coordinate tokens in a database row.

Retry ledger rollout checkpoints

The first failure mode is scheduler coupling. If the cron request waits for every email, a provider slowdown turns a one-minute trigger into a timeout. The next run starts while the first is still active, and now the same report is enqueued twice. Separate “discover due reports” from “deliver jobs,” and make the discovery query claimable with a lease.

The second is an HTTPS endpoint treated as a push queue. HTTP gives you a request timeout and a response code; it does not give you durable storage, ordering, or replay by itself. The subscriber should verify a signature, reject an old timestamp, and return a 2xx only after it has persisted the event. A 5xx or timeout asks the sender to retry. Keep the endpoint idempotent because retries are normal.

The third is retrying everything. DNS failures, throttling, and a 503 deserve different policies from an invalid address or a rejected payload. Store the provider classification with the attempt. This tiny field saves a lot of forensic time when a customer asks why yesterday's report arrived late.

I keep one ugly test in the suite: kill the worker after the provider accepts a message but before the acknowledgement. The next delivery must reuse the same deliveryId. It is not glamorous. It catches the expensive bug.

Subscriber governance data rules

Celery documents a task queue model with workers and brokers; BullMQ provides a Redis-backed job model; Temporal models durable workflows. Those are different operational envelopes, not a ranking. A small report sender may only need a database-backed queue and a timer. A workflow with human approval, long pauses, or multi-step compensation may justify a workflow engine.

The comparison axis I use is recovery ownership. Can I inspect a stuck job, replay one delivery, rotate credentials, and explain a late email at 2 a.m.? If the answer requires a specialist on call, the system is too large for a one-person SaaS. Your mileage may vary when compliance requires an audited workflow history or a regional isolation boundary.

The catch is that a queue-first design is not suitable when the report must be generated synchronously inside an interactive request, or when a recipient cannot expose any callback path and you have no worker runtime. In those cases, a simple scheduled process with a local outbox can be the better fit. Stick with the smallest mechanism that gives you durable intent, bounded retries, and observable backlog.

Before shipping, measure queue age, oldest attempt, send latency, 429 rate, and dead-letter count. Alert on age, not only on worker health: a fleet of healthy workers can still be under-provisioned. Set a drain deadline for the daily run and record which recipients were deferred. That turns “the report is late” into a query with an answer.

References

Top comments (0)