How I Protected My Telegram Bot's AI Quota From Spam Users
Description and use
Protecting a Telegram bot from quota abuse: per‑user rate limits, a global daily cap, and response caching keep 99% of users online and save 50‑70% of API calls.
Problem
A single aggressive user sent 1,400 messages in 3 hours, exhausting the free-tier Gemini API quota of 1,500 requests per day and causing 999+ users to receive quota exceeded errors.
Outcome
Spam blocked by per‑user limit; 99% users unaffected; 50‑70% quota saved via caching; no extra cost as all logic runs in memory.
Workflow
- Implement per‑user rate limit (20 msgs/hr) using in‑memory timestamp list.
- Implement global daily counter with 1,400 request cap and 100‑request buffer.
- Add in‑memory response cache keyed by normalized question text.
- Integrate checks into bot command handler before calling Gemini API.
- Return cached answer if available; otherwise call API and cache result.
- Reset daily counter at UTC midnight.
- Monitor and log quota usage for future adjustments.
Evidence
20 messages per hour per user. 99% users never hit this.
Cap at 1,400 — 100 buffer below the 1,500 limit.
Quota saved: 50-70% via caching
- Record date: 2026-09-22T07:00:36.206Z