Production-grade real-time fleet monitoring system with edge-to-cloud data pipeline
A full-stack platform for vehicle fleet management with real-time telemetry streaming, geofencing with alerts, OAuth authentication, and privacy-compliant data processing. Built with FastAPI, Next.js, and PostgreSQL.
Live Demo: Fleet Dashboard
- Features
- Architecture
- Tech Stack
- Quick Start
- Deployment
- API Documentation
- Project Structure
- Configuration
- Contributing
- Live Vehicle Tracking: Interactive Leaflet map with real-time position updates for 50 simulated vehicles
- WebSocket Streaming: Sub-second latency telemetry delivery via WebSocket connections
- Vehicle Details: Per-vehicle view with GPS coordinates, speed, occupancy, and AI inference metrics
- Dark Mode: Fully responsive UI with light/dark theme support
- Polygon Drawing: Interactive map-based geofence creation with unlimited vertices
- Enter/Exit Alerts: Notifications when vehicles cross geofence boundaries
- Alert Cooldown: 5-minute cooldown prevents alert spam for the same vehicle
- Geofence Caching: Active geofences are cached (30s TTL) to reduce database load during high-frequency telemetry processing
- Multi-User Support: Each user manages their own geofences with role-based access control
- Multiple Auth Methods: Google OAuth 2.0, GitHub OAuth, Email/Password with JWT
- Password Hashing: Direct
bcryptintegration for reliable cross-platform password handling - Role-Based Access Control (RBAC):
- Admin: Full system access, user management
- User: Dashboard access, personal geofences, alerts
- First User Auto-Admin: First registered user automatically becomes admin
- Session Management: Secure cookie-based sessions with automatic token refresh
- WebSocket Auth: Optional JWT-based authentication for WebSocket connections via query parameter
- Occupancy Trends: Historical data visualization with Recharts
- Fleet Statistics: Real-time metrics for active vehicles, total distance, average speed
- Alert Dashboard: Centralized view of all geofence events with severity filtering
- GDPR-Compliant: Built-in consent management and data anonymization
- Privacy Engine: Configurable rules for data redaction and anonymization
- Authenticated Privacy API: All privacy endpoints require valid JWT authentication
- User Privacy Controls: Per-user consent status tracking
- CI/CD Pipeline: Automated testing, linting, and deployment via GitHub Actions
- Containerized: Full Docker Compose orchestration for all services
- Health Checks: Kubernetes-ready liveness and readiness probes
- Prometheus Metrics:
/metricsendpoint for monitoring - Structured Logging: JSON logs with request tracing via
structlog - Rate Limiting: API rate limiting with
slowapi
graph TB
subgraph "Edge Layer"
SIM[Edge Simulator<br/>50 Vehicles]
end
subgraph "Optional Streaming"
KAFKA[Redpanda<br/>Kafka-Compatible]
end
subgraph "Backend Services"
API[FastAPI Backend<br/>Python 3.11]
DB[(PostgreSQL<br/>Database)]
GEO[Geofence Service]
PRIV[Privacy Engine]
TELEM[Telemetry Hub<br/>WebSocket Manager]
end
subgraph "Frontend"
DASH[Next.js Dashboard<br/>TypeScript + React]
MAP[Leaflet Map<br/>Real-time Rendering]
end
SIM -->|HTTP/WebSocket| API
SIM -.->|Optional| KAFKA
KAFKA -.-> API
API <--> DB
API --> GEO
API --> PRIV
API --> TELEM
TELEM -->|WebSocket| DASH
API -->|REST API| DASH
DASH --> MAP
style SIM fill:#e1f5ff
style API fill:#fff3e0
style DB fill:#f3e5f5
style DASH fill:#e8f5e9
style KAFKA fill:#fff9c4
- Edge Simulation: Python simulator generates realistic telemetry for 50 vehicles (GPS, speed, occupancy)
- Ingestion: FastAPI backend receives telemetry via HTTP or Kafka (optional)
- Processing:
- Geofence Service checks vehicle positions against active zones
- Privacy Engine applies anonymization rules
- Telemetry Hub broadcasts to connected WebSocket clients
- Storage: PostgreSQL stores vehicles, users, geofences, and alerts
- Real-time Delivery: Next.js dashboard receives updates via WebSocket and renders on interactive map
| Component | Technology | Purpose |
|---|---|---|
| Framework | FastAPI 0.109+ | High-performance async API framework |
| Runtime | Python 3.11 | Modern Python with async/await support |
| Database | PostgreSQL 16 | Relational database with PostGIS support |
| ORM | SQLAlchemy 2.0 | Async ORM for database operations |
| Auth | Authlib + python-jose + bcrypt | OAuth 2.0, JWT tokens, password hashing |
| WebSocket | websockets 12.0 | Real-time bidirectional communication |
| Validation | Pydantic 2.5 | Data validation and settings management |
| Streaming | Redpanda (optional) | Kafka-compatible event streaming |
| Monitoring | Prometheus | Metrics collection and alerting |
| Component | Technology | Purpose |
|---|---|---|
| Framework | Next.js 14 | React framework with SSR/SSG |
| Language | TypeScript 5.3 | Type-safe JavaScript |
| Styling | Tailwind CSS 3.4 | Utility-first CSS framework |
| Maps | Leaflet 1.9 + React-Leaflet | Interactive map rendering |
| Charts | Recharts 2.10 | Data visualization |
| Icons | Lucide React | Customizable icon library |
| UI Components | Custom + CVA | Theme-aware design system |
| Component | Technology | Purpose |
|---|---|---|
| Containers | Docker + Docker Compose | Service orchestration |
| CI/CD | GitHub Actions | Automated testing and deployment |
| Backend Hosting | Railway | Managed PostgreSQL + app hosting |
| Frontend Hosting | Vercel | Serverless Next.js deployment |
| Linting | Ruff (Python) + ESLint (TS) | Code quality enforcement |
| Formatting | Black (Python) + Prettier (TS) | Consistent code style |
- Docker & Docker Compose (20.10+)
- Python 3.11+ (for local development)
- Node.js 20+ (for frontend development)
- Git 2.0+
git clone https://github.com/Technocrat-dev/Fleet-Vehicle-Gateway.git
cd Fleet-Vehicle-GatewayCreate .env file in the backend/ directory:
cp backend/.env.example backend/.envBackend .env (minimum required):
# Database
DATABASE_URL=postgresql+asyncpg://postgres:postgres@postgres:5432/fleet_gateway
# Security
SECRET_KEY=your-secret-key-here-min-32-chars
# OAuth (optional for local dev)
GOOGLE_CLIENT_ID=your-google-client-id
GOOGLE_CLIENT_SECRET=your-google-secret
GITHUB_CLIENT_ID=your-github-client-id
GITHUB_CLIENT_SECRET=your-github-secret
# Application
APP_ENV=development
DEBUG=true
SIMULATOR_VEHICLE_COUNT=50Frontend .env.local:
cp frontend/.env.example frontend/.env.localNEXT_PUBLIC_API_URL=http://localhost:8000# Start backend + database
docker-compose up -d
# View logs
docker-compose logs -f backendThe services will be available at:
- Frontend: http://localhost:3000
- Backend API: http://localhost:8000
- API Docs: http://localhost:8000/docs
- Database: localhost:5432
For hot-reload during development:
cd frontend
npm install
npm run dev- Open http://localhost:3000
- Click "Sign Up" to create an account (first user becomes admin)
- Explore the dashboard:
- Live Map: See 50 vehicles moving in real-time
- Geofences: Click "Geofences" → "Create Geofence" to draw a zone
- Alerts: View notifications when vehicles enter/exit zones
Both the backend and frontend are deployed as containers on Google Cloud Run (free tier). The database is hosted on Neon (free tier PostgreSQL).
| Service | URL |
|---|---|
| Backend API | https://fleet-api-<project-number>.us-central1.run.app |
| Frontend | https://fleet-frontend-<project-number>.us-central1.run.app |
| API Docs | https://fleet-api-<project-number>.us-central1.run.app/docs |
If you have gcloud configured, deploy directly:
# Backend
cd backend
gcloud builds submit --config=cloudbuild.yaml
gcloud run deploy fleet-api \
--image us-central1-docker.pkg.dev/$PROJECT_ID/fleet-gateway-repo/fleet-api:latest \
--region us-central1 --allow-unauthenticated --port 8000
# Frontend
cd frontend
gcloud builds submit --config=cloudbuild.yaml \
--substitutions=_API_URL=https://your-api-url,_WS_URL=wss://your-api-url/ws/telemetry
gcloud run deploy fleet-frontend \
--image us-central1-docker.pkg.dev/$PROJECT_ID/fleet-gateway-repo/fleet-frontend:latest \
--region us-central1 --allow-unauthenticated --port 3000The project uses GitHub Actions for automated testing and deployment:
-
CI (
.github/workflows/ci.yml): Runs on every push and PR- Backend:
rufflint,blackformat check,pytest(47 tests) - Frontend:
eslint, TypeScript check, build verification - Docker: Multi-stage build validation
- Backend:
-
CD (
.github/workflows/cd.yml): Runs on push tomain- Authenticates to GCP via Workload Identity Federation (keyless)
- Builds and pushes images to Artifact Registry
- Deploys to Cloud Run (backend first, then frontend)
Required GitHub Secrets for CD:
| Secret | Description |
|---|---|
GCP_PROJECT_ID |
Your GCP project ID |
GCP_WIF_PROVIDER |
Workload Identity Federation provider resource name |
GCP_SA_EMAIL |
Service account email for deployments |
API_URL |
Backend API URL (for frontend build) |
WS_URL |
WebSocket URL (for frontend build) |
| Endpoint | Method | Description |
|---|---|---|
/auth/register |
POST | Register new user (email/password) |
/auth/login |
POST | Login with email/password |
/auth/google/login |
GET | Initiate Google OAuth flow |
/auth/github/login |
GET | Initiate GitHub OAuth flow |
/auth/callback |
GET | OAuth callback handler |
/auth/me |
GET | Get current user info |
| Endpoint | Method | Auth | Description |
|---|---|---|---|
/api/vehicles |
GET | Required | List all vehicles |
/api/vehicles/{id} |
GET | Required | Get vehicle details |
/api/vehicles/{id}/telemetry |
GET | Required | Get recent telemetry for vehicle |
| Endpoint | Method | Auth | Description |
|---|---|---|---|
/api/geofences |
GET | Required | List user's geofences |
/api/geofences |
POST | Required | Create new geofence |
/api/geofences/{id} |
GET | Required | Get geofence details |
/api/geofences/{id} |
PUT | Required | Update geofence |
/api/geofences/{id} |
DELETE | Required | Delete geofence |
| Endpoint | Method | Auth | Description |
|---|---|---|---|
/api/alerts |
GET | Required | List user's alerts |
/api/alerts/unread-count |
GET | Required | Get unread alert count |
/api/alerts/{id}/acknowledge |
POST | Required | Mark alert as acknowledged |
| Endpoint | Method | Auth | Description |
|---|---|---|---|
/api/analytics/occupancy |
GET | Required | Occupancy trends over time |
/api/analytics/fleet-stats |
GET | Required | Fleet-wide statistics |
| Endpoint | Protocol | Auth | Description |
|---|---|---|---|
/ws/telemetry |
WebSocket | Optional | Real-time telemetry stream (pass ?token=<jwt> for authenticated sessions) |
/ws/alerts |
WebSocket | Required | Real-time alert notifications |
| Endpoint | Method | Auth | Description |
|---|---|---|---|
/health |
GET | None | Health check (includes DB connectivity) |
/ready |
GET | None | Readiness probe |
/metrics |
GET | None | Prometheus metrics |
/docs |
GET | None | Interactive API documentation (Swagger) |
Interactive API Docs: Visit http://localhost:8000/docs for full Swagger documentation with try-it-out functionality.
fleet-vehicle-gateway/
├── backend/ # FastAPI backend
│ ├── app/
│ │ ├── api/ # REST & WebSocket endpoints
│ │ │ ├── analytics.py # Analytics endpoints
│ │ │ ├── geofencing.py # Geofence CRUD + alert system
│ │ │ ├── privacy.py # Privacy controls (authenticated)
│ │ │ ├── users.py # User management
│ │ │ ├── vehicles.py # Vehicle endpoints
│ │ │ └── websocket.py # WebSocket handlers (optional auth)
│ │ ├── auth/ # Authentication
│ │ │ ├── dependencies.py # Auth dependencies
│ │ │ ├── jwt.py # JWT token handling
│ │ │ ├── oauth.py # OAuth providers (Google, GitHub)
│ │ │ ├── router.py # Auth routes
│ │ │ └── security.py # Password hashing (bcrypt) + token utils
│ │ ├── core/ # Core configuration
│ │ │ ├── config.py # Settings management
│ │ │ ├── database.py # DB connection & session
│ │ │ ├── geo_utils.py # Shared geometry utilities
│ │ │ ├── logging.py # Structured logging setup
│ │ │ ├── migrations.py # Startup migrations
│ │ │ └── permissions.py # RBAC logic
│ │ ├── models/ # Data models
│ │ │ ├── db_models.py # SQLAlchemy ORM models
│ │ │ └── schemas.py # Pydantic request/response schemas
│ │ ├── services/ # Business logic
│ │ │ ├── geofence_service.py # Geofence monitoring (with caching)
│ │ │ ├── kafka_consumer.py # Kafka telemetry consumer
│ │ │ ├── privacy_engine.py # GDPR anonymization engine
│ │ │ ├── simulator_service.py # Vehicle telemetry simulator
│ │ │ └── telemetry_hub.py # WebSocket broadcast hub
│ │ └── main.py # FastAPI app entrypoint
│ ├── tests/ # Backend tests (47 tests)
│ ├── Dockerfile # Backend container
│ └── requirements.txt # Python dependencies
│
├── frontend/ # Next.js dashboard
│ ├── app/ # Next.js 14 app directory
│ │ ├── dashboard/ # Main dashboard page
│ │ ├── geofences/ # Geofence management UI
│ │ │ ├── page.tsx # Geofence list & create modal
│ │ │ └── GeofenceMapComponent.tsx # Interactive polygon drawer
│ │ ├── login/ # Auth pages
│ │ ├── register/
│ │ └── layout.tsx # Root layout
│ ├── components/ # Reusable UI components
│ │ ├── FleetMap.tsx # Main map with vehicle markers
│ │ ├── NotificationBell.tsx # Real-time alert notifications
│ │ ├── VehicleCard.tsx # Vehicle detail cards
│ │ └── ThemeToggle.tsx # Dark mode toggle
│ ├── lib/ # Utilities
│ │ ├── auth.ts # Auth helper (fetchWithAuth)
│ │ └── utils.ts # Common utilities
│ ├── public/ # Static assets
│ └── Dockerfile # Frontend container
│
├── edge/ # Edge gateway simulator
│ └── src/
│ ├── simulator.py # Fleet data simulator (50 vehicles)
│ ├── kafka_producer.py # Kafka telemetry producer
│ └── ai_inference.py # Simulated YOLOv11 inference
│
├── .github/
│ └── workflows/
│ ├── ci.yml # CI pipeline (test, lint, build)
│ └── cd.yml # CD pipeline (deploy)
│
├── deploy/ # Deployment configs
│ ├── railway.json # Railway service config
│ └── vercel.json # Vercel deployment config
│
├── docs/ # Documentation
├── docker-compose.yml # Local development orchestration
└── README.md # You are here!
| Variable | Required | Default | Description |
|---|---|---|---|
DATABASE_URL |
- | PostgreSQL connection string (asyncpg format) | |
SECRET_KEY |
- | JWT signing key (min 32 chars) | |
APP_ENV |
development |
Environment: development, production |
|
DEBUG |
false |
Enable debug mode | |
BACKEND_HOST |
0.0.0.0 |
Server bind address | |
BACKEND_PORT |
8000 |
Server port | |
CORS_ORIGINS |
["*"] |
Allowed CORS origins (JSON array) | |
GOOGLE_CLIENT_ID |
- | Google OAuth client ID | |
GOOGLE_CLIENT_SECRET |
- | Google OAuth secret | |
GITHUB_CLIENT_ID |
- | GitHub OAuth client ID | |
GITHUB_CLIENT_SECRET |
- | GitHub OAuth secret | |
OAUTH_REDIRECT_URL |
- | OAuth callback URL | |
KAFKA_ENABLED |
false |
Enable Kafka consumer | |
KAFKA_BOOTSTRAP_SERVERS |
localhost:19092 |
Kafka broker addresses | |
SIMULATOR_VEHICLE_COUNT |
50 |
Number of simulated vehicles | |
SIMULATOR_UPDATE_INTERVAL_MS |
1000 |
Telemetry update frequency (ms) |
| Variable | Required | Default | Description |
|---|---|---|---|
NEXT_PUBLIC_API_URL |
- | Backend API base URL |
Note: All NEXT_PUBLIC_* variables are embedded at build time and exposed to the browser.
The backend has 47 tests covering authentication, API endpoints, health checks, and core services (privacy engine, telemetry hub, geofence utilities).
cd backend
# Install dev dependencies
pip install pytest pytest-asyncio pytest-cov httpx aiosqlite
# Run all tests
pytest
# Run with coverage
pytest --cov=app tests/
# Run specific test file
pytest tests/test_auth.py -v
pytest tests/test_services.py -vcd frontend
# Lint
npm run lint
# Type check
npx tsc --noEmit
# Build verification
npm run build# Build all images
docker-compose build
# Start in detached mode
docker-compose up -d
# Check logs
docker-compose logs -f
# Run health checks
curl http://localhost:8000/health
curl http://localhost:3000Contributions are welcome! Please follow these guidelines:
- Fork the repository
- Create a feature branch:
git checkout -b feature/amazing-feature - Commit your changes:
git commit -m 'Add amazing feature' - Push to branch:
git push origin feature/amazing-feature - Open a Pull Request
- Backend: Follow PEP 8, enforced by
ruffandblack - Frontend: Follow ESLint + TypeScript strict mode
- Commits: Use Conventional Commits format
All PRs must:
- Pass CI checks (lint, type check, build)
- Include tests for new features
- Maintain or improve code coverage
This project is licensed under the MIT License - see the LICENSE file for details.
- FastAPI - Async Python web framework
- Next.js - React framework
- Leaflet - Open-source interactive maps
- Redpanda - Kafka-compatible streaming
- Railway and Vercel - Deployment platforms
Developer: Manas Sharma
GitHub: @Technocrat-dev
Project Link: Fleet Vehicle Gateway