Skip to main content
Routal

Capacitated distribution

When weight, volume, cold chain, or specialist equipment are non-negotiable. The optimizer respects every constraint you declare; the cost of not declaring them is a truck that gets to the third stop, runs out of room, and has to come back to the depot. This recipe walks the constraint matrix, the operational patterns for cold chain, oversized loads, and mixed fleets, and the webhook cycle that dispatches what fits and tells you which stops did not.

Who this is for

Your operation moves physical goods with hard physical constraints:

  • A wholesaler distributing palletized goods to retailers, where every truck has a finite load capacity in weight and pallet positions.
  • A frozen / refrigerated foods distributor maintaining the cold chain end-to-end, where only specific vehicles carry refrigeration.
  • A beverage / bottled water / gas distributor where volume is the binding constraint rather than weight: a van full of empty 18L containers weighs little but the truck is "full".
  • A specialty chemicals or hazardous goods distributor, where only licensed vehicles can carry certain SKUs.
  • A pharmacy or vaccine distribution chain, where temperature-controlled and chain-of-custody are both binding.

What makes you different from a generic last-mile operation: the wrong truck showing up at the wrong stop is not "inefficient", it's "broken". A van without refrigeration cannot serve a frozen-foods stop; a 3.5-ton van cannot serve a stop that needs an 8-ton truck; a driver without ADR can't carry hazardous goods.

This recipe walks through the constraint matrix and the operational patterns that make the optimizer respect every declared constraint, including what to do when the midnight run leaves stops without a route and the nightly batch can't ship them.

The constraint matrix

Three families of constraint, each with a different shape:

FamilyWhat it constrainsStop fieldsVehicle fields
CapacityHow much one vehicle can carry.weight (kg), volume (m³)max_weight, max_volume, max_services
SkillsWhat kinds of goods a vehicle can carry.requires: ["frozen", "adr", "oversized"]provides: ["frozen", ...]
GeometryWhen and from where the vehicle operates.time_windows, locationtime_window, start_location, end_location, max_distance, max_time

Vehicle fields are named as you send them to POST /v3/vehicles. Reads and PUT /v2/vehicle/{vehicle_id} add a default_ prefix: max_weight on create is default_max_weight when you read it, provides is default_provides.

The optimizer treats all three as hard constraints. A vehicle that doesn't satisfy all three for a candidate stop will not be assigned that stop, even if relaxing one constraint would produce a better overall plan.

Capacity: the most common constraint

Set on every stop:

{
  "external_id": "ORDER-9001",
  "label": "Acme Restaurant",
  "weight": 32,    // kilograms, sum of all items in this order
  "volume": 0.4    // cubic meters, sum of all items in this order
}

Set on every vehicle (becomes the default on every route it executes):

{
  "external_id": "TRUCK-007",
  "label": "Truck 007 (8-ton)",
  "max_weight": 8000,    // 8 tonnes
  "max_volume": 35,      // 35 m³
  "max_services": 25     // optional cap on stops/day for driver fatigue
}

The optimizer sums weight/volume of all stops on a route and won't exceed the vehicle's max. If your operation is dominated by volume (bottled beverages, packaging, empty containers), set max_volume. If it's dominated by weight (industrial supplies, beverage cases, hardware), set max_weight. Most operations set both, even if one is rarely the binding one.

max_services caps stops/day per driver. Useful for residential delivery operations where 25 stops is a long day regardless of weight; less useful for B2B where it's typically 8–12.

Skills: requires and provides

When the constraint isn't "how much" but "what kind", use skill matching:

// stop
{
  "external_id": "ORDER-9001",
  "requires": ["frozen"]
}

// vehicle
{
  "external_id": "TRUCK-007",
  "provides": ["frozen", "refrigerated", "ambient"]
}

A vehicle that provides a superset of what the stop requires is eligible. Empty requires means "any vehicle is fine", the default.

Skill examples that show up in real operations:

Skill string (suggested)What it means
frozenVehicle has freezer compartment (≤ -18°C).
refrigeratedVehicle has chilled compartment (0 to 4°C).
ambientVehicle is room temperature (default for most).
adr-class-3Driver and vehicle licensed for flammable liquids (ADR class 3).
oversizedVehicle is large enough for oversized items (mattresses, large appliances).
tail-liftVehicle has a tail lift for unloading heavy items without a forklift.
crew-2Two-person crew (some installations or heavy unloadings require it).
forklift-pickupStop has a forklift on site, so the vehicle can be a regular truck.

Be explicit. requires: ["frozen"] matches provides: ["frozen", "ambient"] because freezer trucks usually carry ambient too. But a frozen stop will not match a vehicle that only provides: ["refrigerated"]: chilled and frozen are different chambers.

Production code

The code below covers the capacitated parts end to end: the fleet with capacity and skills, the stop shape (weight, volume, skill requirements, narrow service durations), the pre-flight, and the webhook cycle that dispatches what fit and pages you about what didn't. Plan creation and the nightly cron are the same as nightly batch B2B.

Nothing here polls. optimizePlan ends right after it starts the run; the optimization.succeeded webhook picks up from there.

