Menu

Your 'Pay Now' Button Can Charge Twice. Idempotency Keys Are the Fix Nobody Adds Until It Happens
📰

Your 'Pay Now' Button Can Charge Twice. Idempotency Keys Are the Fix Nobody Adds Until It Happens

DEV Community: node·Anas Sheikh·4 days ago
#PzkR9DOG
#devtonodejs#devto#dev#await#request
Reading 0:00
15s threshold

A customer clicks "Pay now". Nothing happens for three seconds, so they click again. Or their phone loses signal for a moment and the app quietly retries the request. Or your load balancer times out and sends the request again.

Your server received the same order twice, and it did exactly what you told it to do: it created two orders.

This is not a rare edge case. It is the default behavior of every POST endpoint you have ever written.

The Endpoint That Looks Fine

app . post ( ' /api/orders ' , requireAuth , async ( req , res ) => { const order = await createOrder ( req . user . id , req . body ); await chargeCard ( order ); res . status ( 201 ). json ({ orderId : order . id }); });

Enter fullscreen mode

Exit fullscreen mode

Nothing is wrong with this code in isolation. The problem is what it cannot know: whether this request is new, or a repeat of one that already succeeded.

Why This Is Hard to Catch

You test with one request at a time.…

Continue reading — create a free account

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