Dev.to WebDev 🛠 Dev 👁 0 📖 7 min read

Your payment webhook will arrive twice. Is your database ready?

Every payment provider retries webhooks. If your endpoint is slow, times out, or returns anything other than a 2xx, the provider sends the same event again. Sometimes it sends it again even when you did everything right,

Your payment webhook will arrive twice. Is your database ready?

Every payment provider retries webhooks. If your endpoint is slow, times out, or returns anything other than a 2xx, the provider sends the same event again. Sometimes it sends it again even when you did everything right, because the response got lost on the way back.

So at some point your handler will receive the same payment twice. The usual defence looks like this.

if not db.exists("SELECT 1 FROM credits WHERE event_id = ?", event.id):
    db.execute("INSERT INTO credits ...")

It works in every test, and it works in production most of the time. It fails when the two deliveries arrive close together, and then the customer gets paid twice.

I wanted to see exactly how that happens, so I reproduced it on a double-entry ledger I've been building in SQL Server. This post shows three versions of the handler, what each one did with the same duplicate delivery, and the pattern I'd use in production.

The test

The test is the same for all three versions.

  • One event, evt_..._v1 and so on, crediting 1,500.00 to a member's savings account.
  • Delivery 1 arrives at t=0.
  • Delivery 2, the retry, arrives 300 ms later.
  • The handler spends 2 seconds between checking for the event and writing the credit. In real code that's validation, a fraud rule, an API call or just a slow lock wait. I made it long on purpose so the race happens every time instead of once a month.

Version 1 checks, then inserts

IF EXISTS (SELECT 1 FROM hook.NaiveCredit WHERE EventId = @EventId)
BEGIN
    SET @Outcome = 'duplicate, ignored';
    RETURN;
END;

-- ... 2 seconds of work ...

INSERT hook.NaiveCredit (EventId, AccountNo, Amount)
VALUES (@EventId, @AccountNo, @Amount);
SET @Outcome = 'credited';

Here's what happened.

16:59:49.095  v1  delivery 1 received evt_195948_v1
16:59:49.404  v1  delivery 2 received evt_195948_v1
16:59:51.117  v1  delivery 1 -> 200 credited
16:59:51.416  v1  delivery 2 -> 200 credited

Both deliveries checked for the event before either had written anything, so both saw nothing and both went ahead. Two 200s, two credits, 3,000.00 for a 1,500.00 payment.

One payment, two credits

The check isn't wrong. It's just not atomic with the insert. Anything can happen between "no, I haven't seen it" and "now I've recorded it", and a second copy of the same request is exactly the thing most likely to arrive in that gap.

Wrapping the two statements in a transaction doesn't fix it either. Under the default isolation level the EXISTS check doesn't lock a row that isn't there yet, so the second session sails through the same way.

Version 2 adds a unique constraint

The database is the only place that can settle a race between two connections, so the next step is to let it.

EventId varchar(64) NOT NULL CONSTRAINT UQ_UniqueCredit_EventId UNIQUE

The handler code is identical. The result is not.

16:59:51.688  v2  delivery 1 received evt_195948_v2
16:59:51.993  v2  delivery 2 received evt_195948_v2
16:59:53.706  v2  delivery 1 -> 200 credited
16:59:54.001  v2  delivery 2 -> 500 error 2627: Violation of UNIQUE KEY constraint 'UQ_UniqueCredit_EventId'

One credit. The money is right, and this alone is a huge improvement over version 1. If you take one thing from this post, it's that the dedupe key needs a unique constraint, not just an index and an IF EXISTS.

But the second delivery got a 500. From the provider's side, the payment failed to process, so it will retry again. Your error tracker lights up and someone gets paged for a payment that was handled perfectly. Some providers will also start flagging or disabling an endpoint that keeps failing.

A duplicate isn't an error. It's the provider doing its job. The handler should answer it calmly, with the same result it gave the first time.

Version 3 claims the event id first

This version keeps a small inbox table keyed on the provider's event id. The first thing the handler does is insert into it. Everything else happens after that, in the same transaction.

CREATE TABLE hook.WebhookEvent (
    EventId        varchar(64)  NOT NULL PRIMARY KEY,
    PayloadHash    binary(32)   NOT NULL,
    ReceivedAt     datetime2(3) NOT NULL DEFAULT SYSUTCDATETIME(),
    JournalEntryId bigint       NULL,      -- the result, returned to every retry
    DeliveryCount  int          NOT NULL DEFAULT 1
);
BEGIN TRY
    BEGIN TRANSACTION;

    -- Claim the event. A second delivery of the same id waits here.
    INSERT hook.WebhookEvent (EventId, PayloadHash) VALUES (@EventId, @hash);

    -- ... 2 seconds of work, then the real ledger posting ...
    EXEC dbo.usp_Deposit @AccountNo = @AccountNo, @Amount = @Amount,
                         @Reference = @ref, @Channel = 'MOBILE',
                         @JournalEntryId = @entry OUTPUT;

    UPDATE hook.WebhookEvent SET JournalEntryId = @entry WHERE EventId = @EventId;

    COMMIT TRANSACTION;
    SELECT @Outcome = 'credited', @JournalEntryId = @entry;