# (0) Once, on deploy: register the webhook. Run
#     GET /v2/webhooks?project_id=PROJECT_ID first and PUT /v2/webhook/{id}
#     instead when your url is already there, so redeploys don't add a second one.
curl -X POST "https://api.routal.com/v2/webhook?private_key=YOUR_KEY&project_id=PROJECT_ID" \
  -H 'Content-Type: application/json' \
  -d '{
    "url": "https://erp.example.com/webhooks/routal?token=LONG_RANDOM_TOKEN",
    "enabled_events": [
      "routal.optimizer.2.optimization.succeeded",
      "routal.optimizer.2.optimization.failed",
      "routal.planner.2.stop.reported",
      "routal.drivers.2.route.finished"
    ],
    "enabled": true
  }'

#     Check the endpoint answers (2xx within 10 s) before relying on it.
curl -X POST "https://api.routal.com/v2/webhook/WEBHOOK_ID/test?private_key=YOUR_KEY" \
  -H 'Content-Type: application/json' \
  -d '{ "event_type": "routal.planner.2.stop.reported" }'

# (1) Onboard the fleet: bulk-create vehicles with max_* + provides. No
#     default_ prefix on create; reads return default_max_weight etc.
curl -X POST "https://api.routal.com/v3/vehicles?private_key=YOUR_KEY&project_id=PROJECT_ID" \
  -H 'Content-Type: application/json' \
  -d '[
    {
      "external_id": "TRUCK-FROZEN-001",
      "label": "Truck 001 (frozen, 8t)",
      "provides": ["frozen", "refrigerated", "ambient"],
      "max_weight": 8000,
      "max_volume": 35,
      "max_services": 30,
      "time_window": [21600, 64800]
    },
    {
      "external_id": "TRUCK-AMBIENT-002",
      "label": "Truck 002 (ambient, 3.5t)",
      "provides": ["ambient"],
      "max_weight": 3500,
      "max_volume": 18,
      "max_services": 35,
      "time_window": [21600, 64800]
    }
  ]'

# (2) Bulk-add stops with weight, volume, requires. Stops requiring "frozen"
#     can only land on the frozen truck.
curl -X POST "https://api.routal.com/v2/stops?private_key=YOUR_KEY&plan_id=PLAN_ID&project_id=PROJECT_ID" \
  -H 'Content-Type: application/json' \
  -d '[
    {
      "external_id": "ORDER-9001",
      "label": "FrozenFoods Restaurant A",
      "location": { "lat": 41.20, "lng": 2.05 },
      "duration": 600,
      "time_windows": [[28800, 43200]],
      "weight": 120,
      "volume": 0.8,
      "requires": ["frozen"]
    },
    {
      "external_id": "ORDER-9002",
      "label": "Beta Hardware Store",
      "location": { "lat": 41.18, "lng": 2.07 },
      "duration": 480,
      "time_windows": [[28800, 50400]],
      "weight": 240,
      "volume": 1.4,
      "requires": []
    }
  ]'

# (3) Optimize once the pre-flight passes. Returns at once: the result is the
#     routal.optimizer.2.optimization.succeeded (or .failed) webhook for PLAN_ID.
curl -X POST "https://api.routal.com/v2/plan/PLAN_ID/optimize/async?private_key=YOUR_KEY"

# (4) On optimization.succeeded: read the routes and dispatch each one that
#     has stops. Then list the plan's stops: any without a route_id did not
#     fit a constraint. Page the supervisor with them.
curl "https://api.routal.com/v2/plan/PLAN_ID/routes?private_key=YOUR_KEY"
curl -X POST "https://api.routal.com/v2/route/ROUTE_ID/dispatch?private_key=YOUR_KEY"
curl "https://api.routal.com/v2/plan/PLAN_ID/stops?private_key=YOUR_KEY"

# (5) Nightly: list yesterday's failed deliveries and resend the ones your
#     ERP never processed. The resent payload keeps its original id.
curl "https://api.routal.com/v2/webhook/WEBHOOK_ID/events?private_key=YOUR_KEY&status=error&date=2026-05-22&limit=100"
curl -X POST "https://api.routal.com/v2/webhook/event/LOG_ENTRY_ID/resend?private_key=YOUR_KEY"
import createClient from 'openapi-fetch';
import express from 'express';
import type { paths } from './routal';

const routal = createClient<paths>({ baseUrl: 'https://api.routal.com' });
const ROUTAL_API_KEY = process.env.ROUTAL_API_KEY!;
const PROJECT_ID = process.env.ROUTAL_PROJECT_ID!;
const WEBHOOK_TOKEN = process.env.ROUTAL_WEBHOOK_TOKEN!; // long random string
const WEBHOOK_URL = `https://erp.example.com/webhooks/routal?token=${WEBHOOK_TOKEN}`;
const key = { private_key: ROUTAL_API_KEY };

const EVENTS = [
  'routal.optimizer.2.optimization.succeeded',
  'routal.optimizer.2.optimization.failed',
  'routal.planner.2.stop.reported',
  'routal.drivers.2.route.finished',
] as const;

