Delivered remotely for a business based in Rotterdam, Netherlands. Names withheld by agreement.
Project Overview
Distributors operating out of the port and urban corridors around Rotterdam navigate an intricate web of narrow inner-city streets, canal bridges, timed pedestrian access gates, and strict zero-emission vehicle zones. Dispatch teams relying on manual territory clustering or legacy static routing tables watched vans crisscross neighborhoods needlessly, miss tight B2B receiving windows, and leave electric cargo vans underutilized while diesel trucks absorbed penalties.
We engineered an AI route optimization platform anchored by Python, Google OR-Tools, and FastAPI. Exposed both as a clean integration API for warehouse management systems and an interactive TypeScript planner workbench, the engine converts raw order manifests and heterogeneous fleet profiles into constraint-verified, road-accurate route plans in seconds.
Dispatch & Routing Friction
Replacing intuition-led morning route assembly surfaced four technical hurdles common to dense European last-mile networks:
- Euclidean approximations fail in port cities: Straight-line distance heuristics routed vans straight across waterways or into restricted historic centers where physical detours added twenty minutes per leg.
- Combinatorial constraint explosion: Balancing weight, cubic volume, chilled-vs-ambient compartments, vehicle height limits, tail-lift gear, and mandatory driver lunch breaks overwhelmed manual planning within minutes.
- Mid-shift disruption fragility: Adding urgent same-day pickups or reallocating stops after a vehicle delay previously forced dispatchers to rebuild entire spreadsheets by hand.
- Opaque "infeasible" solver failures: Naive optimization scripts crashed silently whenever a single customer requested an impossible delivery slot, leaving planners unsure which constraint broke the batch.
Architectural Strategy
We split route intelligence into two cooperating layers: learned travel-time estimation and deterministic combinatorial optimization. Rather than expecting a probabilistic model to respect hard physical laws, a lightweight Python gradient-boosted regression service refines historical segment speeds by hour of day, weekday, and weather bucket atop baseline OSRM road-network durations. Those calibrated travel matrices then feed directly into Google OR-Tools' Capacitated Vehicle Routing Problem with Time Windows (CVRPTW) solver.
FastAPI serves as the stateless orchestration boundary, validating GeoJSON coordinates, vehicle skill tags, and time windows with strict Pydantic schemas before dispatching heavy C++-backed OR-Tools searches to isolated worker processes.
Core Capabilities
- Multi-Dimensional Fleet & Skill Matching: Enforces simultaneous payload weight, pallet count, cubic volume, temperature-zone, electric-range, and vehicle-permit constraints (mapping PostGIS zero-emission zone polygons directly to eligible EVs).
- Time-Window & Driver Break Modeling: Respects hard customer receiving hours, soft preferred windows with configurable lateness penalties, and mandatory mid-shift driver rest intervals.
- Dynamic Mid-Shift Re-Routing: Accepts live driver GPS anchors and completed-stop confirmations to insert rush orders or rebalance delayed routes without disrupting stops already underway.
- Graceful Infeasibility Diagnostics: Uses OR-Tools disjunctions so unroutable orders surface with structured root-cause explanations instead of aborting valid routes.
- Interactive Manual Override Sandbox: Allows Rotterdam dispatchers in the TypeScript workbench to pin specific stops to favored drivers, lock sequences, and immediately recalculate downstream ETAs.
Technical Architecture
Order batches arrive at FastAPI via REST from ERP/WMS platforms or the planner UI. After geocoding validation and PostGIS zone tagging, a Celery worker requests an asymmetric travel-time and distance matrix from a local Open Source Routing Machine (OSRM) cluster compiled with regional truck and cargo-van profiles. Python applies time-of-day speed multipliers, constructs the OR-Tools routing index manager and multi-dimension callbacks, and executes Guided Local Search under a deterministic time budget before persisting the winning solution to PostgreSQL.
Flow: ERP / Planner UI → FastAPI Validation & Job Gateway → Redis Task Queue → Celery Python Worker (OSRM Matrix + ML Speed Calibration → OR-Tools CVRPTW Solver) → PostgreSQL / PostGIS Manifest Store → TypeScript Workbench & Driver Dispatch Webhooks
Running OSRM inside the private VPC alongside Redis matrix caches removes external rate limits and latency spikes, letting the solver evaluate dense multi-hundred-stop neighborhoods predictably.
Technology Stack
| Category | Technology detail |
|---|---|
| Optimization Solver | Python with Google OR-Tools solving multi-constraint CVRPTW and pickup-and-delivery models |
| API Gateway | FastAPI asynchronous REST service handling batch job submission, webhooks, and status polling |
| Road Travel Matrices | Self-hosted OSRM routing engine computing turn-by-turn road durations and distance tables |
| Spatial & Job Store | PostgreSQL with PostGIS storing depot zones, zero-emission polygons, and route manifests |
| Worker Queue | Celery worker pool executing CPU-bound OR-Tools searches outside the FastAPI event loop |
| Matrix & Job Cache | Redis caching sub-regional OSRM travel matrices, solver progress telemetry, and locks |
| Planner Workbench | TypeScript React UI for drag-and-drop stop overrides, Gantt timelines, and route comparison |
| ETA Prediction Layer | Python gradient-boosted service adjusting baseline OSRM speeds by time-of-day congestion |
Engineering Trade-offs & Solutions
| Engineering Challenge | Solution & Trade-off |
|---|---|
| CPU-intensive OR-Tools C++ searches block Python asyncio event loops if run inline | Isolated FastAPI solely to async I/O and validation while offloading solver execution to CPU-pinned Celery workers; adds async job polling complexity in exchange for responsive API uptime. |
| Calculating full N×N road matrices for large regional batches slows startup | Combined OSRM contraction hierarchies with Redis coordinate-bucket caching and depot-clustered sub-matrices, trading minor memory overhead for sub-second matrix retrieval. |
| Pure hard constraints fail entire batches when one customer requests an unreachable slot | Configured configurable penalty disjunctions and soft time-window slack variables in OR-Tools, trading strict zero-drop rigidity for actionable partial plans and clear exception diagnostics. |
| Planners distrust "black-box" route changes when they only adjust one stop manually | Implemented warm-start solution locking in OR-Tools so manual pins remain fixed while surrounding legs re-optimize around them, trading tiny theoretical optimality loss for planner trust. |
Security & Multi-Tenant Isolation
Dispatch APIs handle sensitive commercial customer addresses, B2B contract delivery windows, and live driver locations. FastAPI enforces scoped OAuth2 / API-key authentication per tenant organization, isolating route jobs, depot polygons, and vehicle rosters via strict tenant predicates in PostgreSQL.
Self-hosted OSRM processes geographic coordinates purely in memory without persisting customer metadata or transmitting addresses to third-party mapping clouds. Webhook callbacks delivering finalized route sequences sign every payload with HMAC-SHA256 headers so downstream warehouse systems verify authenticity before printing load manifests.
Solver Scaling & Latency Controls
Vehicle routing is NP-hard, meaning unconstrained searches can easily stall on dense urban datasets. To guarantee predictable dispatch cutoffs, every optimization profile enforces explicit search-strategy defaults—pairing Path Cheapest Arc initial construction with Guided Local Search metaheuristics bounded by strict wall-clock and solution-stagnation timeouts.
Large multi-depot operations partition automatically using PostGIS spatial clustering before parallel Celery workers solve regional sub-problems concurrently. Planners receive usable baseline manifests within seconds, with optional deeper refinement passes triggered before morning dock loading begins.
Operational Outcomes
Integrating mathematical constraint solving with local road-network intelligence transformed last-mile dispatch across urban and port corridors:
- Consistent constraint compliance: Zero-emission zone rules, payload ceilings, and driver break windows are verified algorithmically before trucks leave the depot rather than corrected mid-route.
- Calm mid-day exception handling: Urgent pickup additions and late-running routes rebalance around live driver positions without forcing manual manifest rewrites.
- Elimination of external matrix throttling: Self-hosted OSRM delivers repeatable travel-time matrices at full batch scale without third-party API quotas blocking morning cutoffs.
- Transparent planner control: Interactive sequence pinning and structured infeasibility flags let human dispatchers apply local knowledge alongside automated route efficiency.