Diagnose and fix message backlog and notification-spam issues in cron-based polling bots — covers per-run deduplication flags and stale-message age filters. Apply the Telegram age-gate repair when MAX_AGE_SECONDS is missing and stale messages consume every hourly slot in one cron window. Investigate a sudden flood of old updates, an offset stuck for days, or multiple jobs calling getUpdates with one bot token.
4 stars
0 votes
0 copies
1 view
Added October 1, 2026
ai-agentspythongogitapisecurity
Works with
api
Security analysis
B85/100
highCreates or modifies cron jobs for persistent execution
Installs into .claude/skills of the current project.
Sponsors
SSkills DirectorySkills Directory
Know which skills are safe — weekly.
SSkills DirectorySkills Directory
Is that skill safe to install?
Are you the author of Polling Bot Backlog Diagnosis?
Add the live security badge to your README. It updates with every re-scan.
[](https://www.skillsdirectory.com/skills/williamblair333-polling-bot-backlog-diagnosis)
---
name: polling-bot-backlog-diagnosis
description: Diagnose and fix message backlog and notification-spam issues in cron-based polling bots — covers per-run deduplication flags and stale-message age filters. Apply the Telegram age-gate repair when MAX_AGE_SECONDS is missing and stale messages consume every hourly slot in one cron window. Investigate a sudden flood of old updates, an offset stuck for days, or multiple jobs calling getUpdates with one bot token.
metadata:
type: feedback
---
## When to use
When a cron-based polling bot (Telegram, Slack, etc.) shows either of these symptoms:
- Multiple identical notification messages per cron run (e.g., "⚠️ Message limit reached" appearing 4× instead of once)
- A stale backlog consuming the full rate-limit budget on every reset cycle (e.g., 20 "⏳ Running…" messages over 40 min, then rate limit hit, then repeat)
## Root causes and fixes
### Bug 1: Multiple notifications per cron run
**Symptom:** Each queued message triggers its own rate-limit or error notification. N queued messages → N notifications per run.
**Root cause:** The notification flag is checked per-message rather than per-run.
**Fix:** Set a `rate_limit_notified = False` flag before the message loop. Inside the loop, only send the notification on the first hit and flip the flag. All subsequent rate-limited messages in the same run are silently dropped (advance offsets so they don't reprocess).
rate_limit_notified = False
for message in pending_messages:
if rate_limited:
if not rate_limit_notified:
send("⚠️ Message limit reached")
rate_limit_notified = True
advance_offset(message)
continue
process(message)
### Bug 2: Stale backlog consuming rate-limit budget
**Symptom:** Bot processes messages from hours ago on every cron cycle, burning all hourly slots before reaching fresh messages.
**Root cause:** No message age check — the bot processes everything in the queue regardless of when it was sent.
**Fix:** Add an age filter immediately after the authorized-chat check (before any Claude call). Telegram's `message.date` is a Unix timestamp. Drop anything older than 10 minutes silently.
import time
MAX_AGE_SECONDS = 600 # 10 minutes
msg_age = time.time() - message.date
if msg_age > MAX_AGE_SECONDS:
advance_offset(message)
log(f"Skipped stale message ({int(msg_age)}s old)")
continue
**Order matters:** Age filter first, then rate-limit dedup. Age filter removes backlog cheaply before any API calls occur.
### Telegram gateway repair when the age gate is missing
Use this variant when the state file shows the full budget spent in a single cron window, with bursts of “⏳ Running…” and “⚠️ Message limit reached” clustered within 30–45 minutes. Place the gate after auth/signature validation and before the rate-limit check. In the Python gateway, use its existing `datetime` import and clock convention.
```python
import datetime
MAX_AGE_SECONDS = 600 # module-level constant
# In the message loop, with the update offset already advanced.
msg_age = datetime.datetime.now().timestamp() - msg.get("date", 0)
if msg_age > MAX_AGE_SECONDS:
log(f"Skipped stale message ({int(msg_age)}s old)")
continue
```
Keep the offset advancing on stale skips. Tune the threshold upward only when cron runs more than five minutes apart.
For `state/telegram-gateway-ratelimit.json`, apply this recovery check before clearing state: `check_rate_limit` prunes timestamps older than `RATE_LIMIT_WINDOW_SECS` (typically 3600 s) on the next run. Clear the file manually only when recent timestamps still exhaust the budget and immediate recovery is required.
After editing the gateway, register `scripts/telegram-gateway-poll.sh` with jcodemunch's `register_edit` when available. Verify the next cron run logs stale skips and produces no “⏳ Running…” burst, then check that slots survive the full window.
(Folded in from polling-bot-age-filter-fix on 2026-12-06; that skill stays until William approves removing it.)
## Verification steps
1. Check the rate-limit state file — confirm slot count is reasonable (not maxed)
2. Grep the polling script for both fixes: `rate_limit_notified` flag and age check
3. Confirm age check appears before the rate-limit block in the loop
4. If rate-limit state is stuck at max, reset it manually so the next cron run can proceed immediately
## Clearing stuck rate-limit state
If the state file shows the limit already consumed, zero it out directly — don't wait for the hourly reset. The state file path is typically in `tg_security` constants or the script header.
## Frozen getUpdates offset
A live cron with a days-old offset and the same stale updates logged every run points to a frozen offset. An age gate can discard those messages locally while the queue keeps returning them. Check for competing consumers that acknowledge different batches on one token.
1. Read prior incident notes in memweave and any gitignored local forensics before editing.
2. Check the persisted offset value and last write time with `cat state/<offset-file>` and `stat -c '%y' state/<offset-file>`. Correlate them with fresh log entries that skip the same updates each interval.
3. Enumerate scheduled jobs with `crontab -l | grep -i <bot-or-poll-name>` and check services and daemons too. Trace poll API calls and token configuration with jcodemunch (`search_text` / `search_symbols`) where available. Two pollers using one token confirm competing consumers.
Restore one consumer per token by removing a duplicate job or using a shared `flock -n` when runs can overlap. Then drain the stale backlog once by advancing the persisted offset past the stale updates, preserving fresh ones.
Write a failing single-consumer or offset-advance test before changing code. Run the pre-mortem skill before security-surface edits (`scripts/`, auth/control logic, third-party integration), including checks for TOCTOU, cascade and data integrity. When the work spans security-sensitive code, cron config and a one-time drain, split it into PRs by risk. Report any live checks that still require a human, such as confirming inbound delivery under the actual crontab environment after merge.
(Folded in from polling-bot-offset-freeze-diagnosis on 2026-12-06; that skill stays until William approves removing it.)