// ── (0) Webhook setup: run on every deploy ───────────────────────────────

/** Find-or-update on url, so a redeploy never adds a second webhook. */
export async function ensureWebhook(): Promise<string> {
  const { data: hooks, error } = await routal.GET('/v2/webhooks', {
    params: { query: { ...key, project_id: PROJECT_ID } },
  });
  if (error) throw error;

  const body = { url: WEBHOOK_URL, enabled_events: [...EVENTS], enabled: true };
  const existing = (hooks ?? []).find((h) => h.url === WEBHOOK_URL);
  const { data: hook, error: saveErr } = existing
    ? await routal.PUT('/v2/webhook/{id}', { params: { path: { id: existing.id }, query: key }, body })
    : await routal.POST('/v2/webhook', { params: { query: { ...key, project_id: PROJECT_ID } }, body });
  if (saveErr) throw saveErr;

  // Fails unless the endpoint answers 2xx within 10 seconds.
  const { error: testErr } = await routal.POST('/v2/webhook/{id}/test', {
    params: { path: { id: hook!.id }, query: key },
    body: { event_type: 'routal.planner.2.stop.reported' },
  });
  if (testErr) throw testErr;
  return hook!.id;
}

// ── (1-2) Fleet and stops ────────────────────────────────────────────────

type CapacitatedOrder = {
  id: string;
  customer: string;
  lat: number;
  lng: number;
  serviceMinutes: number;
  windowFromSec: number;
  windowToSec: number;
  weightKg: number;            // explicit: never omit on a capacitated plan
  volumeM3: number;            // explicit: never omit on a capacitated plan
  requires: string[];          // ['frozen'], ['adr-class-3'], etc.
};

type CapacitatedVehicle = {
  id: string;
  label: string;
  provides: string[];          // superset of what stops can require
  maxWeightKg: number;
  maxVolumeM3: number;
  maxServices?: number;
  startSec: number;            // working window start, seconds from midnight
  endSec: number;
};

/** Onboard the fleet once, typically during initial integration setup. */
export async function syncCapacitatedFleet(vehicles: CapacitatedVehicle[]): Promise<void> {
  const { error } = await routal.POST('/v3/vehicles', {
    params: { query: { ...key, project_id: PROJECT_ID } },
    body: vehicles.map((v) => ({
      external_id: v.id,
      label: v.label,
      provides: v.provides,
      max_weight: v.maxWeightKg,
      max_volume: v.maxVolumeM3,
      max_services: v.maxServices,
      time_window: [v.startSec, v.endSec],
    })) as never,
  });
  if (error) throw error;
}

/** Bulk-add capacitated stops to a plan. */
export async function bulkAddCapacitatedStops(
  planId: string,
  orders: CapacitatedOrder[],
): Promise<void> {
  if (orders.length === 0) return;
  const { error } = await routal.POST('/v2/stops', {
    params: { query: { ...key, plan_id: planId, project_id: PROJECT_ID } },
    body: orders.map((o) => ({
      external_id: o.id,
      label: o.customer,
      location: { lat: o.lat, lng: o.lng },
      duration: o.serviceMinutes * 60,
      time_windows: [[o.windowFromSec, o.windowToSec]],
      weight: o.weightKg,         // always present, even if 0
      volume: o.volumeM3,         // always present, even if 0
      requires: o.requires,
    })) as never,
  });
  if (error) throw error;
}

// ── (3) Pre-flight, then start the run and return ────────────────────────

/** Diagnostic: call before optimize to detect obviously infeasible plans. */
export async function preflightCapacityCheck(planId: string): Promise<{
  totalWeight: number;
  totalVolume: number;
  fleetWeight: number;
  fleetVolume: number;
  feasible: boolean;
  unmatchedSkills: string[];
}> {
  const { data: stops } = await routal.GET('/v2/plan/{id}/stops', {
    params: { path: { id: planId }, query: key },
  });
  const { data: vehicles } = await routal.GET('/v2/vehicles', {
    params: { query: { ...key, project_id: PROJECT_ID, limit: 500 } },
  });
  const stopList = (stops as Array<{ weight?: number; volume?: number; requires?: string[] }>) ?? [];
  const vehList = (vehicles?.docs ?? []) as Array<{
    enabled?: boolean;
    default_max_weight?: number;
    default_max_volume?: number;
    default_provides?: string[];
  }>;

  const totalWeight = stopList.reduce((s, x) => s + (x.weight ?? 0), 0);
  const totalVolume = stopList.reduce((s, x) => s + (x.volume ?? 0), 0);
  const activeVeh = vehList.filter((v) => v.enabled !== false);
  const fleetWeight = activeVeh.reduce((s, v) => s + (v.default_max_weight ?? 0), 0);
  const fleetVolume = activeVeh.reduce((s, v) => s + (v.default_max_volume ?? 0), 0);

  const provided = new Set<string>(activeVeh.flatMap((v) => v.default_provides ?? []));
  const unmatchedSkills = Array.from(
    new Set(
      stopList.flatMap((s) => s.requires ?? []).filter((skill) => !provided.has(skill)),
    ),
  );

  return {
    totalWeight,
    totalVolume,
    fleetWeight,
    fleetVolume,
    unmatchedSkills,
    feasible:
      totalWeight <= fleetWeight &&
      totalVolume <= fleetVolume &&
      unmatchedSkills.length === 0,
  };
}

