ClientsPlace sends a weekly "Client Pulse" digest to workspace owners and admins: which clients need attention, new feedback, and what changed since last week. It's a recurring Hangfire job on .NET with PostgreSQL behind it. One Monday it sent the same digest again, then again an hour later, and again an hour after that, until our mail provider blocked outgoing mail on the mailbox.
That mailbox carries every product's mail, not only digests. A block there also stops sign-up, invitation and billing e-mails. A nice-to-have weekly summary ended up stopping mail that really matters.
Here is what happened, and the rules we follow for mail jobs now.
The failure mode: throwing after the send
The original job looked roughly like this:
[AutomaticRetry(Attempts = 24)] // retried hourly public async Task Run(CancellationToken ct) { foreach (var user in recipients) { if (await db.DigestReceipts.AnyAsync(r => r.WorkspaceId == workspaceId && r.UserId == user.Id && r.WeekStart == week, ct)) continue; // already sent await mailer.SendAsync(user.Email, subject, body, ct); // (1) mail goes out db.Add(new DigestReceipt(workspaceId, user.Id, week)); await db.SaveChangesAsync(ct); // (2) can throw } } This is "send, then record". Anything that throws at step (2) turns a successful send into a failed job, and a failed job gets retried. The retry sends again.
Our step (2) threw for a reason that took a while to see. The receipts table has a composite primary key on (workspace, user, week), added earlier precisely to stop repeat sends. But the "already sent?" check went through Entity Framework's global query filter for workspace isolation. Inside the background job, the scoped workspace context could point at a different workspace than the one being processed. So the filter hid the existing receipt, and the check said "not sent yet". The job sent the e-mail, the insert hit the primary key, and the job threw. Hangfire retried an hour later, and the same thing happened again, for every recipient.
The primary key did its job and protected the data. But the code around it treated "this row already exists" as a crash rather than as the answer to the question.
Fix 1: read dedupe state without tenant filters
A query filter that's right for a request can be wrong in a job. In background jobs, dedupe reads now bypass the global filter and use the workspace id explicitly:
var alreadySent = await db.DigestReceipts .IgnoreQueryFilters() .AnyAsync(r => r.WorkspaceId == workspaceId && r.UserId == user.Id && r.WeekStart == week, ct); IgnoreQueryFilters() should make a reviewer stop and look, because it removes tenant isolation. Here it is paired with an explicit WorkspaceId == condition, so the query is still scoped. It is scoped by the job's own loop variable instead of an ambient context the job does not control.
Fix 2: a duplicate key means "sent", not "error"
The same-day hotfix also changed how the insert fails. A unique violation on the receipt now counts as "already handled":
try { await db.SaveChangesAsync(ct); } catch (DbUpdateException ex) when (ex.InnerException is PostgresException { SqlState: PostgresErrorCodes.UniqueViolation }) { db.ChangeTracker.Clear(); // someone already recorded it } Clearing the change tracker matters. Otherwise the failed entity stays tracked, and the next SaveChangesAsync in the loop tries to insert it again.
Fix 3: record the send before sending
Those two fixes stopped the loop, but the structure was still "send, then record". A review the next day flipped the order. The receipt is now committed first, and the unique key turns that commit into a claim:
db.Add(new DigestReceipt(workspaceId, user.Id, week, sentAt: now)); try { await db.SaveChangesAsync(ct); // claim this (workspace, user, week) } catch (DbUpdateException ex) when (IsUniqueViolation(ex)) { db.ChangeTracker.Clear(); // another run already claimed it continue; } try { await mailer.SendAsync(user.Email, subject, body, ct); } catch (Exception ex) when (ex is not OperationCanceledException) { // Keep the claim: a retry must never replay this recipient. logger.LogError(ex, "Digest send failed for {UserId}; receipt kept.", user.Id); } The first version of this change released the claim when the send failed. We later changed it to keep the claim. A transport error is often ambiguous: the provider may have accepted the message before the connection dropped. Releasing the claim on an ambiguous failure brings back exactly the duplicate we are trying to prevent.
This is a deliberate trade-off. We chose at most once over at least once. If a send really fails, that owner misses one weekly digest. For a summary e-mail that's the right call. For something like a password reset it wouldn't be, so pick the guarantee per e-mail type.
Fix 4: the job never throws after a send
The framework's automatic retry is now off for this job ([AutomaticRetry(Attempts = 0)]). Errors are caught per workspace, logged, and recorded as "this run had failures". The job schedules its own single retry, and that retry is guarded by a claim key too, so it can't create a chain of retries:
private async Task ScheduleRetryAsync(DateTimeOffset week, CancellationToken ct) { var retryAt = clock.GetUtcNow().AddHours(1); if (WeekStart(retryAt) != week) return; // never retry into next week if (!await claims.TryClaimAsync($"digest-retry:{week:yyyyMMdd}", ct)) return; jobs.Schedule(j => j.RunWeek(week, CancellationToken.None), retryAt); } The retry only re-processes recipients without a receipt, so it's safe to run. Claiming before scheduling means a scheduler failure loses one retry instead of creating a duplicate one.
A generic claim table for every scheduled mail
Other scheduled mails (for example, trial-ending reminders) don't have a natural receipts table. For them, we use one tiny table whose primary key is the idempotency key:
CREATE TABLE mail_claims ( claim_key varchar(200) PRIMARY KEY, claimed_at timestamptz NOT NULL DEFAULT now() ); public async Task TryClaimAsync(string key, CancellationToken ct) { var rows = await db.Database.ExecuteSqlInterpolatedAsync( $"INSERT INTO mail_claims (claim_key) VALUES ({key}) ON CONFLICT (claim_key) DO NOTHING", ct); return rows == 1; // true = this caller owns the send } The important design choice is the key. It names the business event, not the job run. For a trial reminder, the key is the workspace, the reminder stage (three days before, last day) and the trial end time. A rerun, a retry, or a second server racing the first all produce the same key, and only one of them gets rows == 1. If the trial end date changes, the key changes too, and a new reminder is allowed. That's what we want.
Smaller guards that also matter
- No overlapping runs:
[DisableConcurrentExecution]on the job, so a slow run and the next trigger can't process the same recipients at the same time. - Stop at the week boundary: a slow batch checks the current ISO week before each recipient and stops if the week has rolled over. Otherwise it would deliver last week's digest on Tuesday under this week's key.
- Pace the sends: the digest waits a few seconds between messages. An earlier unpaced run, together with bounces from seed accounts, had already got the mailbox throttled once.
- Only confirmed addresses: the digest goes only to verified e-mail addresses, so a retry can never hit an unconfirmed or fake address and add bounces.
Stopping a job that's already looping
If this happens in production, deploying the fix is not enough. The pending retry already sits in Hangfire's storage. We removed it from the schedule and marked the job as deleted directly in the Hangfire tables before the next hourly attempt. Learn how to do that for your storage backend before you need it.
The rules, short
- A mail job must never throw after an e-mail has gone out.
- Record the send before sending, with a unique key that names the business event.
- A unique violation on that record means "already handled".
- In background jobs, read dedupe state with explicit tenant ids, not ambient query filters.
- Choose at-most-once or at-least-once on purpose, per e-mail type.
- Turn off blind automatic retries for jobs that have side effects. Retry on your own terms.
We build ClientsPlace, a client portal for service businesses: clientsplace.com.

