Skip to content

Idempotency and Effectively-Once Side Effects in Distributed Messaging Systems

2 min read

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

LayerMechanismWhat It Protects Against
1. Admission LedgerUnique DB key (jobId, recipientId, stepKey) inserted before calling external APIConcurrent workers or duplicate queue deliveries
2. Provider Idempotency KeyDeterministic header or client reference passed to downstream APITimeout-after-commit retries against provider
3. Result ReconciliationStore providerMessageId + terminal state atomically after responseRe-sending after worker crash right before commit

Implementing an Atomic Claim Ledger in SQL

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 uncertain with 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.

Was this helpful?