Unified Backend & Intelligence Engine
Enterprise-grade Django 6.1+ REST framework monolith with in-memory Google OR-Tools CP-SAT solver, Calibrated XGBoost failure risk scoring, PostgreSQL 16, and Celery 5.6+ task queue.
Unified Monolith Architecture
Rather than distributing business logic and AI solvers across fragmented microservices that introduce serialization overhead and container failures, the backend is architected as a unified, high-performance monolith:
Web & API Framework
Django 6.1+ & Django REST Framework (DRF). Standardized viewsets, routers, paginated serializations, and built-in interactive browsable API.
Embedded In-Memory AI Solvers (0ms Latency)
Google OR-Tools CP-SAT discrete solver and Calibrated XGBoost models run directly within the Django worker memory, achieving sub-second optimization (~0.1s) without microservice roundtrips.
Relational Persistence & Zero-Config Fallback
PostgreSQL 16 in production (Supabase / Managed PaaS) via psycopg3, with zero-config local SQLite development fallback.
Asynchronous Workers & Telemetry Bridge
Celery 5.6+ & Redis coordinate timetable synchronization at 02:00 AM IST and fetch live train movements from the RailKit API with strict quota protections.
Base URLs & IST Timezone Standards
Timezone Standard: Indian Standard Time (IST - Asia/Kolkata)
All API inputs, outputs, and Celery cron evaluations operate on formatted IST: YYYY-MM-DD HH:MM:SS. While datetimes are stored in UTC in PostgreSQL, serializers convert them dynamically via timezone.localtime() to eliminate date drift between maintenance queue rows and block window recommendations.
Backend Repository Layout
Structured into clean Django domain apps and embedded AI modules:
REST API Endpoints Reference
15+ REST Endpoints| Domain | Method | Endpoint Path | Operational Purpose |
|---|---|---|---|
| Corridors | GET | /railways/sections/ | List all corridor track sections with source/destination station codes |
| Assets | GET | /railways/assets/ | List infrastructure assets (Engineering, SNT, Traction) with criticality ratings |
| Maintenance | GET | /railways/maintenance-tasks/ | List maintenance tasks with auto-overdue sync to DELAYED status |
| Trains | GET | /railways/trains/ | List all trains synchronized via RailKit timetable sync |
| Live Operations | GET | /railways/trains/operations/ | Combined live tracking view for up to 30 trains with calculated entry/exit delay |
| Schedules | GET | /railways/train-schedules/ | Weekly timetables with 7-day running bitmask filter (?date=YYYY-MM-DD) |
| Block Windows | GET | /railways/block-windows/ | List all reserved, available, or blocked corridor windows |
| Feasible Windows | POST | /railways/block-windows/feasible-windows/ | Runs in-memory OR-Tools CP-SAT solver to compute safe block windows |
| AI Recommendation | GET | /railways/block-windows/{id}/recommendation/ | Evaluates conflict count and recommends best alternative slot with suggested payload |
| Auto-Apply Slot | POST | /railways/block-windows/{id}/apply-recommendation/ | 1-Click action to automatically update block window to AI-recommended slot |
| By Task Window | PUT | /railways/block-windows/by-task/{task_id}/ | Update or reserve block window directly by human-readable task code (e.g. TMS-746) |
| Conflict Check | POST | /railways/block-windows/check-conflict/ | Detect train movement collisions during proposed maintenance interval |
Deep-Dive API Payloads & Responses
Compute Feasible Maintenance Windows (In-Memory CP-SAT)
Submits a maintenance task code and target date. Dynamically builds a 24-hour virtual planning horizon for the task's corridor section and executes the Google OR-Tools CP-SAT discrete solver to find conflict-free intervals.
Dynamic AI Recommendation & Conflict Resolution
Evaluates an existing block window against live and scheduled train movements. If a conflict or suboptimal delay risk is detected, returns an alternative 100% collision-free slot with an auto-generated suggested PUT payload.
1-Click Auto-Apply AI Recommendation
Applies the AI-recommended conflict-free slot directly to the block window database record in a single atomic transaction. Automatically updates the linked maintenance task to SCHEDULED.
Direct Task-Based Window Update (/by-task/)
Allows frontend or external systems to reserve or update block windows directly by the task's human-readable identifier (such as TASK-OHE-101 or TMS-746) without needing to query internal numeric IDs.
Corridor Conflict Detection Engine
Inspects all scheduled and live trains on a corridor section during a proposed time range. Returns collision status and lists overlapping trains with exact entry/exit timestamps.
Live Operations Dashboard Aggregator
Aggregates master train records, scheduled timetables, and actual live movement tracking for up to 30 operating trains along a corridor section with calculated delay minutes.
Multi-Tier Auto-Overdue DELAYED Transition
Whenever a maintenance task's deadline passes (due_date < today in Asia/Kolkata) without completion, the backend transitions its status to DELAYED and sets is_overdue = True across three redundant mechanisms:
MaintenanceTask.save() evaluates deadlines before committing changes to PostgreSQL.
MaintenanceTaskViewSet.get_queryset() runs a bulk update on expired tasks upon every GET request.
Scheduled at 00:00 IST daily to log and synchronize all expired tasks across all divisions.
Celery Periodic Tasks & RailKit Quota Guards
Daily at 02:00 AM IST. Syncs full weekly timetables inside atomic transactions.
Every 3 hours. Dispatches tracking tasks for up to 30 operating trains.
🛡️ Strict Quota Protection Features
- Hard Quota Cap (30 Trains / Cycle): Prioritizes up to 10 premium services (Vande Bharat, Shatabdi, Rajdhani, Tejas).
- Rate Limiting (15/m): Throttles live-tracking calls to 15 per minute, preventing RailKit HTTP 429 errors.
- Active-Day Bitmask Pre-Filter: Checks train running masks before scheduling API queries.
- Graceful Skip Handling: Caught RailKit 400 responses are marked as SKIPPED rather than triggering failing retries.
Automated Testing & Bruno API Collection
35 Bruno RequestsThe backend repository includes a git-friendly Bruno API Collection with 35 automated requests covering sections, assets, tasks, trains, block windows, and AI endpoints:
Production Cloud Deployment (Render / Docker)
Because the AI models run in-memory within the Django process, no separate AI container or microservice port is required.
Memory Optimization for Free Tier (512 MB)
Configure Gunicorn with 2 workers and 2 threads to ensure the in-memory CP-SAT and XGBoost models never trigger Out-Of-Memory (OOM 137) errors:
