Unified Backend & Intelligence Engine
DocumentationDjango 6.1 + DRF

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

GEThttp://127.0.0.1:8000/railways/
Interactive DRF Browsable API Root
GEThttp://127.0.0.1:8000/admin/
Django Administration Panel & Data Editor

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:

Backend Directory Architecture
backend/
├── apps/                              # 🚆 Django Business Logic Applications
│   ├── corridors/                     # Railway corridor sections and station codes
│   ├── assets/                        # Track, OHE, traction, and signaling assets
│   ├── maintenance/                   # Defect logs, severity ratings, deadlines & overdue automation
│   ├── trains/                        # Timetables, live train movements & Celery tasks
│   └── blocks/                        # Maintenance windows & in-memory AI constraint solver bridge
│       ├── ai_client.py               # In-memory bridge to RailwayMLEngine (0ms latency)
│       ├── services.py                # Conflict detection & CP-SAT feasible window calculations
│       ├── views.py                   # BlockWindowViewSet (check-conflict, feasible-windows)
│       └── serializers.py             # Serializers with decision_score & algorithm fields
├── src/                               # 🧠 Embedded Railway AI/ML Intelligence Engine
│   ├── decision/                      # Multi-factor maintenance decision & urgency scoring
│   ├── optimization/                  # Google OR-Tools CP-SAT discrete constraint optimizer
│   ├── models/                        # ML failure predictors (calibrated XGBoost, Cox survival)
│   └── features/                      # Operational telemetry & section delay pressure builders
├── models/                            # 📦 11 Serialized AI/ML Pre-Trained Artifacts (.pkl, .pt)
├── bruno/                             # 🚀 35-Request Automated API Test Collection
├── config/                            # ⚙️ Django settings, URLs, Celery instantiation
└── requirements.txt                   # Production dependencies (Django + OR-Tools + ML)

REST API Endpoints Reference

15+ REST Endpoints
DomainMethodEndpoint PathOperational Purpose
CorridorsGET/railways/sections/List all corridor track sections with source/destination station codes
AssetsGET/railways/assets/List infrastructure assets (Engineering, SNT, Traction) with criticality ratings
MaintenanceGET/railways/maintenance-tasks/List maintenance tasks with auto-overdue sync to DELAYED status
TrainsGET/railways/trains/List all trains synchronized via RailKit timetable sync
Live OperationsGET/railways/trains/operations/Combined live tracking view for up to 30 trains with calculated entry/exit delay
SchedulesGET/railways/train-schedules/Weekly timetables with 7-day running bitmask filter (?date=YYYY-MM-DD)
Block WindowsGET/railways/block-windows/List all reserved, available, or blocked corridor windows
Feasible WindowsPOST/railways/block-windows/feasible-windows/Runs in-memory OR-Tools CP-SAT solver to compute safe block windows
AI RecommendationGET/railways/block-windows/{id}/recommendation/Evaluates conflict count and recommends best alternative slot with suggested payload
Auto-Apply SlotPOST/railways/block-windows/{id}/apply-recommendation/1-Click action to automatically update block window to AI-recommended slot
By Task WindowPUT/railways/block-windows/by-task/{task_id}/Update or reserve block window directly by human-readable task code (e.g. TMS-746)
Conflict CheckPOST/railways/block-windows/check-conflict/Detect train movement collisions during proposed maintenance interval

Deep-Dive API Payloads & Responses

POST/railways/block-windows/feasible-windows/
AIOR-Tools CP-SAT0ms Latency

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.

GET/railways/block-windows/{id}/recommendation/
AI Co-PilotDynamic Rescheduling

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.

POST/railways/block-windows/{id}/apply-recommendation/
1-Click ActionAtomic Update

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.

PUT/railways/block-windows/by-task/{task_id}/
Developer FriendlyTask Linked

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.

POST/railways/block-windows/check-conflict/
SafetyCollision Check

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.

GET/railways/trains/operations/
Live TelemetryRailKit Bridge

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:

1. Model-Level Hook

MaintenanceTask.save() evaluates deadlines before committing changes to PostgreSQL.

2. On-the-Fly API Sync

MaintenanceTaskViewSet.get_queryset() runs a bulk update on expired tasks upon every GET request.

3. Midnight Celery Beat

Scheduled at 00:00 IST daily to log and synchronize all expired tasks across all divisions.

Celery Periodic Tasks & RailKit Quota Guards

apps.trains.tasks.sync_all_timetables

Daily at 02:00 AM IST. Syncs full weekly timetables inside atomic transactions.

Crontab(0, 2)
apps.trains.tasks.sync_relevant_live_trains

Every 3 hours. Dispatches tracking tasks for up to 30 operating trains.

Crontab(0, */3)

🛡️ 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 Requests

The backend repository includes a git-friendly Bruno API Collection with 35 automated requests covering sections, assets, tasks, trains, block windows, and AI endpoints:

Automated Test Commands
# Run in-memory embedded AI unit tests (CP-SAT + XGBoost)
python -m unittest tests/test_embedded_ai.py
# Output: Ran 4 tests in ~0.1s — OK

# Verify ML engine health
python -c "from src.services.ml_engine import RailwayMLEngine; print(RailwayMLEngine().health())"

# Execute Bruno API tests via CLI
bru run bruno/ --env Local

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:

bash
gunicorn config.wsgi:application --workers 2 --threads 2 --bind 0.0.0.0:$PORT
Render Production .env
# Required Environment Variables on Render (with Deployed Frontend CORS)
DEBUG=False
SECRET_KEY=generate-a-strong-random-secret-key
DATABASE_URL=postgresql://user:pass@host:5432/railway_db?sslmode=require
ALLOWED_HOSTS=*
CSRF_TRUSTED_ORIGINS=https://backend-oz3h.onrender.com,https://sanket.aryanshrivastava.dev
CORS_ALLOWED_ORIGINS=https://sanket.aryanshrivastava.dev,http://localhost:3000
ENABLE_LIVE_SYNC=False
RAILKIT_API_KEY=your_railkit_api_key