Idempotency keys for UPI callbacks, done properly
Banks retry. Networks duplicate. Here is the table design that made our UPI webhook handler boring again.
Our UPI collect flow receives callbacks from the PSP bank. During a festive-sale spike we saw the same callback arrive up to six times within two seconds — and two of them were processed twice.
The fix: a unique constraint, not a cache
CREATE TABLE payment_events (
idempotency_key text PRIMARY KEY,
payment_id uuid NOT NULL,
status text NOT NULL,
received_at timestamptz NOT NULL DEFAULT now()
);
INSERT INTO payment_events (idempotency_key, payment_id, status)
VALUES ($1, $2, $3)
ON CONFLICT (idempotency_key) DO NOTHING
RETURNING payment_id;
If RETURNING yields no row, the event was already handled and we respond 200 without side effects. No Redis lock, no race window.
Let the database say no. It is better at it than your application.
Results
- Zero double-credits in the last two sale events.
- p99 handler latency down from 180 ms to 40 ms.
- One less moving part on the on-call runbook.