/** No polling: the optimization.succeeded webhook picks up from here. */
export async function optimizePlan(planId: string) {
  const check = await preflightCapacityCheck(planId);
  if (!check.feasible) {
    await alertSupervisor({
      plan_id: planId,
      overage_weight_kg: Math.max(0, check.totalWeight - check.fleetWeight),
      overage_volume_m3: Math.max(0, check.totalVolume - check.fleetVolume),
      unmatched_skills: check.unmatchedSkills,
    });
    return; // don't optimize: we already know the answer
  }
  // Insert-if-absent: a cron that fires twice must not start, or forget, a second run.
  if (!(await pendingRuns.addIfAbsent(planId, new Date()))) return;
  const { error } = await routal.POST('/v2/plan/{id}/optimize/async', {
    params: { path: { id: planId }, query: key },
  });
  if (error) {
    await pendingRuns.remove(planId);
    throw error; // e.g. sync_optimization_already_progress: wait, don't retry
  }
}

// ── (4) Webhook receiver ─────────────────────────────────────────────────

type RoutalEvent = { id?: string; event_id: string; project_id: string; created_at: string; data: any };

const app = express();
app.post('/webhooks/routal', express.json({ limit: '10mb' }), async (req, res) => {
  if (req.query.token !== WEBHOOK_TOKEN) return res.sendStatus(401); // not retried
  const event = req.body as RoutalEvent;
  if (!event.id) return res.sendStatus(200); // test event from /v2/webhook/{id}/test
  await jobs.enqueue('routal-event', event); // durable queue; a throw here → 500 → Routal retries
  res.sendStatus(200);                        // within 10 s, or it counts as a failure
});

/** Worker. Deliveries are at-least-once: the envelope id drops duplicates. */
export async function handleRoutalEvent(event: RoutalEvent) {
  if (await processed.has(event.id!)) return;

  switch (event.event_id) {
    case 'routal.optimizer.2.optimization.succeeded': {
      const planId: string = event.data.plan.id;
      // Runs started from the planner fire this too: only act on yours.
      if (await pendingRuns.remove(planId)) {
        await dispatchRoutes(planId);
        await reportLeftovers(planId);
      }
      break;
    }
    case 'routal.optimizer.2.optimization.failed':
      // The failed event carries no plan id today: page with every run still pending.
      // Those plans keep the routes they had: dispatch nothing.
      await alertSupervisor({ error: event.data.error, pending: await pendingRuns.list() });
      break;
    case 'routal.planner.2.stop.reported':
      await reconcileStop(event.data);
      break;
    case 'routal.drivers.2.route.finished':
      await reconcileRoute(event.data); // every stop of event.data.stops has a final state in the ERP?
      break;
  }
  await processed.add(event.id!);
}

async function dispatchRoutes(planId: string) {
  const { data } = await routal.GET('/v2/plan/{id}/routes', {
    params: { path: { id: planId }, query: key },
  });
  for (const route of (data as Array<{ id: string; stops?: unknown[] }>) ?? []) {
    if (!route.stops?.length) continue; // an empty route has nothing to dispatch
    if (await dispatched.has(route.id)) continue; // dispatch re-sends the driver email
    const { error } = await routal.POST('/v2/route/{id}/dispatch', {
      params: { path: { id: route.id }, query: key },
    });
    if (error) throw error;
    await dispatched.add(route.id);
  }
}

/** Stops no vehicle could take. Page with their constraints; never auto-relax. */
async function reportLeftovers(planId: string) {
  const { data } = await routal.GET('/v2/plan/{id}/stops', {
    params: { path: { id: planId }, query: key },
  });
  type PlanStop = { external_id?: string; route_id?: string; weight?: number; volume?: number; requires?: string[] };
  const leftovers = ((data as PlanStop[]) ?? []).filter((s) => !s.route_id);
  if (leftovers.length === 0) return;
  await alertSupervisor({
    plan_id: planId,
    unrouted: leftovers.map(({ external_id, weight, volume, requires }) => ({ external_id, weight, volume, requires })),
  });
}

const ERP_STATE = {
  service_report_completed: 'delivered',
  service_report_attempted: 'delivery_failed',
  service_report_canceled: 'canceled',
} as const;

async function reconcileStop(stop: any) {
  const report = stop.reports?.at(-1); // data is the stop; its latest report is the new one
  if (!report) return;
  await erp.updateOrder(stop.external_id, {
    state: ERP_STATE[report.type as keyof typeof ERP_STATE],
    signatureUrl: report.signature?.url,
    photoUrls: (report.images ?? []).map((i: { url: string }) => i.url),
    cancelReason: report.cancel_reason,
  });
}

// ── (5) Nightly: replay what the receiver missed ─────────────────────────

