Technology Stack & Role
The LogiRoute codebase is organized as a monorepo to ensure tight integration between backend API validation, dispatcher views, and mobile workflows.
Backend API
Bun + Hono API framework
PostgreSQL / Drizzle ORM
Web Console
Next.js 15+ (App Router)
Tailwind CSS v4 / Zustand
Mobile Clients
Flutter (Android/iOS/Web)
BLoC State / Geolocator
1. The Business & Engineering Problem
Last-mile delivery operations fail when dispatchers, couriers, and clients operate with disconnected states. Traditional architectures face major friction points:
- Serviceability Overlaps: Standard circular distance boundaries fail to map urban realities. Deliveries are assigned to warehouses blocked by rivers, bridges, or highways.
- GPS Database Bloat: Scaling courier networks that ping locations every 10 seconds overwhelms standard OLTP databases.
- Audit Fraud: Couriers clicking "Reached Store" or "Delivered" from home to bypass strict SLAs.
- Billing Ambiguity: Calculating fair compensation across store hubs with different traffic conditions, night shifts, and distances without clear route history records.
2. High-Level System Architecture
I designed a multi-layer database approach: PostgreSQL stores relational states, PostGIS manages store catchment polygons, Redis caches telemetry state keys, and TimescaleDB partitions historical tracking logs.
Houses accounts, catalog objects, and custom drawn service catchments. Evaluates ST_Contains spatial checks on customer orders.
Logs historical driver coordinates. Hypertable chunk sizes are tuned to handle 10-second intervals for large fleets without query performance degradation.
Caches temporary OTP states (5-minute TTL) and ephemeral driver coordinates in GEO indices. Powering the WebSocket live tracking subscriptions.
3. Core Engineering Implementations
A. PostGIS Spatial catchments & Serviceability check
Instead of simple distance checks, stores declare custom service polygons. The admin web portal exposes an interactive Leaflet editor to draw custom polygons or automatically generate a 5km hexagon zone. When checking serviceability, the database uses PostGIS containment:
-- Check if order coords fall within store catchment polygon SELECT id, name, address FROM stores WHERE is_active = true AND ST_Contains( catchment_polygon, ST_SetSRID(ST_Point(longitude, latitude), 4326) );
B. Telemetry Pipeline & TimescaleDB Optimization
A Flutter background scheduler pings locations every 10 seconds. Pings are written to Redis for live location retrieval, and asynchronously bulk-written to TimescaleDB. To render these paths on the Next.js ops map, we query historical pings.
To prevent loading thousands of raw coordinates over the network, I wrote an on-the-fly path simplifier on the Hono backend implementing the **Ramer-Douglas-Peucker (RDP)** algorithm. This simplifies coordinates based on perpendicular distance thresholds, reducing payload size by **80% to 90%** while preserving the route shape:
/** Conceptual RDP path-simplifier inside server/src/utils/rdp.ts **/ export function simplifyPath(points: Point[], epsilon: number): Point[] { if (points.length <= 2) return points; let maxDist = 0; let index = 0; const end = points.length - 1; for (let i = 1; i < end; i++) { const d = getPerpendicularDistance(points[i], points[0], points[end]); if (d > maxDist) { maxDist = d; index = i; } } if (maxDist > epsilon) { const rec1 = simplifyPath(points.slice(0, index + 1), epsilon); const rec2 = simplifyPath(points.slice(index), epsilon); return rec1.slice(0, rec1.length - 1).concat(rec2); } return [points[0], points[end]]; }
C. Geofenced Milestone Tracking
To prevent fraud, the backend locks courier workflow progress. Driver APIs for `/reached-store` and `/reached-location` require coordinate parameters. The backend calculates distance from the destination using the **Haversine formula**. If the driver is greater than **100 meters** away, the transaction is rejected:
/** Haversine formula calculation for milestone validation **/ function getDistanceInMeters(lat1, lon1, lat2, lon2): number { const R = 6371e3; -- Earth's radius in meters const phi1 = lat1 * Math.PI/180; const phi2 = lat2 * Math.PI/180; const deltaPhi = (lat2-lat1) * Math.PI/180; const deltaLambda = (lon2-lon1) * Math.PI/180; const a = Math.sin(deltaPhi/2) * Math.sin(deltaPhi/2) + Math.cos(phi1) * Math.cos(phi2) * Math.sin(deltaLambda/2) * Math.sin(deltaLambda/2); const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); return R * c; }
Completed dropoffs are secured by a two-factor handshake: the courier must input a unique **verification PIN** shared with the customer, and upload a delivery proof photo directly to an S3/MinIO bucket.
D. Per-Store Payroll & Financial Settlement Engine
A core driver of system scalability is the payroll calculation. The billing rules engine computes payouts using default or override configurations per store hub:
perOrderRate × Completed DeliveriesperKmRate × Sum of Haversine distance logsThe calculations run in Postgres batches and generate weekly ledgers. Managers audit these on a Next.js console, toggle quarantine holds, and export approved records as standard **bank-compliant clearing CSVs**.
4. Testing, Automation & Verification
To ensure transaction integrity, I wrote automated integration and regression bash smoke tests. These execute full operational scenarios against local Docker services:
5. Key Engineering Accomplishments
Telemetry data payload size saved on historical route loads via RDP simplification.
Average query latency for multi-audience WebSocket syncs and geo checks.
Transaction integrity for payroll batch generations and document S3 locks.
LogiRoute demonstrates that choosing the right tool for the job—such as leveraging PostGIS for spatial checks instead of custom geometry code, caching temporary location metrics in Redis, and simplifying API data payloads—delivers production-grade software that remains responsive at scale.