A scalable Telegram bot that tracks user registrations and notifies an admin of milestone achievements. Designed to handle millions of concurrent users with a production-grade architecture.
- ✅ Scalable: Async/await architecture with connection pooling
- ✅ Database: PostgreSQL support for storing millions of users
- ✅ Caching: Redis for performance and rate limiting
- ✅ Rate Limiting: Per-user rate limiting to prevent abuse
- ✅ Docker: Ready for containerized deployment
- ✅ Logging: Comprehensive logging for monitoring
- ✅ Commands:
/start,/stats,/help
-
Clone and setup:
cd user_count cp .env.example .env -
Edit
.envwith your credentials:BOT_TOKEN=your_token_here ADMIN_ID=your_admin_id_here -
Install dependencies:
pip install -r requirements.txt
-
Run:
python main.py
-
Setup
.env:cp .env.example .env # Edit .env with your credentials -
Deploy:
docker-compose up -d
-
Monitor logs:
docker-compose logs -f bot
| Variable | Default | Description |
|---|---|---|
BOT_TOKEN |
Required | Telegram bot token |
ADMIN_ID |
Required | Admin user ID for notifications |
DATABASE_URL |
sqlite+aiosqlite:///users.db |
Database connection string |
REDIS_URL |
redis://localhost:6379/0 |
Redis connection string |
NOTIFICATION_INTERVAL |
500 |
Notify admin every N users |
RATE_LIMIT_REQUESTS |
100 |
Max requests per user |
RATE_LIMIT_SECONDS |
60 |
Rate limit window |
SQLite (Local Development):
DATABASE_URL=sqlite+aiosqlite:///users.db
PostgreSQL (Production):
DATABASE_URL=postgresql+asyncpg://user:password@localhost:5432/telegram_bot
- Language: Python 3.11+
- Bot Framework: python-telegram-bot
- Database: SQLAlchemy ORM with async support
- Cache: Redis
- Containerization: Docker & Docker Compose
- Concurrency: AsyncIO with connection pooling
-
Database Layer
- Connection pooling (20 connections, 40 max overflow)
- Async database operations
- Efficient queries with indexed lookups
-
Caching Layer
- Redis for stats caching
- Rate limiting with Redis
- Reduced database queries
-
Async I/O
- Non-blocking bot message handling
- Proper coroutine management
- Connection reuse
-
Monitoring
- Structured logging
- Error handling and recovery
- Health checks available
-
/start- Register as a user (or welcome back)- Returns user count
- Triggers admin notification at milestones
-
/stats- View bot statistics- Total user count
- Last milestone reached
- Last update time
-
/help- Show available commands
Estimated capacity with proper hardware:
| Component | Capacity |
|---|---|
| Concurrent Users | 1,000,000+ |
| Registrations/sec | 1,000+ |
| Queries/sec | 100,000+ |
| Cache Hit Rate | 80%+ |
- Use PostgreSQL (not SQLite)
- Set up multiple bot instances behind a load balancer
- Configure Redis Cluster for high availability
- Use Kubernetes for orchestration
- Monitor with Prometheus/Grafana
- Use RDS (AWS) or Cloud SQL (Google) for managed PostgreSQL
- Use ElastiCache (AWS) or Memorystore (Google) for managed Redis
apiVersion: apps/v1
kind: Deployment
metadata:
name: telegram-bot
spec:
replicas: 3
selector:
matchLabels:
app: telegram-bot
template:
metadata:
labels:
app: telegram-bot
spec:
containers:
- name: bot
image: telegram-bot:latest
env:
- name: BOT_TOKEN
valueFrom:
secretKeyRef:
name: bot-secrets
key: token
- name: DATABASE_URL
value: postgresql+asyncpg://user:pass@postgres-service:5432/bot_db
- name: REDIS_URL
value: redis://redis-service:6379/0
resources:
requests:
memory: "256Mi"
cpu: "250m"
limits:
memory: "512Mi"
cpu: "500m"main.py- Main bot coderequirements.txt- Python dependenciesDockerfile- Container image definitiondocker-compose.yml- Local deployment stack.env.example- Environment variables templateREADME.md- This file
id (BigInteger, PK) - Telegram user ID
username (String) - User's first name
registered_at (DateTime) - Registration timestamp
id (Integer, PK) - Always 1 for singleton
message_id (Integer) - Telegram message ID
last_count (Integer) - Last notified user count
last_updated (DateTime) - Update timestamp
- Database connection failures: Falls back gracefully
- Redis unavailable: Continues with in-memory caching disabled
- Telegram API errors: Logged and retried
- Rate limiting: Prevents user abuse
MIT License - feel free to use for your projects
Contributions welcome! Please ensure:
- All async functions are properly awaited
- Database operations use connection pooling
- Errors are logged appropriately
- Code follows PEP 8 style guide
For issues or questions:
- Check logs for error messages
- Verify environment variables are set correctly
- Ensure database and Redis are running
- Implement Prometheus/Grafana monitoring
- Add health check endpoints
- Support for multiple admin notifications