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 support background work, while manual sync commands discover section timetables and overlay live status from the local indian-rail-mcp / NTES railway service at localhost:3001.

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/                             # 🚀 33-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 trains discovered from active section timetables
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
Audit HistoryGET/railways/maintenance-logs/Read-only maintenance event trail; filter by task, task code, or event
Shared BlocksPOST/railways/block-windows/combined-recommendation/Preview or create one conflict-free block for compatible tasks in the same section
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

Shared Block Recommendation

Compatible tasks on different assets in the same section can be co-planned into one train-conflict-free block. A preview leaves data unchanged; sending the same request with apply: true allocates the combined block window and links every eligible task to it.

Preview a shared maintenance block
POST /railways/block-windows/combined-recommendation/

{
  "task_id": "TMS-784",
  "nearby_days": 2,
  "apply": false
}
Allocate the combined block window
POST /railways/block-windows/combined-recommendation/

{
  "task_id": "TMS-784",
  "nearby_days": 2,
  "apply": true
}

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 Telemetryindian-rail-mcp / NTES

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 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.

Manual Railway Data Sync & Live Status Overlay

Start the local Node railway service at http://localhost:3001, then discover active-section timetables and refresh yesterday’s and today’s live movement records.

Manual sync workflow
uv run python manage.py sync_section_trains
uv run python manage.py sync_railway_data

# Optional: synchronize a specific service date and its preceding day
uv run python manage.py sync_railway_data --date 2026-09-20

# Troubleshoot one train
uv run python manage.py sync_train 14116

Selection and failure isolation

  • At most 30 trains per active section: The first 10 places are reserved for premium or priority services; duplicate train numbers are queried only once.
  • Unknown live status is preserved safely: When the provider cannot give a reliable delay, the train is skipped and existing movement estimates remain intact.
  • Active-day selection: Only trains operating on the target date are selected for a live-status lookup.
  • Run continuity: A failed section or train request is reported without removing existing data or stopping the rest of the manual run.

Automated Testing & Bruno API Collection

33 Bruno Requests

The backend repository includes a git-friendly Bruno API Collection with 33 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
# The local indian-rail-mcp / NTES service is started separately on port 3001