Prompt
idempotent job processing at least once delivery
Latest observation
To make job processing idempotent under at-least-once delivery, the goal is:
If the same job is delivered or executed multiple times, the outcome is the same as if it ran once.
Core idea
Assume duplicates will happen. Design the job so repeated processing:
- does not create duplicate side effects
- safely detects prior completion
- can resume or no-op on retries
Common techniques
1. Use a unique job/command ID
Every job should have a stable unique identifier.
Examples:
job_idevent_idrequest_iddeduplication_key
Store this ID in a durable place and check it before doing work.
2. Record processing state
Keep a table like:
job_idstatus=pending | processing | done | failed- timestamps
- result/checksum
Flow:
- Receive job
- Try to claim it atomically
- If already
done, skip - If not, process
- Mark
done
Use a transaction or atomic conditional write so two workers can’t both claim it.
3. Make side effects idempotent
Examples:
- DB updates: use
UPDATE ... WHERE ...or upserts - Creates: use unique constraints on business keys
- External APIs: pass an idempotency key if supported
For example:
- Instead of “insert order”, do
INSERT ... ON CONFLICT DO NOTHING - Instead of “charge card twice”, send an idempotency key to payment provider
4. Separate “at-least-once” from “exactly-once effect”
You may not get exactly-once delivery, but you can get exactly-once effects by deduping at the application layer.
5. Use atomic commit patterns
If possible, combine:
- job state update
- side-effect intent/logging
into one transactional boundary.
If external side effects are involved, consider:
- outbox pattern
- inbox pattern
- saga/compensation
Typical pattern
worker receives job_id
-> check if job_id already completed
-> if yes, ack and exit
-> atomically mark as processing
-> perform work
-> mark completed
-> ack message
Important edge cases
- Worker crashes after side effect but before marking done
- duplicate run may happen
- idempotent side effect prevents harm
- Two workers receive same message
- only one should win the claim step
- Retry after timeout
- same job ID must map to same logical operation
Example
Suppose a job sends a welcome email:
- Bad: every retry sends another email
- Good: store
welcome_email_sent_ator asent_emailstable with unique(user_id, email_type)constraint
Then retries do nothing if already sent.
Practical rule
For every job, ask:
- What is the unique identity of this logical operation?
- What durable state proves it already happened?
- What side effects must be guarded by uniqueness or idempotency keys?
- What happens if the worker crashes at every step?
If you want, I can give:
- a database transaction example
- a Redis-based dedupe example
- or a Kafka/SQS job worker pattern.