Menu

Telegram can deliver the same payment twice: idempotent Stars crediting on Cloudflare D1
πŸ“°

Telegram can deliver the same payment twice: idempotent Stars crediting on Cloudflare D1

DEV Community: javascriptΒ·kraiwen23Β·6 days ago
#GNuhYPk9
#devtojavascript#devto#dev#insert#payments
Long article (934 words) β€” no AI summary yet.
Reading 0:00
15s threshold

After my previous post on Telegram Stars payments , a reader (thanks, @keyharbor !) pointed out a real bug in step 3: the "check if we already saw this charge, then insert it" pattern can still credit a user twice. This post is the fix, with the reasoning, so you can apply it to any webhook-driven bot β€” not only on D1.

Why duplicates happen at all

Telegram retries a webhook update when your endpoint does not answer with 2xx fast enough. A Worker that is cold, or waits on a slow sendMessage , can easily take long enough for Telegram to send the same successful_payment update again. Two copies of the update can then run at the same time in two isolates.

The broken version: SELECT, then INSERT

const seen = await env . DB . prepare ( 'SELECT 1 FROM payments WHERE charge_id = ?' ) . bind ( chargeId ) . first ( ) ; if ( seen ) return ; await env . DB . prepare ( 'INSERT INTO payments (...) VALUES (...)' ) . bind ( . . . ) .…

Continue reading β€” create a free account

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