Skip to content

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.

ts
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 sent write can still repost once: that is the limit without an idempotency key on the API.
  • Keep messageId to reply to the original post later.

Built for the channel announcements on ravy.pro. Firestore transactions.

Share LinkedIn Post on X

Related notes

Newsletter

Occasional notes on engineering, game tech, and new tools — no spam, unsubscribe anytime.

Ravy

Engineering manager, founder, and software developer building web platforms, game systems, real-time services, and automation tools. 15 years of shipped work — currently at Gaijin.net.

Get in Touch

Building an MVP, shipping a game feature, or automating a team workflow? Open source or paid — let's talk.

Contact Me
© 2020-2026 XPLOIT FZE. All trademarks, names and logos belong to their respective copyright holders.