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 ( . . . ) .β¦