I was building the coin system for Eyerone , a social platform with live streaming and virtual gifts: users buy a coin pack through Stripe Checkout, Stripe calls my webhook, and my server credits the coins.
It worked perfectly in testing. Then I noticed something in the database: some users had been credited twice for a single payment.
No hacking, no bugs in Stripe. Just a classic race condition in my own code. Here's what happened and the fix.
The naive version
This is roughly what my fulfillment logic looked like:
async function fulfillOrder ( sessionId ) { const order = await Order . findOne ( { stripeSessionId : sessionId } ) ;
if ( order . status === 'paid' ) return ; // already handled ✅ ...right?
order . status = 'paid' ; await order . save ( ) ;
await User . updateOne ( { _id : order . userId } , { $inc : { coins : order . coins } } ) ; }
Enter fullscreen mode
Exit fullscreen mode
Looks safe. We check the status before doing anything.…