export async function replayFailedDeliveries(webhookId: string, date: string) {
  for (let offset = 0; ; offset += 100) {
    const { data, error } = await routal.GET('/v2/webhook/{id}/events', {
      params: { path: { id: webhookId }, query: { ...key, status: 'error', date, offset, limit: 100 } },
    });
    if (error) throw error;
    for (const entry of data!.events as Array<{ id: string; data?: any }>) {
      const payloadId = entry.data?.payload_sent?.id;
      if (payloadId && (await processed.has(payloadId))) continue; // a retry got through
      await routal.POST('/v2/webhook/event/{event_id}/resend', {
        params: { path: { event_id: entry.id }, query: key },
      });
    }
    if (!data!.hasNextPage) break;
  }
}
import os
import requests
from flask import Flask, request

ROUTAL_API_KEY = os.environ["ROUTAL_API_KEY"]
PROJECT_ID = os.environ["ROUTAL_PROJECT_ID"]
WEBHOOK_TOKEN = os.environ["ROUTAL_WEBHOOK_TOKEN"]  # long random string
WEBHOOK_URL = f"https://erp.example.com/webhooks/routal?token={WEBHOOK_TOKEN}"
BASE = "https://api.routal.com"
KEY = {"private_key": ROUTAL_API_KEY}

EVENTS = [
    "routal.optimizer.2.optimization.succeeded",
    "routal.optimizer.2.optimization.failed",
    "routal.planner.2.stop.reported",
    "routal.drivers.2.route.finished",
]


# ── (0) Webhook setup: run on every deploy ───────────────────────────────

def ensure_webhook() -> str:
    """Find-or-update on url, so a redeploy never adds a second webhook."""
    hooks = requests.get(f"{BASE}/v2/webhooks", params={**KEY, "project_id": PROJECT_ID}, timeout=30)
    hooks.raise_for_status()
    body = {"url": WEBHOOK_URL, "enabled_events": EVENTS, "enabled": True}
    existing = next((h for h in hooks.json() if h["url"] == WEBHOOK_URL), None)
    if existing:
        resp = requests.put(f"{BASE}/v2/webhook/{existing['id']}", params=KEY, json=body, timeout=30)
    else:
        resp = requests.post(f"{BASE}/v2/webhook", params={**KEY, "project_id": PROJECT_ID}, json=body, timeout=30)
    resp.raise_for_status()
    hook_id = resp.json()["id"]

    # Fails unless the endpoint answers 2xx within 10 seconds.
    requests.post(
        f"{BASE}/v2/webhook/{hook_id}/test",
        params=KEY,
        json={"event_type": "routal.planner.2.stop.reported"},
        timeout=30,
    ).raise_for_status()
    return hook_id


# ── (1-2) Fleet and stops ────────────────────────────────────────────────

def sync_capacitated_fleet(vehicles: list[dict]) -> None:
    payload = [
        {
            "external_id": v["id"],
            "label": v["label"],
            "provides": v["provides"],
            "max_weight": v["max_weight_kg"],
            "max_volume": v["max_volume_m3"],
            "max_services": v.get("max_services"),
            "time_window": [v["start_sec"], v["end_sec"]],
        }
        for v in vehicles
    ]
    resp = requests.post(
        f"{BASE}/v3/vehicles",
        params={**KEY, "project_id": PROJECT_ID},
        json=payload,
        timeout=60,
    )
    resp.raise_for_status()


def bulk_add_capacitated_stops(plan_id: str, orders: list[dict]) -> None:
    if not orders:
        return
    payload = [
        {
            "external_id": o["id"],
            "label": o["customer"],
            "location": {"lat": o["lat"], "lng": o["lng"]},
            "duration": o["service_minutes"] * 60,
            "time_windows": [[o["window_from_sec"], o["window_to_sec"]]],
            "weight": o["weight_kg"],
            "volume": o["volume_m3"],
            "requires": o["requires"],
        }
        for o in orders
    ]
    resp = requests.post(
        f"{BASE}/v2/stops",
        params={**KEY, "plan_id": plan_id, "project_id": PROJECT_ID},
        json=payload,
        timeout=60,
    )
    resp.raise_for_status()


# ── (3) Pre-flight, then start the run and return ────────────────────────

def list_stops(plan_id: str) -> list[dict]:
    resp = requests.get(f"{BASE}/v2/plan/{plan_id}/stops", params=KEY, timeout=30)
    resp.raise_for_status()
    return resp.json()


def preflight_capacity_check(plan_id: str) -> dict:
    """
    Diagnostic: call before optimize to detect obviously infeasible plans.
    Returns aggregate stop demand vs aggregate fleet supply, plus any required
    skills that no vehicle provides.
    """
    stops = list_stops(plan_id)
    vehicles = requests.get(
        f"{BASE}/v2/vehicles",
        params={**KEY, "project_id": PROJECT_ID, "limit": 500},
        timeout=30,
    ).json().get("docs", [])

    total_weight = sum(s.get("weight") or 0 for s in stops)
    total_volume = sum(s.get("volume") or 0 for s in stops)
    active = [v for v in vehicles if v.get("enabled") is not False]
    fleet_weight = sum(v.get("default_max_weight") or 0 for v in active)
    fleet_volume = sum(v.get("default_max_volume") or 0 for v in active)

    provided = {p for v in active for p in (v.get("default_provides") or [])}
    required = {r for s in stops for r in (s.get("requires") or [])}
    unmatched = sorted(required - provided)

    return {
        "total_weight": total_weight,
        "total_volume": total_volume,
        "fleet_weight": fleet_weight,
        "fleet_volume": fleet_volume,
        "unmatched_skills": unmatched,
        "feasible": (
            total_weight <= fleet_weight
            and total_volume <= fleet_volume
            and not unmatched
        ),
    }


def optimize_plan(plan_id: str) -> None:
    """No polling: the optimization.succeeded webhook picks up from here."""
    check = preflight_capacity_check(plan_id)
    if not check["feasible"]:
        alert_supervisor(
            plan_id=plan_id,
            overage_weight_kg=max(0, check["total_weight"] - check["fleet_weight"]),
            overage_volume_m3=max(0, check["total_volume"] - check["fleet_volume"]),
            unmatched_skills=check["unmatched_skills"],
        )
        return  # don't optimize: we already know the answer
    # Insert-if-absent: a cron that fires twice must not start, or forget, a second run.
    if not pending_runs.add_if_absent(plan_id):
        return
    resp = requests.post(f"{BASE}/v2/plan/{plan_id}/optimize/async", params=KEY, timeout=60)
    if not resp.ok:
        pending_runs.remove(plan_id)
        resp.raise_for_status()  # e.g. sync_optimization_already_progress: wait, don't retry


# ── (4) Webhook receiver ─────────────────────────────────────────────────

app = Flask(__name__)


@app.post("/webhooks/routal")
def routal_webhook():
    if request.args.get("token") != WEBHOOK_TOKEN:
        return "", 401  # not retried
    event = request.get_json()
    if not event.get("id"):
        return "", 200  # test event from /v2/webhook/{id}/test
    jobs.enqueue("routal-event", event)  # durable queue; an exception here → 500 → Routal retries
    return "", 200  # within 10 s, or it counts as a failure


ERP_STATE = {
    "service_report_completed": "delivered",
    "service_report_attempted": "delivery_failed",
    "service_report_canceled": "canceled",
}


def handle_routal_event(event: dict) -> None:
    """Worker. Deliveries are at-least-once: the envelope id drops duplicates."""
    if processed.has(event["id"]):
        return
    kind, data = event["event_id"], event["data"]

    if kind == "routal.optimizer.2.optimization.succeeded":
        plan_id = data["plan"]["id"]
        # Runs started from the planner fire this too: only act on yours.
        if pending_runs.remove(plan_id):
            dispatch_routes(plan_id)
            report_leftovers(plan_id)
    elif kind == "routal.optimizer.2.optimization.failed":
        # The failed event carries no plan id today: page with every run still pending.
        # Those plans keep the routes they had: dispatch nothing.
        alert_supervisor(error=data.get("error"), pending=pending_runs.list())
    elif kind == "routal.planner.2.stop.reported":
        reconcile_stop(data)
    elif kind == "routal.drivers.2.route.finished":
        reconcile_route(data)  # every stop of data["stops"] has a final state in the ERP?

    processed.add(event["id"])


def dispatch_routes(plan_id: str) -> None:
    resp = requests.get(f"{BASE}/v2/plan/{plan_id}/routes", params=KEY, timeout=30)
    resp.raise_for_status()
    for route in resp.json():
        if not route.get("stops"):
            continue  # an empty route has nothing to dispatch
        if dispatched.has(route["id"]):
            continue  # dispatch re-sends the driver email
        requests.post(f"{BASE}/v2/route/{route['id']}/dispatch", params=KEY, timeout=30).raise_for_status()
        dispatched.add(route["id"])


def report_leftovers(plan_id: str) -> None:
    """Stops no vehicle could take. Page with their constraints; never auto-relax."""
    leftovers = [s for s in list_stops(plan_id) if not s.get("route_id")]
    if leftovers:
        alert_supervisor(
            plan_id=plan_id,
            unrouted=[
                {k: s.get(k) for k in ("external_id", "weight", "volume", "requires")}
                for s in leftovers
            ],
        )


def reconcile_stop(stop: dict) -> None:
    reports = stop.get("reports") or []
    if not reports:
        return
    report = reports[-1]  # data is the stop; its latest report is the new one
    erp.update_order(
        stop["external_id"],
        state=ERP_STATE[report["type"]],
        signature_url=(report.get("signature") or {}).get("url"),
        photo_urls=[i["url"] for i in report.get("images") or []],
        cancel_reason=report.get("cancel_reason"),
    )


# ── (5) Nightly: replay what the receiver missed ─────────────────────────

