Today I learned
How do I stop a bot from posting the same message twice across server instances?
My site announces new posts in a Telegram channel. It runs on two instances, a post can be republished, and a worker may retry the call. A plain "if not sent yet, send" check races, and the channel gets the post twice.
Fix: one ledger document per message, claimed in a transaction before the send.
async function claim(ref: DocumentReference): Promise<boolean> {
return db.runTransaction(async (tx) => {
const cur = (await tx.get(ref)).data()
if (cur?.status === 'sent') return false
if (cur?.status === 'sending' && Date.now() - Date.parse(cur.claimedAt) < 5 * 60_000) return false
tx.set(ref, { status: 'sending', claimedAt: new Date().toISOString() })
return true
})
}
const ref = db.collection('channel_ledger').doc(`blog-${slug}`)
if (await claim(ref)) {
try {
const msg = await sendToChannel(post)
await ref.set({ status: 'sent', messageId: msg.message_id })
} catch (err) {
await ref.delete() // release, so a retry can send
throw err
}
}
- Key by the message, not the request (
blog-<slug>,til-<slug>-video), so a republish does nothing. - The 5-minute TTL frees a claim whose process died. A crash between Telegram's OK and the
sentwrite can still repost once: that is the limit without an idempotency key on the API. - Keep
messageIdto reply to the original post later.
Built for the channel announcements on ravy.pro. Firestore transactions.