Skip to the page

Messaging patterns · mid

Idempotent consumers and safe payments

A check of a processed table before the work is a race. Claim the event first with a unique constraint, and send an idempotency key to the payment gateway.

The notes

What you must know

  • A check-then-act race: delivery 1 checks (not processed) and calls the gateway, which is slow. The visibility timeout ends and the queue gives the same message to another worker. Delivery 2 checks and still sees not processed. Two charges.
  • Claim first, atomically: INSERT INTO processed_events (event_id, status) VALUES (:id, 'IN_PROGRESS') ON CONFLICT DO NOTHING, with a unique constraint on event_id. Only the worker whose insert succeeded continues, and it marks DONE at the end.
  • A payment row with a unique key on the order and a state machine is even better.
  • Stale IN_PROGRESS rows (a worker died): after a timeout, ask the gateway for the payment status. Never charge blindly.
  • Send the gateway an idempotency key (the order or payment id). Even if two calls get through, it charges once. After a timeout, query the status instead of retrying blindly.
  • Make the visibility or consumer timeout longer than the call, and set the HTTP timeout shorter than the visibility timeout.
  • Test with two consumers, one message and a fake gateway that sleeps longer than the timeout. Assert exactly one charge.
  • After a duplicate charge: list them from the gateway report, refund the customers (do not delete rows), and brief support.

The red pen

Common traps: mistake → fix

  • Mistake: Switch to FIFO, it is exactly-once

    Fix: FIFO dedupes sends, not slow consumers.

  • Mistake: A Redis SETNX with a short TTL is a guard

    Fix: it expires while the call is still running.

  • Mistake: Delete the duplicate rows

    Fix: refund the customers, then clean up.

Easy to hard

Questions interviewers ask, easy to hard

  1. Our consumer checks a processed table, yet 46 customers were charged twice. How?
  2. How do you make a payment consumer safe?
  3. What is an idempotency key?

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview