HomeCase studiesConstraint-Driven AI Route Optimization Engine Built with...

Case study · Rotterdam, Netherlands

Constraint-Driven AI Route Optimization Engine Built with Python, OR-Tools, and FastAPI

Last-Mile Dispatch & Vehicle Routing

Urban parcel and wholesale distributors operating around dense European ports lose hours daily when static spreadsheet routes collide with strict delivery time windows, vehicle payload limits, and municipal zero-emission zones. We engineered an AI route optimization engine built on Python, Google OR-Tools, and FastAPI, paired with self-hosted OSRM road-network matrices and PostGIS spatial rules. Planners submit hundreds of stops and heterogeneous fleet constraints via REST API and receive deterministic, constraint-verified manifest sequences alongside dynamic mid-shift re-optimization.

Industry
Last-Mile Dispatch & Vehicle Routing
Solution
A constraint-aware vehicle routing and dynamic dispatch optimization platform built with Python, OR-Tools, FastAPI, OSRM, and PostGIS.
Platforms
Web & API
Stack
Python · OR-Tools · FastAPI · PostgreSQL · PostGIS · Redis
Location
Rotterdam, Netherlands · delivered remotely
Role
Engineering, with the team behind for mobile and QA

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.

01 — Questions

asked about this kind of project

Why pair Google OR-Tools with a machine-learning travel-time layer instead of asking an LLM or pure neural net to build routes?

Hard logistics constraints—such as cold-compartment capacity, tail-lift requirements, driver break rules, and exact delivery windows—demand mathematical feasibility guarantees. OR-Tools enforces strict constraints deterministically, while ML models refine the underlying edge travel durations fed into the solver.

Why self-host OSRM instead of calling third-party commercial distance-matrix APIs on every optimization run?

Evaluating hundreds of stops produces tens of thousands of origin-destination matrix pairs per batch. Self-hosted OSRM over regional OpenStreetMap extracts computes full asymmetric matrices locally in milliseconds with zero per-element API cost and supports custom truck height or zero-emission road penalties.

How does FastAPI stay responsive while OR-Tools runs multi-second local search heuristics?

FastAPI never runs C++ OR-Tools search inside its async worker threads. Optimization jobs enqueue onto dedicated CPU-pinned Celery workers via Redis, returning a job handle immediately and streaming incremental best-found route improvements via webhooks or polling.

What happens when a high-priority order arrives or a van breaks down mid-morning?

The re-optimization endpoint locks already-completed stops and in-transit anchors, freezes each active driver's current GPS position as a virtual start node, and re-runs OR-Tools with warm-start hints on remaining unassigned stops.

How does the engine handle impossible or over-constrained delivery schedules?

Disjunction penalties allow the solver to drop conflicting low-priority stops gracefully rather than failing the entire batch. Each dropped stop returns an explicit infeasibility reason—such as conflicting time window or exceeded volume—for planner triage.

03 — Similar project?

describe what is different about yours

Build yours.

Tell me what exists, what you need and the deadline. Fixed price for a defined scope, or $55/day (8–9 hours work) with a written plan first.

Solitaire Corporate Park, Makarba, Ahmedabad, Gujarat 380015, India · IST (UTC+5:30) · --:-- IST · Mon–Fri 09:00–18:00 IST · US & EU overlap daily

No newsletter, no CRM. Just a reply.