Email Operations
What Is Idempotent Email Sending?
Published 2026-09-20 · CSV Sender
Learn how CSV Sender uses atomic SENDING claims and status-guarded updates so cron retries and worker crashes never double-send the same prepared row.
Quick answer
Idempotent email sending means calling the send pipeline more than once for the same queued row still produces at most one Gmail delivery. CSV Sender achieves this with PostgreSQL claim_due_messages (atomic transition SCHEDULED → SENDING), worker updates that include .eq("status", "SENDING"), and terminal states SENT or FAILED that never revert without operator action. Retries reschedule rows—they do not blindly call Gmail again while a row is already SENT.
Why idempotency matters for CSV campaigns
A CSV campaign may run for days. Cron invokes /api/cron/send every minute; workers can crash mid-request; Gmail may time out after accepting mail. Without idempotency, you risk duplicate copies of the same prepared subject and body reaching one recipient—damaging trust and violating expectations set in avoid emailing twice.
Import-time dedupe (email duplicate protection) stops duplicate addresses in one file, but runtime idempotency protects against infrastructure retries.
Atomic claim: SCHEDULED to SENDING
The SQL function claim_due_messages selects due rows with FOR UPDATE SKIP LOCKED, then updates matching messages to SENDING and sets sending_started_at. Only one worker owns a row during delivery. Other cron ticks skip locked rows and move on.
Eligible rows require:
- Campaign status RUNNING
- Message status SCHEDULED with
scheduled_at <= now() - Retry gate:
next_retry_atnull or in the past
This pattern is the hub for queue safety—companion articles cover email queue duplicates and email send retries.
Status-guarded updates after Gmail
Functions like markMessageSent update a row only when current status is SENDING. If a stale worker finishes late, the conditional update affects zero rows—preventing a second SENT transition.
Failures use the same guard. Retryable errors return rows to SCHEDULED with a future next_retry_at; auth errors mark FAILED without endless retry loops (Gmail authorization expired).
Stale SENDING recovery
If a process dies after claiming, a row may sit in SENDING. Operational playbooks release stale locks back to SCHEDULED so delivery can resume without creating a second message record. The important invariant: one row id maps to one logical send attempt chain.
Relationship to Gmail message ids
Successful sends store provider_message_id from Gmail API users.messages.send. That id is audit metadata—not a second send trigger. Idempotency lives in CSV Sender’s database state machine, not in Gmail threading.
Operator checklist
- Never manually set rows from SENT back to SCHEDULED unless you intend a new campaign row.
- Pause with PAUSED instead of duplicating CSV uploads when investigating errors (pause email campaign).
- Monitor FAILED vs SCHEDULED retry counts in the campaign view.
- Keep send-only OAuth connected so retries do not fail auth for transient reasons (Gmail OAuth for email sending).
- Read campaign send worker for cron boundaries.
Example timeline
Row A is due at 09:00. Cron claims it (SENDING), Gmail returns 503, worker schedules retry at 09:05 (SCHEDULED). At 09:05 another claim occurs; Gmail succeeds; row becomes SENT. Total Gmail attempts: two API calls, one delivered message—acceptable. Without status guards, a duplicate 09:00 and 09:05 success could both mark SENT—CSV Sender prevents that.
FAQ
Is idempotency the same as deduping my CSV?
No. CSV dedupe is upload-time; idempotency is runtime across workers and retries.
Does Gmail dedupe on its own?
Do not rely on Gmail—enforce idempotency in your queue (Gmail sending queue).
What status should never repeat for one row?
Two successful SENT transitions for the same message id.
Can I replay cron manually?
Yes—claims are safe when statuses are correct.
Where is MIME built?
Per row at send time via Gmail API (gmail API send email).
Related reading
Database semantics operators should trust
Each message row is a single primary key in PostgreSQL. Campaign workers never insert a second row when retrying the same logical send— they mutate the existing row’s status and timestamps. That design choice matters for analytics: counting SENT rows equals counting intended deliveries, not counting API attempts.
When reviewing Supabase or SQL logs during an incident, look for sequences like SCHEDULED → SENDING → SCHEDULED → SENDING → SENT rather than duplicate ids with the same recipient and subject. The latter would indicate a product bug; the former is normal retry behavior with email send retries.
Comparison to at-least-once messaging systems
Some distributed queues guarantee at-least-once delivery, pushing deduplication responsibility to consumers. CSV Sender instead implements exactly-once user-visible delivery per message row by coupling Gmail API calls to conditional SQL updates. This is stricter than typical SMTP bulk scripts, which often lack row-level state machines altogether.
Testing idempotency mentally
Ask: “If cron runs twice in the same second, can two workers claim the same row?” SKIP LOCKED prevents double claim. Ask: “If Gmail succeeds but our update crashes, could we send again?” The row stays SENDING until timeout or manual recovery—operators should not delete rows mid-flight.
Compliance and audit
Prepared email workflows often require proof that a recipient received a specific text version. Provider message ids plus immutable SENT timestamps supply audit evidence without storing duplicate MIME payloads in logs (email activity log).
Related articles
Email Operations
How Email Sending Queues Prevent Duplicates
Duplicate queue sends come from retries without idempotency, overlapping campaigns, or bad CSV exports—not from normal CSV Sender claims. Here is how to prevent them.
Email Operations
Why Email Sending Systems Need Retries
CSV Sender classifies Gmail errors, retries up to five times with exponential backoff minutes, and reschedules rows to SCHEDULED with next_retry_at.
Gmail
Gmail Sending Queue for CSV Campaigns
Sequential row processing, pause/resume, and throttling between Gmail API sends from a prepared CSV.
Email Operations
Why Duplicate Email Protection Matters
CSV Sender rejects duplicate emails within a CSV, optionally skips previously contacted addresses at campaign start, and validates before messages reach Gmail.
Permalink: http://localhost:3000/blog/idempotent-email-sending