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(...).run(); await extendPremium(userId, days); 

Both requests run the SELECT before either has written. Both see nothing, both extend premium. Classic check-then-act race. A PRIMARY KEY on charge_id makes the second INSERT fail — but if you catch and ignore that error after crediting, or credit before inserting, the damage is done.

The fix: let the INSERT be the lock

The database already serializes writes to a single row key. So do the write first and ask the database whether this request was the one that wrote:

const ins = await env.DB.prepare( 'INSERT OR IGNORE INTO payments (charge_id, user_id, amount, payload, created_at) VALUES (?, ?, ?, ?, ?)' ).bind(p.telegram_payment_charge_id, userId, p.total_amount, p.invoice_payload, now()).run(); if (!ins.meta || ins.meta.changes !== 1) return; // someone else already handled this charge 

meta.changes is 1 only for the request whose row actually landed; every duplicate gets 0 and exits. No extra lock table, no KV, no Durable Object. (INSERT ... ON CONFLICT(charge_id) DO NOTHING works the same way in SQLite/D1.)

The schema needs exactly one thing for this to be safe: telegram_payment_charge_id must be unique.

CREATE TABLE IF NOT EXISTS payments ( charge_id TEXT PRIMARY KEY, user_id INTEGER NOT NULL, amount INTEGER NOT NULL, payload TEXT, refunded INTEGER DEFAULT 0, created_at INTEGER ); 

Extending premium: one atomic UPDATE, not read-modify-write

The second race hides in "read premium_until, add 30 days in JS, write it back". Two different payments from the same user (a double tap on the invoice is enough) can interleave and one renewal is lost. Do the arithmetic in SQL:

await env.DB.prepare( 'UPDATE users SET premium_until = MAX(?, COALESCE(premium_until, 0)) + ? WHERE id = ?' ).bind(now(), days * DAY, userId).run(); 

MAX(now, premium_until) also gives you the right behaviour for early renewals: the new period stacks on top of the remaining time instead of resetting it.

Refunds: take back only what the payment bought

refundStarPayment returns the Stars, and the obvious follow-up is premium_until = now(). That is wrong when the user renewed early: refunding the second payment would also wipe the first, already paid period. Subtract the days of that payment and mark it refunded in the same batch:

const r = await tg(env, 'refundStarPayment', { user_id: pay.user_id, telegram_payment_charge_id: chargeId }); if (r.ok) { await env.DB.batch([ env.DB.prepare('UPDATE payments SET refunded = 1 WHERE charge_id = ?').bind(chargeId), env.DB.prepare('UPDATE users SET premium_until = MAX(0, COALESCE(premium_until, 0) - ?) WHERE id = ?') .bind(daysOf(pay.payload) * DAY, pay.user_id), ]); } 

Check pay.refunded before calling the API so an admin double-click cannot subtract the days twice (Telegram will reject the second refund anyway, but your DB would not know).

Answer the webhook fast

Retries are the root cause, so reduce them: return 200 as soon as the update is accepted and do slow work (the "thank you" message, analytics) with ctx.waitUntil(...). Idempotency still has to be there — retries also happen on network errors you do not control — but fewer duplicates means fewer weird logs.

Checklist

  • unique key on telegram_payment_charge_id;
  • INSERT OR IGNORE first, credit only when meta.changes === 1;
  • date arithmetic inside a single UPDATE, never read-modify-write in JS;
  • refunds subtract the refunded period, guarded by a refunded flag;
  • respond 200 quickly, push slow work to waitUntil.

All of this is in the MIT-licensed Telegram Stars bot boilerplate for Cloudflare Workers (with tests that simulate the double delivery), and it runs in production in a small crypto price alert bot. If you spot another race in it — comments are very welcome, the last one made the code better.