• Nov 6, 2026
  • 3 min read

Exactly-Once (Almost) on Telegram Long Polling

A moderation bot that bans people must not repeat itself. If the process dies after deleting a message but before saving that it did, the restart must not count the same message as a second strike and ban someone for one offence.

This is the part of the build I’m happiest with, and it’s about 80 lines.

Long polling, so no inbound ports

The bot calls getUpdates with a 25-second timeout. Telegram holds the request open until something happens. No webhook, no reverse proxy, no tunnel: the homelab only needs outbound internet. The catch is that only one process may poll a token, so local mode and Docker must never run at the same time.

Layer 1: the update ledger

def begin_update(self, update_id, kind) -> bool:
    INSERT OR IGNORE INTO updates(update_id, event_type) ...
    return completed_at IS NULL           # handle only if not finished

def complete_update(self, update_id):
    with self.db:                          # one transaction
        UPDATE updates SET completed_at = now ...
        meta.offset = max(meta.offset, update_id + 1)

The offset sent to getUpdates comes from SQLite, not from memory. It moves forward only after the update is fully handled. A crash halfway means Telegram sends the update again and the handler runs again. That’s safe because of layer 2.

Layer 2: every action has a name

Every Telegram write goes through one function with a deterministic key:

self.action(f"delete:{chat_id}:{message_id}", "deleteMessage", ...)
self.action(f"ban:{chat_id}:{user_id}:{message_id}", "banChatMember", ...)
self.action(f"digest:{today}", "sendMessage", ...)
def action(self, key, method, **params):
    if actions[key].status == "done": return       # already happened
    record pending → call Telegram → mark done / failed
    retry network, 429 and 5xx up to 3×, waiting retry_after or 1-2-4 s

Decisions get the same treatment. message:<update_id> stores the Jev scores, so a replayed update reuses the earlier decision instead of calling the classifier again (and paying twice). Deletions are keyed by (chat_id, message_id), so a strike can’t be counted twice.

Layer 3: an outbox for alerts

Messages to me (review cards, errors, score reports) aren’t sent directly. They’re inserted into an alerts table with a stable key and sent by flush_alerts() before and after each poll. If Telegram is down, they wait. If the same problem happens ten times, INSERT OR IGNORE means one alert.

Failures, by type

FailureBehavior
Telegram 429 / 5xx / networkretry with backoff, then the loop retries the update
Telegram 400 / 403 / 404 (e.g. missing rights)log, alert the owner, close the update
Jev down or bad responseleave the message, record unscored, alert
SQLite errorstop processing, wait 5 s, try again; never act without recording
RSS feed downdelay the digest, alert at most once a day, mark nothing as seen

The honest gap

Telegram’s sendMessage has no idempotency key. If the process dies after Telegram accepted a digest but before the done commit, the digest can go out twice. Moderation actions fail the other way. If a delete went through but wasn’t marked done, the replay gets “message to delete not found” (a permanent 400). I get an alert and the update closes without a strike. The worst case is a missed strike, never a double one. Sends are the only thing that can repeat. It’s documented, the actions table shows it if it happens, and I’m fine with a rare duplicate “New on FOSS Engineer” post.

All of this is covered by offline tests with fake Telegram and Jev clients, e.g. test_permanent_delete_error_is_logged_without_deletion_credit.


Next in this series: Two Strikes, Edits and the Owner Exemption

Part 3 of 6. Start with the series overview.