END TRY
BEGIN CATCH
    IF @@TRANCOUNT > 0 ROLLBACK TRANSACTION;
    IF ERROR_NUMBER() NOT IN (2601, 2627) THROW;

    -- Seen before. Return what the first delivery got, unless the payload changed.
    UPDATE hook.WebhookEvent
    SET    DeliveryCount = DeliveryCount + 1,
           @entry = JournalEntryId, @storedHash = PayloadHash
    WHERE  EventId = @EventId;

    IF @storedHash <> @hash
        THROW 50090, 'Event id reused with a different payload.', 1;

    SELECT @Outcome = 'duplicate, returned original', @JournalEntryId = @entry;
END CATCH;

Same test.

16:59:54.266  v3  delivery 1 received evt_195948_v3
16:59:54.571  v3  delivery 2 received evt_195948_v3
16:59:56.308  v3  delivery 1 -> 200 credited, entry 8315
16:59:56.323  v3  delivery 2 -> 200 duplicate, returned original, entry 8315

One credit, two 200s, and both deliveries report the same journal entry.

Claim the event id first

The interesting part is what delivery 2 did for those 1.7 seconds. Its INSERT hit the key that delivery 1 had inserted but not yet committed, so it waited. It didn't guess and it didn't fail early. When delivery 1 committed, the insert failed with a duplicate key error, the handler read the stored result, and it returned that. If delivery 1 had failed and rolled back instead, delivery 2's insert would have succeeded and it would have done the work itself. Either way the customer is credited exactly once.

That waiting comes from the key lock on the uncommitted row, which is why it still works with READ_COMMITTED_SNAPSHOT turned on. Snapshot isolation changes what reads see, not how two inserts of the same key behave.

And the summary from the demo script.

Handler               Credits  Credited
v1 check then insert  2        3000.00
v2 plus UNIQUE        1        1500.00
v3 claim event first  1        1500.00

Three details that matter

Use the provider's event id. Not your own order id, not a timestamp, not a hash of the request body. The provider's id is the one thing guaranteed to be identical on every retry of the same event, and different for a genuinely new event.

Check that the payload matches. The same id with a different amount is a bug or an attack, not a retry. Storing a hash of the fields you act on lets you tell the difference. In my run, resending the event with 15,000.00 instead of 1,500.00 was rejected and nothing was posted.

changed amount: 50090 Event id reused with a different payload.

Keep a second line of defence. The ledger itself has a unique constraint on every journal entry's reference, and the handler posts with WH- plus the event id. Even if someone later adds a second code path that skips the inbox table, the same event still can't be posted twice.

When the handler calls something else

Version 3 holds a transaction open while it works. That's fine when all the work is in the same database, like here. It isn't fine when the work includes an HTTP call to another service, because now a slow third party is holding your locks.

In that case, split it up.

  1. Insert the event row with a status of PROCESSING and commit straight away.
  2. Do the external work, and pass the event id along as that service's idempotency key, so it can dedupe too.
  3. Update the row to DONE with the result.

A duplicate that arrives while the row says PROCESSING gets a 409 or a 503, and the provider tries again later. You also need a job that picks up rows stuck in PROCESSING, because the process can crash between steps 1 and 3.

The same thing applies if you put webhooks onto a queue and process them later. Most queues deliver at least once, so the consumer has exactly the same problem and needs exactly the same table.

Not on SQL Server?

The idea carries over directly. In PostgreSQL the claim step is one statement.

INSERT INTO webhook_event (event_id, payload_hash)
VALUES ($1, $2)
ON CONFLICT (event_id) DO NOTHING
RETURNING event_id;

If it returns a row, you own the event. If it returns nothing, someone else already claimed it, so read their result. A concurrent insert of the same key waits for the other transaction to finish, just like the SQL Server version.

Takeaways

  • Webhooks are delivered at least once. Plan for every event to arrive twice.
  • IF NOT EXISTS ... INSERT is a race. Two copies of the same request will both pass the check.
  • Put a unique constraint on the provider's event id. That alone stops the double credit.
  • Then treat a duplicate as a success and return the original result, instead of a 500.
  • Store a hash of the payload, and reject the same id with different data.
  • Keep the inbox rows for longer than your provider's retry window, then clean them up.

The full code, including a script that fires the two deliveries at all three handlers, is on GitHub in isaactony/sacco-ledger. Run demo/webhook_duplicates.sh after building the database and you can watch version 1 pay out twice.

How does your team handle duplicate webhooks? I'm curious whether most people dedupe in the database or somewhere earlier, like a cache.

📰 Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.