Idempotency keys & exactly-once effects
Making POST safe to retry with Idempotency-Key headers, unique constraints as the guard, storing responses, idempotent consumers for webhooks and queues, and natural idempotency.
The problem
Client --POST /journals/post--> Server (posts JE-000042, commits)
Client <---- response lost (network drop / timeout) ----
Client retries --POST /journals/post--> Server posts JE-000043 (DUPLICATE!)
Networks, mobile apps, load balancers, message brokers and webhook providers all retry. Every non-idempotent write needs protection.
Idempotency keys
The client generates a unique key per intended operation and sends it with every retry:
POST /api/v1/companies/c-9/journals
Idempotency-Key: 5c1f9a8e-... <- same value on every retry
@Transactional
public JournalResponse create(CreateJournalRequest req, String idemKey) {
return journals.findByIdempotencyKey(companyId, idemKey)
.map(mapper::toResponse) // replay: return the ORIGINAL result
.orElseGet(() -> {
JournalEntry je = JournalEntry.draft(req, idemKey);
journals.save(je); // unique index guarantees one winner
return mapper.toResponse(je);
});
}
CREATE UNIQUE INDEX uq_journal_idempotency
ON journal_entries (company_id, idempotency_key)
WHERE idempotency_key IS NOT NULL;
The unique index is the real guard. If two retries race, both pass the findBy, one insert wins, and the other gets a constraint violation, which you catch and turn into “return the existing record”.
Full-featured variant (Stripe-style)
Store (key, request_hash, status, response_body, created_at):
- The same key with a different body returns 422 (key reuse).
- While the first request is still in progress, return 409 so the client retries later.
- Expire keys after 24 hours.
Idempotent consumers
Webhooks and queue messages are delivered at least once, so record what you’ve processed:
@Transactional
public void handle(PaystackEvent e) {
if (!webhookEvents.insertIfAbsent(e.id())) return; // ON CONFLICT DO NOTHING -> already processed
wallets.credit(e.reference(), e.amount()); // same transaction as the dedup row
}
In your projects
ledger: findByIdempotencyKey · uq_journal_idempotency · uq_journal_one_reversalPosting is idempotent by key, enforced by a partial unique index. Reversal is naturally idempotent: uq_journal_one_reversal means an entry can be reversed only once, so a double-click on “Reverse” can’t create two reversals.
webhook_events (changelog 081) · LedgerService · reconciliation jobsPaystack webhooks are deduplicated through webhook_events, and ledger postings reference provider transaction references. That makes “credit the wallet” safe to receive many times.
cart_items UNIQUE (cart_id, product_id)A natural idempotency guard: adding the same product twice can’t create two rows. Now that the getCartItem bug below is fixed, it increments the quantity instead.
Natural idempotency
Some operations are idempotent by design. Prefer them:
PUT /users/7 {full state}.SET status = 'APPROVED' WHERE status = 'PENDING'(a second run updates 0 rows).- An UPSERT
ON CONFLICT DO NOTHING.
Related concepts you must know
- Exactly-once effects = at-least-once delivery + idempotent processing (outbox lesson).
- Client responsibilities. Generate the key once per user intent, and reuse it on retry.
- Payment provider keys. Pass your idempotency key through to Stripe or Paystack calls too.
- Retry with backoff + jitter on the client side.