I run a Telegram bot that uses Google's Gemini API for free-tier AI features. The free tier gives 1,500 requests per day.
Last week, one user sent 1,400 messages in 3 hours.
The result? 999+ users got "quota exceeded" errors. My entire AI feature was dead for the day.
Here's how I fixed it.
Free AI APIs have hard daily limits. One aggressive user can consume the entire quota. There's no native protection unless you build it.
I needed:
def check_rate_limit(user_id):
now = time.time()
hour_ago = now - 3600
uid = str(user_id)
user_requests.setdefault(uid, [])
user_requests[uid] = [t for t in user_requests[uid] if t > hour_ago]
if len(user_requests[uid]) >= 20:
return False
user_requests[uid].append(now)
return True
20 messages per hour per user. 99% users never hit this.
Layer 2: Global Daily Cap
global_counter = {"date": "...", "count": 0}
def check_global_limit():
today = datetime.utcnow().strftime("%Y-%m-%d")
if global_counter["date"] != today:
global_counter["date"] = today
global_counter["count"] = 0
if global_counter["count"] >= 1400:
return False
global_counter["count"] += 1
return True
Cap at 1,400 — 100 buffer below the 1,500 limit.
Layer 3: Response Cache
answer_cache = {}
cached = answer_cache.get(question.lower().strip())
if cached:
return cached
answer_cache[question.lower().strip()] = answer
Common questions like "What is Bitcoin?" get cached. Repeat users hit cache, not API.
The Results
Spam blocked: 20 msg/hour limit
99% users unaffected
Quota saved: 50-70% via caching Zero extra cost: All in-memory, no database
What I Learned
Free tiers are fragile. Build protection before you scale. Rate limiting + caching is the cheapest fix — no infrastructure needed.
Want the full script?
I packaged this as a production-tested template. Includes:
Complete quota_protection.py
Bot integration example
Setup guide
Multi-provider fallback ready
I'm building an automated Telegram empire in public. Follow along for real code, real numbers, no hype.