@
@levelsio @levelsio
Monday, November 4, 2024 import

Tweet

Crazy bug on Photo AI today, and took hours to solve it: > invoice.paid - No Photo AI user in db exists with Stripe customer ID: cus_12345678 Stripe webhooks or payments (?) seem to have increased in speed so much now that it's started causing problems for me for about 1% of signups with this funny race condition: 1) customer.subscription.created arrives when a new customer signs up: they're subscribed to a plan, at that time I create a new user in the db for them, send them a welcome email with a login link, etc. Sometimes though customer.subscription.created does NOT mean the payment actually went through, so you can't rely on that or you're giving users the product for free, so you have to wait for invoice.paid to arrive 2) invoice.paid arrives when the payment went through, at that point we know we got their money, so it loads the user account with photo credits and they can start using it On a regular card payment this process happens in milliseconds, so you don't notice it, you just sign up and immediately you can start using the app But 1% of time, the invoice.paid webhook arrives SO fast, that the customer.subscription.created webhook script is still busy CREATING the user, so it errors with: > invoice.paid - No Photo AI user in db exists with Stripe customer ID: cus_12345678 Because there is no user in the db yet, but a few milliseconds after there will be My fix? Add sleep(1) to invoice.paid, it will wait 1 second and then it's definitely created If even then not, it will reply with HTTP error 400, so Stripe can auto retry the webhook!