def replay_failed_deliveries(webhook_id: str, date: str) -> None:
    offset = 0
    while True:
        resp = requests.get(
            f"{BASE}/v2/webhook/{webhook_id}/events",
            params={**KEY, "status": "error", "date": date, "offset": offset, "limit": 100},
            timeout=30,
        )
        resp.raise_for_status()
        page = resp.json()
        for entry in page["events"]:
            payload_id = ((entry.get("data") or {}).get("payload_sent") or {}).get("id")
            if payload_id and processed.has(payload_id):
                continue  # a retry got through
            requests.post(f"{BASE}/v2/webhook/event/{entry['id']}/resend", params=KEY, timeout=30).raise_for_status()
        if not page["hasNextPage"]:
            break
        offset += 100

pendingRuns, processed, dispatched, jobs, erp and alertSupervisor stand for your own storage, queue, ERP client and paging. processed and dispatched only need an insert and a lookup by id.

Production hardening

Always declare weight and volume, even when "small"

The most common production bug in capacitated operations is treating weight and volume as optional. A stop without weight defaults to 0, and 0 fits anywhere, so the optimizer is free to put 50 of them on the smallest van. On execution day the driver runs out of room and turns around.

Make the import job fail closed: if the source order doesn't carry weight and volume, raise an error rather than push the stop with zeros.

if (order.weightKg == null || order.volumeM3 == null) {
  throw new Error(
    `order ${order.id} missing weight/volume: refuse to push to a capacitated plan`,
  );
}

Same logic for requires: a frozen-foods order pushed without requires: ["frozen"] will land on an ambient truck and arrive thawed.

Pre-flight before optimize

An infeasible plan doesn't fail at the POST: optimize/async returns at once. The run then places what it can and ends in optimization.succeeded with some stops left without a route, or ends in optimization.failed. Neither tells you which constraint was the problem.

So check aggregate supply against aggregate demand on your side first. optimizePlan above runs preflightCapacityCheck and, when the plan can't fit, pages the supervisor with the overage in kg, m³ and skill names instead of starting a run. That catches most infeasible plans before the optimizer sees them, with information the supervisor can act on.

Note: pre-flight is necessary but not sufficient. The aggregate supply-vs-demand check passes even when per-time-window capacity is broken (e.g. all stops want service between 10:00 and 12:00 but only two trucks are available in that window). The optimizer is the only check that catches geometry + capacity interactions.

Cold chain: model the chain, not just the truck

A frozen-foods route has additional patterns the basic requires: ["frozen"] doesn't enforce:

  1. Time-temperature ceilings. A frozen item out of the cold chamber for more than N minutes is no longer frozen. Routal doesn't enforce this, but you can keep route duration bounded by setting max_time on the vehicle, indirectly capping how long any single stop can stretch.
  2. Pre-cooling and post-cooling time. The truck takes 20 minutes at the start of the day to chill down. Model it as the first stop of the route or by setting the driver's time_window to start 20 minutes after their actual depot arrival.
  3. Chamber-by-chamber capacity. A frozen truck typically has a frozen chamber AND a fridge chamber AND ambient space. The single max_volume covers all of them. If you need per-chamber capacity, split into multiple "virtual" vehicles in Routal, one per chamber. chain_id is not the right tool for this.

If your cold chain requirements need stronger guarantees than requires gives you, talk to support: there are options that aren't part of the public REST surface today.

Oversized loads: when volume isn't enough

max_volume is total m³. It doesn't model shape: a 2m³ mattress won't fit in a van with 2m³ of remaining capacity if the remaining capacity is fragmented or short. Two patterns to compensate:

  • Use requires: ["oversized"] on the stop and provides: ["oversized"] only on vehicles that can geometrically take the item. The match becomes yes/no, not "do you have enough m³ left".
  • Constrain to one oversized stop per route. Set max_services: 1 on a vehicle dedicated to a single oversized delivery. Crude but effective when the geometry truly demands it.

Mixed fleets: explicit provides saves you

A fleet of 20 ambient trucks + 3 frozen trucks + 2 ADR-class-3 trucks looks ambiguous to the optimizer until you set provides correctly:

// ambient trucks
{ "provides": ["ambient"] }

// frozen trucks (also carry ambient)
{ "provides": ["ambient", "refrigerated", "frozen"] }

// ADR-class-3 trucks (specialized, only ADR cargo)
{ "provides": ["ambient", "adr-class-3"] }

A stop with requires: ["frozen"] only matches the 3 frozen trucks. A stop with requires: ["adr-class-3"] only matches the 2 ADR trucks. A stop with no requires matches every truck.

Don't over-engineer it: skills you never require on a stop are harmless on the vehicle side. Keep the catalog focused on what actually differentiates your operation.

When stops come back without a route anyway

Despite the pre-flight, a run may still leave stops without a route (reportLeftovers pages you with their weight, volume and requires) or end in optimization.failed. Common causes:

  • A stop's time window is shorter than the minimum service + travel time from any vehicle's depot. Pre-flight misses this because it doesn't compute travel.
  • All frozen capacity is full by 12:00 but stops at 16:00 also require frozen: single-chamber-day capacity is exhausted even though aggregate supply matches aggregate demand.
  • A specific requires skill is provided by only one vehicle, and that vehicle's time window doesn't overlap with all the stops that need it.

