Video in progress

The payment provider sends the same callback twice. How do you process it only once in the database?

I put a unique constraint on the external ID and do INSERT ... ON CONFLICT DO NOTHING: if the row is inserted, I process it; if not, it's a duplicate. Since the check and the write are one atomic action, there's no race.

📖 Answer

The classic mistake is a SELECT exists(...) first, then an INSERT. If two callbacks arrive at the same time, both see "not there" and both write. Only the database itself can close a race like that.

CREATE TABLE payment_events (
  provider     text   NOT NULL,
  external_id  text   NOT NULL,
  payload      jsonb  NOT NULL,
  received_at  timestamptz NOT NULL DEFAULT now(),
  PRIMARY KEY (provider, external_id)
);

INSERT INTO payment_events (provider, external_id, payload)
VALUES (:provider, :extId, :payload::jsonb)
ON CONFLICT (provider, external_id) DO NOTHING
RETURNING external_id;

If RETURNING returns a row, it's the first time: in that same transaction I mark the order as "paid". If nothing comes back, it's a duplicate, and I just return 200 OK to the provider.

Key points:

  • Writing the event and the business change must be in one transaction. Otherwise, if the event is written and then something fails, the next duplicate gets skipped as "already there" and the payment is lost.
  • The second transaction waits on the unique index until the first commits. That's normal, but keep the transaction short.
  • The amount is checked too: if the same external_id arrives with a different amount, that isn't a duplicate, it's an anomaly, so alert.

Hibernate has no ON CONFLICT, so I write this part as a native query or with JdbcTemplate.