Skip to content

Lesson 6 of 9 · 27m

Idempotent Workers That Survive Redelivery

Make repeated delivery harmless using natural keys, idempotency tables, compare-and-set state transitions, and transactional outbox patterns.

Idempotency is the difference between a queue system and a random duplicate generator attached to your database. The worker's job is not to prevent redelivery — you cannot prevent redelivery — but to make redelivery boring. When the same message arrives twice, the second execution should observe existing truth and stop.

Start with a stable idempotency key

The best key is a natural business key, not a random queue message ID:

invoice.finalized       tenant_id + invoice_id + event_version
email/password/payment  tenant_id + user/token/payment_intent_id
image thumbnail         asset_id + transform_hash

Queue message IDs can change across replay, migration, or redrive. Business identity survives.

Store processing claims transactionally

A relational idempotency table is simple and effective:

create table job_effects (
    effect_key text primary key, job_type text not null, status text not null,
    result jsonb, created_at timestamptz not null default now(), completed_at timestamptz
);

The worker inserts the key before or alongside the business effect. If the insert conflicts, the effect already exists or is in progress:

insert into job_effects (effect_key, job_type, status)
values ('tenant_8:invoice_10492:v18', 'invoice.finalized', 'processing')
on conflict (effect_key) do nothing;

For short critical sections, perform the business write and completion mark in one transaction. For external APIs, store the provider's idempotency response so retries can reconcile rather than blindly repeat.

Idempotency is not only deduplication

State transitions need guards. A cancellation arriving after completion must not rewind the entity:

update orders
set status = 'cancelled'
where id = 'ord_419' and status in ('pending', 'payment_failed');

This is compare-and-set through the database. Zero rows means the transition no longer applies; inspect state before deciding whether that outcome is success, conflict, or permanent failure.

External APIs need their own keys

Payment providers and mail providers commonly accept explicit idempotency keys:

curl https://api.stripe.com/v1/payment_intents   -u "$STRIPE_SECRET_KEY:" -H "Idempotency-Key: tenant_8:invoice_10492:capture:v18"   -d amount=4200 -d currency=usd -d confirm=true

Derive the key from the business operation and persist it; a fresh key per retry defeats the provider's protection.

The outbox protects the boundary

The worst dual-write is database commit succeeds, publish fails. Use an outbox table written in the same transaction as business state, then publish asynchronously:

insert into invoices (...) values (...);
insert into outbox_events (id, type, payload) values
  ('evt_...', 'invoice.finalized', '{"invoice_id":"inv_10492"}');

A relay publishes outbox rows; publish duplication is acceptable because consumers are idempotent.

Field notes

  • Do not delete idempotency records too early. Retention must exceed maximum replay and incident recovery windows.
  • "Already exists" is not automatically success. Verify the stored operation matches the incoming payload before treating it as a duplicate.
  • Idempotency does not fix authorization or validation. Reject impossible work permanently instead of polishing its retry path.

Was this lesson helpful?

Sign in to rate