Recovery hierarchy:

  1. Page the supervisor with the diagnostic (which stops, which constraints). Don't auto-relax.
  2. Add a vehicle for the day from a backup pool, or borrow capacity from a sister depot.
  3. Reschedule overflow stops to the next day's plan (POST /v2/stop/move). They are still pending, so moving is safe.
  4. Renegotiate with the customer. Windows that systematically can't be met aren't customer service, they're operational debt.

The routes that fit are already dispatched, and the dispatched set keeps a later run from emailing those drivers again. On optimization.failed the plan keeps the routes it had: dispatch nothing until a run succeeds. Give every pending run a timeout too, say 30 minutes: a run canceled from the planner sends neither event.

Reconciling stop.reported and route.finished

stop.reported fires once per report, and data is the stop with all its reports. The newest one is the last. Map its type into your source system:

Latest report.typeStop statusSource-system action
service_report_completedcompletedMark the order delivered, attach signature + photo URLs.
service_report_attemptedpendingMark delivery failed with the cancel_reason. The driver may try again, so wait for the next report or route.finished.
service_report_canceledcanceledMark the order canceled.

route.finished carries the route with its stops. A stop still incomplete there is the one to reschedule; check that every other stop already has a final state in your system.

Authenticate the webhook handler with a URL token, drop duplicates by the envelope id, and answer 2xx within 10 seconds. Timeouts and 5xx are retried 1, 5 and 30 minutes later; Routal disables the webhook after 50 lost events in a row. See Webhooks → Retries.

Missed events: replay from the delivery log

Some deliveries get lost anyway: an ERP outage longer than the retry window, a bug in the handler. The nightly replayFailedDeliveries job above reads yesterday's failed attempts from GET /v2/webhook/{id}/events?status=error, skips the ones your processed table already has (a later retry got through) and resends the rest. A resent payload keeps its id, so running the job twice is harmless. See Webhooks → Delivery log.

Observability: the metrics that matter

MetricWhat it tells you
capacitated.fleet_utilization{dimension}weight / volume / services: average % of capacity used per route. >85% is great. >100% means you're forecasting wrong. <50% is missed efficiency.
capacitated.demand_supply_ratio{dimension}Aggregate stop demand / aggregate fleet supply for the day. ≥1.0 means you can't ship without overflow.
capacitated.unmatched_skill_total{skill}Times a requires skill had no provides match. Spike = vehicle was sick or you onboarded a new product type and forgot to update the fleet.
capacitated.infeasible_run_rate% of your runs that ended in optimization.failed or left stops without a route. Sustained > 5% is a routing problem, not a one-off.
capacitated.overweight_alerts_totalDrivers reporting their truck was over capacity at dispatch time. Should be zero. If not, your weight data upstream is wrong.
capacitated.webhook_replays_totalDeliveries the nightly job had to resend. Above zero most days = the receiver is dropping events.

Tag every metric by depot (if multi-depot) and by skill so the dispatcher can break down "frozen capacity utilization" separately from "ambient utilization".

Common errors

message_idCauseWhat to do
highway.optimization.error.no_result_foundDemand exceeds supply on at least one dimension (weight, volume, skill, or time window).Run pre-flight first. When it still fires, page the supervisor with the diagnostic; don't auto-relax.
highway.optimization.error.sync_optimization_already_progressAnother optimization is still running for the same plan.Wait for its optimization.succeeded or optimization.failed webhook. Do not retry.
highway.webhook.error.invalid_urlThe webhook url is not public: localhost, a private IP, an internal host, or credentials in the URL.Use a public HTTPS URL; a tunnel such as ngrok for local development.
highway.webhook.error.send_testPOST /v2/webhook/{id}/test got no 2xx from your endpoint within 10 seconds.Fix the endpoint before the first real event: check the token, the route and the response time.
highway.geocoding.error.wrong_lat_lngA stop's location.lat / lng is out of the valid range.Validate coords upstream. Refuse to push a stop with lat: 0, lng: 0 or values outside [-90, 90] / [-180, 180].
highway.stop.error.custom_fields_invalidA stop sent custom fields that aren't defined in the project.Update the project's custom-field schema, or fix the payload.
400 Bad Request (no message_id) on weight / volume validationNegative number, NaN, or value out of the schema's allowed range.Validate upstream. Treat null as "missing" → either default to 0 (and explicitly accept the risk) or refuse.
highway.optimization.error.too_much_requestsOptimizer rate-limited the request. Heavy capacitated optimizations are more compute-intensive.Back off 60–90 s and retry. If persistent on large fleets, talk to support about dedicated optimizer capacity.

Next steps

  • Nightly batch for B2B distribution: the daily-plan scaffolding this recipe inherits.
  • Field service with appointments: when capacity (parts in the van) and skills (technician certifications) both matter, combine this recipe's vehicle setup with that one's stop shape.
  • Package tracking is orthogonal to capacity: weight / volume feed the optimizer, while packages track individual parcels through pending → picked → delivered. Use both when each box matters.
  • Webhooks: the full cycle, event catalog, retries, delivery log and authentication patterns.