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 ..." )
Enter fullscreen mode
Exit fullscreen mode
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.…