← Back to Blog

The Hard Part of a Reminder System Is Deciding Not to Send

AnnMax · November 25, 20267 min read

The Decision Is the Product

CertTrack is the .NET + Vue product line in my cert-track repo. The "cert" is a worker's qualification credential — a forklift licence, a confined-space card — not a TLS certificate. When one is about to expire, the employer gets an email. It is one of three mutually exclusive product lines, and the storefront in front of it is six languages of plain static HTML whose trial button is a mailto: link that deliberately refuses to collect an address. A reminder product that will not take your email — an easy constraint to respect.

There is no cron. One BackgroundService runs three independent 30-minute loops — expiry scan, email dispatch, payment reconciliation — and the split between the first two is the design: the scan loop answers should this be sent, and when and writes a row into ntf_email_outbox; the dispatch loop answers how and knows no business rules. Outbox, here, exists to keep the "should I" code away from the "send it" code. The mail goes out through the Resend HTTP API from remind@annmax1983.com, built by templates that are plain constants — one method per letter, every user-supplied value HTML-escaped.

One note before the code: this repo's comments are Chinese. Where I quote a comment below, I have translated it.

The Dedupe Key Has to Contain the Expiry Date

The scan runs every 30 minutes and re-derives the same reminders each time, so something has to remember what already went out. That was a key of daysBefore|toEmail — tier and recipient, nothing else — checked against ntf_reminder_log, a table that is never purged. The key is now this:

// The key carries dueAt: once a renewal changes the expiry date, the new
// date must not be permanently suppressed by the old tier record.
var sentKeys = await _logRepo.GetSentKeys(accountId, bizType, bizId, new List<int> { days });
if (sentKeys.Contains($"{dueAt:s}|{days}|{toEmail}")) return;

await _outboxRepo.AddIgnoreDuplicate(new NtfEmailOutboxDbModel { ... });

That line is the fix. Before it, a certificate reminded at "30 days" wrote 30|supervisor@site.com into the log forever. The worker renewed, the credential got a fresh expiry a year out, and that next cycle needed the same key — already marked sent. Every later reminder for that item was silenced permanently. For a compliance tool that is the worst possible failure: the record you go quiet on belongs to someone actively managing their certifications.

A field in a string is exactly what a later refactor drops, so it is pinned by a regression test that runs against a real database, asserting three things. Re-scanning the same due date must produce the same key set, so dedupe still works. A renewed due date must not appear among the sent keys, so reminders resume. And the unique index must tolerate two log rows for one business item with different DueAt values — miss that and the code is correct while the insert silently fails, which is why the test's own failure message tells you to migrate uk_ntf_reminder_log_dedup to include DueAt. The outbox has its own unique key over the same columns, so the insert is AddIgnoreDuplicate: a collision means it is already queued, not that something broke.

"30 Days Before" Is a Calendar Day in the Account's Time Zone

private static bool IsDue(DateTime expiryUtc, int days, DateTime nowUtc, TimeZoneInfo tz)
{
  var expiryLocalDate = TimeZoneInfo.ConvertTimeFromUtc(expiryUtc, tz).Date;
  var todayLocal = TimeZoneInfo.ConvertTimeFromUtc(nowUtc, tz).Date;
  return (expiryLocalDate - todayLocal).Days == days;
}

Both sides are projected into the account's time zone and truncated to a date before subtracting. Expiry dates are stored as UTC instants, but a credential that dies "on the 14th" is a wall-clock fact in the country where the worker works. A UTC day boundary would put "30 days before" a day early for a customer in California and a day late for one in Shanghai — and since the comparison is equality against a tier, off-by-one is not rounding, it is a missed tier.

The time zone is the browser's IANA name, sniffed from Intl.DateTimeFormat().resolvedOptions().timeZone at registration; the settings page offers no manual dropdown. The resolver that turns that name into a TimeZoneInfo states the real risk in its header comment: on Linux the name hits directly, but on Windows a naive lookup degrades to UTC, and then both the day boundary and quiet hours are computed in the wrong zone — a silent error that is simply one day wrong, every day, forever. Nothing throws. So resolution goes direct hit, then the built-in IANA-to-Windows conversion, then a short hardcoded table, then UTC; and the tests assert real offsets for zones like Asia/Kolkata and Europe/Madrid that are deliberately absent from that legacy table.

Quiet Hours and the Gap Where an Hour Is Missing

Because the scan owns timing, quiet hours cost one extra line there: during local 00:00–07:00 the row is still queued immediately, but its SendAt is set to 07:00 local. The reasoning in the quiet-hours helper is that a reminder already has a 30, 14 or 7 day lead, so a few hours' delay costs nothing, while a phone lighting up at three in the morning is harassment. Weekends are not quiet — customers read mail outside working days too.

// Convert with the offset of that local instant, not ConvertTimeToUtc:
// the latter throws for instants that do not exist inside a DST gap.
var offset = tz.GetUtcOffset(localSendAt);
return DateTime.SpecifyKind(localSendAt - offset, DateTimeKind.Utc);

The comment goes further than the rule it justifies. A "07:00 local" that does not exist on a spring-forward Sunday would make ConvertTimeToUtc throw, and an exception inside the scan loop means no reminders for anyone in that account. So the offset is read from the local value instead. The comment then admits this could be an hour off in principle, and argues it cannot bite: DST jumps cluster around 00:00–03:00, never 07:00, and an hour of error on a 30-day lead is invisible. That is a tolerance stated out loud rather than luck. The tests check New York in September and in January, Sydney because the southern hemisphere jumps the other way, and the boundary itself: 06:59 defers, 07:00 sharp sends.

The Failed Rows and the Ones That Must Stay Pending

Outbox rows carry pending / sent / failed, retried up to 5 times, 100 per batch. Certificate rows carry valid / expiring_soon / expired / renewing, and a small helper in the scan derives the first three from the expiry date. The status worth arguing about is the one that is not there. When an account's monthly alert-email quota runs out, the dispatch loop deliberately does not mark the row failed — it leaves it pending and writes only a reason. Running out of quota is not a delivery failure; it is a delivery that happens next billing cycle.

The outbox model's own header comment explains why failing it would be a trap:

/// The dedupe key does not include Status, so a 'failed' row blocks the same
/// key from being re-queued — which is what stops a dead letter retrying forever.
/// To resend one deliberately: set Status back to 'pending', RetryCount to 0.

So a failed row is a deliberate dead letter, and reviving it is a manual database edit. That trade-off lives in a model comment rather than a closed ticket, which is the only reason I will remember it in a year.

The same instinct runs through the parts of the stack that only move bytes. The Cloudflare Worker proxying the browser to the backend gives up on the upstream at 14 seconds while the client waits 15, because answering a request nobody is waiting for invites a retry — and those POSTs are not idempotent. The 6MB attachment cap is pinned inside the SigV4 signature, so object storage enforces it rather than the upload form. And wrangler.toml declares no [vars] at all, everything a secret, because when a name exists in both places the precedence is unspecified — and the variable that used to sit there was MOCK_MODE, which mints a valid JWT for any password.

Composing an email and calling an API is thirty lines. The part that deserves tests is the part that decides not to.

Related Articles