Menu

Stripe Webhooks Were Double-Crediting My Users — Fixed with One Atomic MongoDB Query
📰

Stripe Webhooks Were Double-Crediting My Users — Fixed with One Atomic MongoDB Query

DEV Community: mongodb·Sithija Kalhara·3 days ago
#gHbA1FS9
#devtomongodb#devto#dev#order#status
Reading 0:00
15s threshold

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.…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.