Idempotency and Effectively-Once Side Effects in Distributed Messaging Systems
In distributed systems, networks drop packets after a remote server has already processed a request. When a worker times out waiting for a messaging API response and retries, an unguarded activity will send the exact same promotional message twice to the same customer. True "exactly-once delivery" over TCP does not exist; production systems achieve effectively-once side effects through idempotency.
The Three-Layer Idempotency Pattern
| Layer | Mechanism | What It Protects Against |
|---|---|---|
| 1. Admission Ledger | Unique DB key (jobId, recipientId, stepKey) inserted before calling external API | Concurrent workers or duplicate queue deliveries |
| 2. Provider Idempotency Key | Deterministic header or client reference passed to downstream API | Timeout-after-commit retries against provider |
| 3. Result Reconciliation | Store providerMessageId + terminal state atomically after response | Re-sending after worker crash right before commit |
Implementing an Atomic Claim Ledger in SQL
-- Atomic admission guard: only one worker can claim a dispatch slot
INSERT INTO outbound_dispatch_claims (
tenant_id,
idempotency_key,
recipient_ref,
status,
claimed_at
)
VALUES ($1, $2, $3, 'in_flight', now())
ON CONFLICT (tenant_id, idempotency_key) DO NOTHING
RETURNING id;
If RETURNING id yields zero rows, another attempt already claimed or completed that exact message: read its existing state instead of calling the external provider again.
Handling the "Unknown Outcome" Window
What if the worker crashes after sending the HTTP request to a messaging provider that does not support idempotency keys, and before persisting the response?
- Mark the claim
uncertainwith a short lease window rather than blindly retrying marketing messages. - Reconcile against provider delivery webhooks (matching client metadata or recipient+timestamp correlation) before deciding whether to re-attempt.
- For promotional outreach, failing safe (at-most-once) is almost always preferable to spamming customers twice.
Next: tune retry strategies without amplifying outages in Resilient Retries: Exponential Backoff, Jitter, and DLQs.