The All File Converter service is designed as a scalable distributed SaaS system based on a modern asynchronous Python 3.12 stack. The architecture is divided into independent layers: network event ingestion, task orchestration, isolated execution of heavy binary processes, and the analytical circuit.
1. General Technology Stack and System Architecture
The platform is built on principles of high throughput, minimal memory consumption, and fault tolerance:
- Telegram Bot Framework:
Aiogram 3.13running in Webhook mode with secret token validation and custom message lifecycle filters. - Web Gateway and REST API:
FastAPIbased on the Uvicorn ASGI server with asynchronous binary file streaming (FileResponse) and background cleanup viaBackgroundTasks. - Queue Broker and Cache:
Redis 7(Celery task management, race condition locks, brute-force protection, session caching). - Background Task Executor:
Celery 5.4with a dedicated pool of workers in an isolatedconverter_workercontainer. - Database:
PostgreSQL 16with theSQLAlchemy 2.0 (asyncpg)ORM layer, a persistent connection pool (20+10 overflow), and automatic retry for failed transactions (@db_retry). - Network Circuit: Tunneling via
Cloudflare Zero Trustwith direct server IP access blocking through Middleware.
2. Asynchronous Queues and Heavy Computation Isolation (Celery + Redis)
Media file and office suite conversions create peak loads on CPU and RAM. To prevent incoming Telegram message processing from blocking during heavy operations, strict isolation is implemented:
- Task Delegation to Redis: Upon format selection, the Telegram handler registers a task in the DB with the
PROCESSINGstatus and queues the job intasks.execute_conversionvia Celery. - Isolated Worker Container: Conversion utilities are executed inside a separate Linux container with its own CPU time and memory limits.
- Hang Control and Timeouts: External utility calls are wrapped in an asynchronous context with strict time control (
conversion_timeout_sec = 180). If the limit is exceeded, the process is forcibly terminated viaproc.kill(), freeing up resources. - Fault-Tolerant Fallback: If the Redis broker is temporarily unavailable, the task is automatically intercepted by the local asynchronous dispatcher and executed directly without failing for the user.
3. Specialized Conversion Engine Pipeline
Narrowly specialized native utilities and libraries are employed for each data type:
- Documents and Spreadsheets (LibreOffice): A headless office suite (
soffice --headless) for accurate rendering of DOCX, XLSX, PPTX, RTF, and ODT into PDF or text files. - Streaming Audio and Video (FFmpeg): Multithreaded transcoding of video codecs (H.264), audio codecs (MP3, OGG Opus), extraction of audio tracks, GIF generation (Lanczos filter), and square cropping (1:1) of Telegram video messages.
- High-Speed PDF Processing (Poppler Utils):
pdftotextutilities (instant extraction of formatted text in UTF-8) andpdftoppm(page-by-page PDF rendering to raster images without LibreOffice overhead). - Optical Character Recognition (Tesseract OCR): Neural network extraction of printed text from scans and photos in 40+ languages.
- Raster and Vector Graphics:
Pillowlibraries (including HEIC and AVIF format support),CairoSVGfor vector images, andlottiefor animated Telegram stickers (.TGS). - Books, Subtitles, and Fonts: The
Calibreengine (ebook-convert), thepysubs2subtitle parser (SRT, VTT, ASS, SSA), and thefonttoolsfont compiler (Brotli compression in WOFF2).
4. Preventive Resource Protection (System Guard)
To protect against server crashes caused by out-of-memory errors (OOM Killer), the System Guard preventive diagnostics service is integrated. Before accepting a file for processing, the system checks key host metrics:
- Free RAM: Minimum 500 MB of free volume (
guard_min_free_ram_mb). - Disk Space: Minimum 2 GB of free space in the
/tmpdirectory (guard_min_free_disk_mb). - Task Queue: Celery queue length limitation (no more than 20 pending tasks).
If limits are exceeded, the service temporarily enables protection (HTTP 503 / chat message), preventing server overload and sending an instant alert to administrators in Telegram.
5. File Lifecycle and Security (GDPR)
The architecture is designed around a Zero-Data-Footprint model:
- User files are uploaded to a secure
tmp/conversions/volume with unique prefixes based on task IDs. - Files remain accessible strictly within the working session — no more than 15 minutes (900 seconds).
- The automatic garbage collector erases original and ready-made files immediately after confirmation of successful delivery to the chat or upon session timeout expiration.
- The PostgreSQL database does not store binary files or personal document texts — only anonymized technical metadata (formats, sizes in bytes, processing time, statuses) are recorded in the tables.
6. Universal REST API for External Web Services
The service was initially designed as a multi-platform backend. Alongside the bot, a fully functional secure software interface operates for websites (e.g., built on Django) and third-party bots:
GET /api/v1/formats— dynamic JSON matrix of available conversion directions, synchronized with Google Sheets settings.POST /api/v1/convert— universal endpoint acceptingmultipart/form-data(file, target format, external client ID) and returning the ready byte stream as a direct download.- Authorization via Bearer tokens (
WEBHOOK_REFRESH_TOKEN) with timing attack protection viasecrets.compare_digest.
7. Control Panel and Observability (NiceGUI + AG Grid)
Business metric and system status monitoring has been brought into a native Single-Page control panel based on NiceGUI 2.x:
- Interactive
AG Grid (v32+)tables with custom Excel-style checkbox filters (aggrid_filters.js). - Real-time monitoring of queues, API provider latencies, and PostgreSQL / Redis ping.
- End-to-end date filtering with seamless integration of the
MetabaseBI dashboard via signed JWT tokens.