Telegram Bot Daemon (a2z-game-master)
Project Overview
The a2z-game-master bot is an autonomous 24/7 background worker daemon deployed on Railway PaaS container infrastructure (Repository: alexmurphy3526-ship-it/a2z-game-master, Author: aznasim488-coder). It delivers high-concurrency automated gaming transactions, multi-user balance ledgers, and secure role-based command dispatching without human intervention.
The daemon interfaces with a Supabase PostgreSQL backend using persistent connection pools, enforcing user authorization, balance deductions, transaction rollback safeguards, and real-time administrative telemetry broadcasts.
What This System Gives To The User & Business
24/7 Autonomous Transaction Execution
Users execute automated balance top-ups, orders, and gameplay events directly within Telegram with zero downtime.
Real-Time Ledger & Balance Security
Instant balance verification and deduction with strict transaction isolation, preventing overdrafts and race conditions.
Railway PaaS Continuous Uptime
Deployed on containerized cloud infrastructure with automatic health monitors, memory leak prevention, and automated crash recovery.
Idempotent Command Processing
Ensures that duplicate Telegram button taps or network retries never double-charge user balances through UUID session tokens.
Role-Based Admin Telemetry
Granular access control allowing administrators to audit live user balances, toggle features, and monitor error logs in real time.
Languages & Codebase Breakdown
Core async event loop, python-telegram-bot v20+, task dispatching, connection pooling
Relational schema, user ledger balance deductions, ACID transactions, stored procedures
Railway PaaS container supervision, health check scripts, environment bootstrapping
⚠ The Challenge
Running uninterrupted 24/7 in cloud container environments, preventing connection pool exhaustion during traffic surges, and ensuring idempotent execution so duplicate Telegram webhooks never double-charge balances or cause database deadlocks.
✓ The Solution
Architected an asynchronous worker pipeline utilizing python-telegram-bot v20+ with asyncio, persistent connection pooling via asyncpg/Supabase, tenacity exponential backoff retries, and row-level locking (SELECT ... FOR UPDATE) to guarantee atomic ledger updates.
# Asynchronous Railway Daemon Worker with Supabase Connection Pooling
import asyncio
from telegram.ext import ApplicationBuilder, CommandHandler
from tenacity import retry, stop_after_attempt, wait_exponential
@retry(stop=stop_after_attempt(3), wait=wait_exponential(multiplier=1, min=2, max=10))
async def execute_ledger_transaction(user_id: int, amount: float, session_token: str):
"""Atomically verify balance and deduct funds with Supabase connection pooling."""
async with db_pool.acquire() as conn:
async with conn.transaction():
# Acquire strict row-level lock to prevent concurrent overdrafts
balance = await conn.fetchval(
"SELECT balance FROM user_ledgers WHERE user_id = $1 FOR UPDATE", user_id
)
if balance < amount:
raise InsufficientFundsError(f"User {user_id} has insufficient balance.")
# Atomic deduction and audit trail
await conn.execute(
"UPDATE user_ledgers SET balance = balance - $1, updated_at = NOW() WHERE user_id = $2",
amount, user_id
)
await conn.execute(
"INSERT INTO audit_logs (user_id, delta, token) VALUES ($1, $2, $3)",
user_id, -amount, session_token
)