Nightly batch + live dispatch
Most of the work is the nightly batch, but new orders keep arriving during operations and have to be slotted into routes that already left the depot. This recipe covers the architectural decision of where to slot, the three optimizer strategies that are safe with drivers already on the road, the webhook cycle that dispatches and updates your OMS after every optimization run, and the operational patterns that keep dispatcher panic to a minimum.
Who this is for
You run an operation where the majority of orders close the night before (the nightly batch B2B pattern is your default), but new orders keep landing during the day and you can't tell the customer "wait until tomorrow":
- An e-commerce platform with a same-day SLA on a small fraction of orders.
- A meal-box delivery service taking late additions through the morning.
- A B2B distributor whose top customers can phone in an emergency order at 10am.
- A pharmacy distribution network with stat-of-care orders the same day.
You are not a 100% on-demand operation (that's a different recipe entirely, closer to a dispatch engine than a planner). You have a structured nightly batch and a tail of incremental orders during execution. The incremental tail has to be slotted into routes that already left the depot, without disrupting drivers who have a clipboard with their morning's sequence.
If that sounds like your operation, this recipe walks you through the three choices you have to make for every late order: which driver, when to re-optimize, and how to notify them.
What the rhythm looks like
Day -1 Day 0 (execution)
───────────────────────────────────── ─────────────────────────────────────
18:00 Order cutoff for nightly batch 06:00 Drivers open the app
→ /v2/plan + bulk /v2/stops → routes flip to in_transit
→ /v2/plan/{id}/optimize/async → plan flips to in_progress
18:02 ⚡ optimization.succeeded 09:30 ⚡ NEW ORDER arrives
(nightly run) 1. POST /v2/stops to active plan
→ dispatch every route 2. Slot it: re-sequence one route,
(driver gets a magic-link or optimize/async with
email) keep_current_assignment=true
09:31 ⚡ optimization.succeeded
(keep_current_assignment: true)
→ new ETAs to the OMS
→ dispatch only routes that
had no stops before
11:15 ⚡ Late order while a run is
still pending: queued, that
run's webhook starts the next
13:45 ⚡ stop.created from the driver
app → imported into the OMS
18:00 Last route finishes
⚡ route.finished
→ plan flips to finished
22:00 ⚡ Replay failed webhook deliveriesThe integration gets three responsibilities on the execution day:
- Push late orders into the active plan as soon as they arrive.
- Tell the driver about the new stop without breaking what they're already doing.
- React to webhooks:
optimization.succeededafter every run, nightly or live;stop.createdfor stops someone else added;stop.reportedandroute.finishedfor outcomes.
This recipe assumes the nightly batch is already running. If it isn't yet, start with Nightly batch for B2B distribution and come back here.
The three injection strategies
Picking the right one depends on how disruptive you want a late order to be.
| Strategy | What it does | When to use |
|---|---|---|
| Naive append | Add stop to a manually-picked route. Driver sees it at the bottom of their queue on next refresh. | Cheap. Use when the new stop is "whenever you can fit it" and the driver chooses the moment. |
| Per-route re-sequence | Add stop to a manually-picked route, then POST /v2/route/{route_id}/optimize. Routal re-sequences only this driver's stops, keeping the assigned vehicle fixed. A stop that no longer fits stays on the route, moved to the end and flagged with optimization_warning. | Most common. The driver's morning is preserved but the new stop lands in the right spot of the sequence. |
| Conservative plan re-balance | Add stop(s) to the plan, then POST /v2/plan/{id}/optimize/async?keep_current_assignment=true. Routal keeps every already-assigned stop where it is and only assigns the new stops to whichever driver minimizes cost. The result arrives as an optimization.succeeded webhook. | Use when you don't want to pick the driver yourself and there's no in-flight driver context to disrupt, typically just before drivers actually arrive at their first stop. |
Never use POST /v2/plan/{id}/optimize/async with keep_current_assignment=false
once any route has flipped to in_transit. Routal will happily reshuffle
stops between drivers, and the driver who already started their morning will
have stops mysteriously disappear from their queue.
Production code
The code below runs both strategies on top of one webhook worker:
injectLateOrderis the per-route re-sequence, the most common one.POST /v2/route/{id}/optimizeanswers with the new sequence, so it needs no webhook.pickBestRouteranks routes by remaining capacity; replace it with your own heuristic if you have driver-position data.injectLateOrdersis the plan-level re-balance. It goes throughstartRun, which the nightly job uses too (callstartRun(planId, 'nightly')where the B2B recipe starts its optimization).handleRoutalEventdispatches and updates the OMS whenoptimization.succeededarrives, for the nightly run and every live one. Use it instead of the B2B worker.
# (0) Once, on deploy: register the webhook. Run
# GET /v2/webhooks?project_id=YOUR_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=YOUR_PROJECT_ID" \
-H 'Content-Type: application/json' \
-d '{
"url": "https://oms.example.com/webhooks/routal?token=LONG_RANDOM_TOKEN",
"enabled_events": [
"routal.optimizer.2.optimization.succeeded",
"routal.optimizer.2.optimization.failed",
"routal.planner.2.stop.created",
"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.created" }'
# Late order arrives at 09:30. The current execution day's plan_id is in your
# cache (set by the nightly batch).
PLAN_ID="..." # active plan, status=in_progress
ROUTE_ID="..." # driver you picked (see TS/Python for picking logic)
# (1) Add the new stop to the active plan. external_id is the late order's ID
# from your source system, which makes the add retry-safe.
curl -X POST "https://api.routal.com/v2/stops?private_key=YOUR_KEY&plan_id=${PLAN_ID}&project_id=YOUR_PROJECT_ID" \
-H 'Content-Type: application/json' \
-d '[
{
"external_id": "ORDER-9501",
"label": "Acme Late Order",
"location": { "lat": 41.22, "lng": 2.07, "address": "456 Industrial Park" },
"duration": 480,
"time_windows": [[36000, 64800]],
"weight": 8,
"volume": 0.1
}
]'
# → returns the created stop. Save the stop_id.
# (2) The stop landed on the plan but isn't yet on any route. Two options:
#
# 2a. Assign manually to the route you picked, then re-sequence that route.
# The list replaces the route's stops: a stop you leave out is unassigned.
curl -X PUT "https://api.routal.com/v2/route/${ROUTE_ID}/stops?private_key=YOUR_KEY" \
-H 'Content-Type: application/json' \
-d '{
"stops": [
"EXISTING_STOP_1",
"EXISTING_STOP_2",
"NEW_STOP_ID",
"EXISTING_STOP_3"
]
}'
# Then ask Routal to find the best sequence for this route. The response's
# route.stops is the new order; a stop that doesn't fit stays at the end with
# optimization_warning: true.
curl -X POST "https://api.routal.com/v2/route/${ROUTE_ID}/optimize?private_key=YOUR_KEY"
# 2b. Let Routal pick the best driver: conservative re-balance. Returns at
# once. Don't send it while a run of yours is still pending on this plan:
# wait for that run's webhook.
curl -X POST "https://api.routal.com/v2/plan/${PLAN_ID}/optimize/async?private_key=YOUR_KEY&keep_current_assignment=true"
# (3) On optimization.succeeded for PLAN_ID (it fires after the nightly run and
# after every live one): read the routes and dispatch only those you never
# dispatched. Dispatch re-sends the driver email.
curl "https://api.routal.com/v2/plan/${PLAN_ID}/routes?private_key=YOUR_KEY"
curl -X POST "https://api.routal.com/v2/route/NEW_ROUTE_ID/dispatch?private_key=YOUR_KEY"
# (4) Nightly: list the day's failed deliveries and resend the ones your OMS
# 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://oms.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.created',
'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.created' },
});
if (testErr) throw testErr;
return hook!.id;
}
// ── (1) Optimization runs: one per plan at a time ────────────────────────
type RunKind = 'nightly' | 'live';
/**
* Start a run and return: the optimization.succeeded webhook picks up.
* 'nightly' rebuilds every route; 'live' passes keep_current_assignment=true
* so drivers on the road keep their stops.
*/
export async function startRun(planId: string, kind: RunKind) {
// Insert-if-absent: false while a run of yours is pending on this plan.
// Calling optimize now would fail with sync_optimization_already_progress;
// instead, the pending run's webhook starts the next one.
if (!(await pendingRuns.add(planId, kind))) {
await rerunQueued.add(planId);
return;
}
const { error } = await routal.POST('/v2/plan/{id}/optimize/async', {
params: { path: { id: planId }, query: { ...key, keep_current_assignment: kind === 'live' } },
});
if (error) {
await pendingRuns.remove(planId);
throw error; // already_progress here means a run started from the planner
}
}
// ── (2) One late order: per-route re-sequence ────────────────────────────
type LateOrder = {
id: string;
customer: string;
lat: number;
lng: number;
serviceMinutes: number;
windowFromSec: number;
windowToSec: number;
weightKg?: number;
volumeM3?: number;
requires?: string[]; // skills the order needs
};
type RouteWithStops = { id: string; stops?: Array<{ id: string; optimization_warning?: boolean }> };
/**
* Inject a late order into the active plan using the
* per-route re-sequence strategy.
*
* Steps:
* 1. Resolve the active plan for today.
* 2. Pick the best route (driver) for this order.
* 3. Add the stop to the plan.
* 4. Insert it into the chosen route's stop list.
* 5. Ask Routal to re-sequence that route.
* 6. Return the new stop position and whether it fits.
*/
export async function injectLateOrder(order: LateOrder) {
const planId = await resolveActivePlanForToday();
if (await pendingRuns.has(planId)) {
// A plan-level run of yours is going: leave the routes alone. Its
// webhook starts a follow-up live run that places this stop.
const stopId = await addStopToPlan(planId, order);
await rerunQueued.add(planId);
return { planId, stopId, queued: true as const };
}
const route = await pickBestRoute(planId, order);
const stopId = await addStopToPlan(planId, order);
await appendStopToRoute(route.id, route.currentStopIds, stopId);
const reoptimized = await reSequenceRoute(route.id);
await dispatchNewRoutes([reoptimized]); // a spare van that just got its first stop
const stops = reoptimized.stops ?? [];
const sequence = stops.findIndex((s) => s.id === stopId);
return {
planId,
routeId: route.id,
stopId,
sequence,
// A stop the route can't fit stays at its end, flagged with optimization_warning.
fits: sequence !== -1 && !stops[sequence].optimization_warning,
};
}
async function resolveActivePlanForToday(): Promise<string> {
const today = new Date().toISOString().slice(0, 10);
const { data, error } = await routal.GET('/v2/plans', {
params: { query: { ...key, project_id: PROJECT_ID, limit: 5, sort: 'created_at:desc' } },
});
if (error) throw error;
const active = data!.docs?.find(
(p) =>
p.execution_date?.startsWith(today) &&
(p.status === 'in_progress' || p.status === 'planning'),
);
if (!active) throw new Error(`no active plan for ${today}`);
return active.id!;
}
type RouteSummary = { id: string; currentStopIds: string[]; remainingCapacity: number };
async function pickBestRoute(planId: string, order: LateOrder): Promise<RouteSummary> {
// Naive heuristic: pick the route with the most remaining max_volume that
// also covers the order's `requires` skills. Replace with your own logic
// when you have driver-position data; typically lowest detour cost wins.
const { data: routes, error } = await routal.GET('/v2/plan/{id}/routes', {
params: { path: { id: planId }, query: key },
});
if (error) throw error;
const candidates = (routes ?? [])
.filter((r) => r.status !== 'finished')
.map((r) => ({
id: r.id!,
currentStopIds: (r.stops ?? []).map((s: { id?: string }) => s.id!).filter(Boolean),
// A route has max_volume but no load field: sum the volume of its stops.
remainingCapacity:
(r.max_volume ?? 0) - (r.stops ?? []).reduce((sum: number, s: { volume?: number }) => sum + (s.volume ?? 0), 0),
provides: r.provides ?? [],
}));
const matching = candidates.filter((r) =>
(order.requires ?? []).every((skill) => r.provides.includes(skill)),
);
if (matching.length === 0) throw new Error('no route can serve this order today');
matching.sort((a, b) => b.remainingCapacity - a.remainingCapacity);
return matching[0];
}
async function addStopToPlan(planId: string, order: LateOrder): Promise<string> {
const { data, error } = await routal.POST('/v2/stops', {
params: { query: { ...key, plan_id: planId, project_id: PROJECT_ID } },
body: [
{
external_id: order.id,
label: order.customer,
location: { lat: order.lat, lng: order.lng },
duration: order.serviceMinutes * 60,
time_windows: [[order.windowFromSec, order.windowToSec]],
weight: order.weightKg,
volume: order.volumeM3,
requires: order.requires,
},
] as never,
});
if (error) throw error;
return (data as { id: string }[])[0].id;
}
async function appendStopToRoute(
routeId: string,
currentStopIds: string[],
newStopId: string,
): Promise<void> {
// The list replaces the route's stops: a stop you leave out is unassigned.
const { error } = await routal.PUT('/v2/route/{id}/stops', {
params: { path: { id: routeId }, query: key },
body: { stops: [...currentStopIds, newStopId] },
});
if (error) throw error;
}
async function reSequenceRoute(routeId: string): Promise<RouteWithStops> {
const { data, error } = await routal.POST('/v2/route/{id}/optimize', {
params: { path: { id: routeId }, query: key },
});
if (error) throw error;
return (data as { route: RouteWithStops }).route; // the route with its new sequence
}
// ── (3) Several late orders: plan-level re-balance ───────────────────────
/** Add them all, then one live run slots them. Queued if a run of yours is pending. */
export async function injectLateOrders(orders: LateOrder[]) {
const planId = await resolveActivePlanForToday();
for (const order of orders) await addStopToPlan(planId, order);
await startRun(planId, 'live');
}
// ── (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;
// Fires after every run, planner runs included: only act on yours.
if (!(await pendingRuns.remove(planId))) break;
// data.keep_current_assignment is false for the nightly run and true for
// your live ones. The same code serves both: dispatch skips routes that
// were already dispatched, so only new routes get the driver email.
await dispatchNewRoutes(await getRoutes(planId));
await syncEtas(planId);
// Late orders that arrived while this run was going: one follow-up run.
if (await rerunQueued.remove(planId)) await startRun(planId, 'live');
break;
}
case 'routal.optimizer.2.optimization.failed': {
// No plan id today. keep_current_assignment tells a live run from the nightly one.
const kind: RunKind = event.data.keep_current_assignment ? 'live' : 'nightly';
const suspects = (await pendingRuns.list()).filter((r) => r.kind === kind);
await alertDispatcher('Routal optimization failed', { error: event.data.error, suspects });
break;
}
case 'routal.planner.2.stop.created':
// Your own pushes fire this too. A stop the OMS doesn't know was added in
// the planner or the driver app: import it so it doesn't go unseen.
if (!(await oms.hasOrder(event.data.external_id))) await oms.importStop(event.data);
break;
case 'routal.planner.2.stop.reported':
await updateOrder(event.data);
break;
case 'routal.drivers.2.route.finished':
await reconcileRoute(event.data); // undelivered stops get a new stop tomorrow, never a move
break;
}
await processed.add(event.id!);
}
async function getRoutes(planId: string): Promise<RouteWithStops[]> {
const { data, error } = await routal.GET('/v2/plan/{id}/routes', {
params: { path: { id: planId }, query: key },
});
if (error) throw error;
return (data as RouteWithStops[]) ?? [];
}
/** Dispatch re-sends the driver email: only routes that never had it, now with stops. */
async function dispatchNewRoutes(routes: RouteWithStops[]) {
for (const route of routes) {
if (!route.stops?.length || (await dispatched.has(route.id))) continue;
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);
}
}
/** A live run re-sequences routes, so every pending ETA can move. */
async function syncEtas(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; status: string; planned_arrival_time?: number; tracking_url?: string };
const pending = ((data as PlanStop[]) ?? []).filter((s) => s.status === 'pending');
await oms.updateEtas(
pending
.filter((s) => s.route_id)
.map((s) => ({ orderId: s.external_id, routeId: s.route_id, plannedArrival: s.planned_arrival_time, trackingUrl: s.tracking_url })),
);
const unplaced = pending.filter((s) => !s.route_id);
if (unplaced.length) await oms.flagUnplaced(unplaced.map((s) => s.external_id)); // see "doesn't fit" below
}
const OMS_STATE = {
service_report_completed: 'delivered',
service_report_attempted: 'delivery_failed',
service_report_canceled: 'canceled',
} as const;
async function updateOrder(stop: any) {
const report = stop.reports?.at(-1); // data is the stop; its latest report is the new one
if (!report) return;
await oms.updateOrder(stop.external_id, {
state: OMS_STATE[report.type as keyof typeof OMS_STATE],
signatureUrl: report.signature?.url,
photoUrls: (report.images ?? []).map((i: { url: string }) => i.url),
cancelReason: report.cancel_reason,
});
}
// ── 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, requests
from datetime import date
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://oms.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.created",
"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.created"},
timeout=30,
).raise_for_status()
return hook_id
# ── (1) Optimization runs: one per plan at a time ────────────────────────
def start_run(plan_id: str, kind: str) -> None:
"""
Start a run and return: the optimization.succeeded webhook picks up.
"nightly" rebuilds every route; "live" passes keep_current_assignment=true
so drivers on the road keep their stops.
"""
# Insert-if-absent: False while a run of yours is pending on this plan.
# Calling optimize now would fail with sync_optimization_already_progress;
# instead, the pending run's webhook starts the next one.
if not pending_runs.add(plan_id, kind):
rerun_queued.add(plan_id)
return
resp = requests.post(
f"{BASE}/v2/plan/{plan_id}/optimize/async",
params={**KEY, "keep_current_assignment": "true" if kind == "live" else "false"},
timeout=60,
)
if not resp.ok:
pending_runs.remove(plan_id)
resp.raise_for_status() # already_progress here means a run started from the planner
# ── (2) One late order: per-route re-sequence ────────────────────────────
def inject_late_order(order: dict) -> dict:
"""
Inject a late order into the active plan using the per-route
re-sequence strategy.
"""
plan_id = resolve_active_plan_for_today()
if pending_runs.has(plan_id):
# A plan-level run of yours is going: leave the routes alone. Its
# webhook starts a follow-up live run that places this stop.
stop_id = add_stop_to_plan(plan_id, order)
rerun_queued.add(plan_id)
return {"plan_id": plan_id, "stop_id": stop_id, "queued": True}
route = pick_best_route(plan_id, order)
stop_id = add_stop_to_plan(plan_id, order)
append_stop_to_route(route["id"], route["currentStopIds"], stop_id)
reoptimized = re_sequence_route(route["id"])
dispatch_new_routes([reoptimized]) # a spare van that just got its first stop
stops = reoptimized.get("stops") or []
placed = next((s for s in stops if s["id"] == stop_id), None)
return {
"plan_id": plan_id,
"route_id": route["id"],
"stop_id": stop_id,
"sequence": stops.index(placed) if placed else None,
# A stop the route can't fit stays at its end, flagged with optimization_warning.
"fits": placed is not None and not placed.get("optimization_warning"),
}
def resolve_active_plan_for_today() -> str:
today = date.today().isoformat()
resp = requests.get(
f"{BASE}/v2/plans",
params={**KEY, "project_id": PROJECT_ID, "limit": 5, "sort": "created_at:desc"},
timeout=30,
)
resp.raise_for_status()
for plan in resp.json().get("docs", []):
if (plan.get("execution_date") or "").startswith(today) and \
plan.get("status") in ("in_progress", "planning"):
return plan["id"]
raise RuntimeError(f"no active plan for {today}")
def pick_best_route(plan_id: str, order: dict) -> dict:
candidates = []
for r in get_routes(plan_id):
if r.get("status") == "finished":
continue
stops = r.get("stops") or []
candidates.append({
"id": r["id"],
"currentStopIds": [s["id"] for s in stops if s.get("id")],
# A route has max_volume but no load field: sum the volume of its stops.
"remainingCapacity": (r.get("max_volume") or 0) - sum(s.get("volume") or 0 for s in stops),
"provides": r.get("provides") or [],
})
requires = order.get("requires") or []
matching = [r for r in candidates if all(s in r["provides"] for s in requires)]
if not matching:
raise RuntimeError("no route can serve this order today")
matching.sort(key=lambda r: r["remainingCapacity"], reverse=True)
return matching[0]
def add_stop_to_plan(plan_id: str, order: dict) -> str:
payload = [{
"external_id": order["id"],
"label": order["customer"],
"location": {"lat": order["lat"], "lng": order["lng"]},
"duration": order["service_minutes"] * 60,
"time_windows": [[order["window_from_sec"], order["window_to_sec"]]],
"weight": order.get("weight_kg"),
"volume": order.get("volume_m3"),
"requires": order.get("requires"),
}]
resp = requests.post(
f"{BASE}/v2/stops",
params={**KEY, "plan_id": plan_id, "project_id": PROJECT_ID},
json=payload,
timeout=30,
)
resp.raise_for_status()
return resp.json()[0]["id"]
def append_stop_to_route(route_id: str, current_stop_ids: list[str], new_stop_id: str) -> None:
# The list replaces the route's stops: a stop you leave out is unassigned.
resp = requests.put(
f"{BASE}/v2/route/{route_id}/stops",
params=KEY,
json={"stops": current_stop_ids + [new_stop_id]},
timeout=30,
)
resp.raise_for_status()
def re_sequence_route(route_id: str) -> dict:
resp = requests.post(f"{BASE}/v2/route/{route_id}/optimize", params=KEY, timeout=60)
resp.raise_for_status()
return resp.json()["route"] # the route with its new sequence
# ── (3) Several late orders: plan-level re-balance ───────────────────────
def inject_late_orders(orders: list[dict]) -> None:
"""Add them all, then one live run slots them. Queued if a run of yours is pending."""
plan_id = resolve_active_plan_for_today()
for order in orders:
add_stop_to_plan(plan_id, order)
start_run(plan_id, "live")
# ── (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
OMS_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"]
# Fires after every run, planner runs included: only act on yours.
if pending_runs.remove(plan_id):
# keep_current_assignment is False for the nightly run and True for
# your live ones. Dispatch skips routes already dispatched, so the
# same code serves both.
dispatch_new_routes(get_routes(plan_id))
sync_etas(plan_id)
# Late orders that arrived while this run was going: one follow-up run.
if rerun_queued.remove(plan_id):
start_run(plan_id, "live")
elif kind == "routal.optimizer.2.optimization.failed":
# No plan id today. keep_current_assignment tells a live run from the nightly one.
run_kind = "live" if data.get("keep_current_assignment") else "nightly"
suspects = [r for r in pending_runs.list() if r["kind"] == run_kind]
alert_dispatcher("Routal optimization failed", error=data.get("error"), suspects=suspects)
elif kind == "routal.planner.2.stop.created":
# Your own pushes fire this too. A stop the OMS doesn't know was added in
# the planner or the driver app: import it so it doesn't go unseen.
if not oms.has_order(data.get("external_id")):
oms.import_stop(data)
elif kind == "routal.planner.2.stop.reported":
update_order(data)
elif kind == "routal.drivers.2.route.finished":
reconcile_route(data) # undelivered stops get a new stop tomorrow, never a move
processed.add(event["id"])
def get_routes(plan_id: str) -> list[dict]:
resp = requests.get(f"{BASE}/v2/plan/{plan_id}/routes", params=KEY, timeout=30)
resp.raise_for_status()
return resp.json()
def dispatch_new_routes(routes: list[dict]) -> None:
"""Dispatch re-sends the driver email: only routes that never had it, now with stops."""
for route in routes:
if not route.get("stops") or dispatched.has(route["id"]):
continue
requests.post(f"{BASE}/v2/route/{route['id']}/dispatch", params=KEY, timeout=30).raise_for_status()
dispatched.add(route["id"])
def sync_etas(plan_id: str) -> None:
"""A live run re-sequences routes, so every pending ETA can move."""
stops = requests.get(f"{BASE}/v2/plan/{plan_id}/stops", params=KEY, timeout=30).json()
pending = [s for s in stops if s.get("status") == "pending"]
oms.update_etas([
{"order_id": s.get("external_id"), "route_id": s["route_id"],
"planned_arrival": s.get("planned_arrival_time"), "tracking_url": s.get("tracking_url")}
for s in pending if s.get("route_id")
])
unplaced = [s.get("external_id") for s in pending if not s.get("route_id")]
if unplaced:
oms.flag_unplaced(unplaced) # see "doesn't fit" below
def update_order(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
oms.update_order(
stop["external_id"],
state=OMS_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"),
)
# ── 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 += 100pendingRuns, rerunQueued, processed, dispatched, jobs and oms stand
for your own storage, queue and OMS client. pendingRuns.add is an
insert-if-absent that returns false when the plan is already there, and keeps
the run's kind; the others only need an insert, a lookup and a remove by id.
Production hardening
Where to slot: picking the driver matters
The naive heuristic in the code above (most remaining capacity, skills match) is the right starting point. Three improvements your platform team will want before scaling:
- Use driver positions. The
routal.drivers.2.route.startedwebhook tells you a route is now in transit (add it toEVENTSif you use it). After that, the public REST API does not stream driver coordinates today, but you can read the route's progress (route.stops[].status) to know which stops have been visited, and infer roughly where the driver is. If your business needs live coordinates, talk to support: there are options for real-time tracking that are not part of the public REST surface. - Account for already-committed time. A driver whose remaining route ends
at 14:30 can't take a 16:00 delivery. Filter candidates by overlap between
the route's remaining
time_windowand the late order'stime_windows. - Detour cost, not Euclidean distance. If two routes have similar
capacity but route A passes 200m from the new stop while route B passes
3km away, route A wins regardless of who has more headroom. Routal's
per-route optimizer computes detour cost during
POST /v2/route/{id}/optimize. Call it on candidate routes with the stop temporarily attached and compare the resulting durations.
When NOT to re-optimize at all
Sometimes the right move is to append and let the driver decide:
- The order is "whenever you can fit it" without a hard time window.
- The driver is using their judgment for sequencing today (e.g. construction delays, customer was just on the phone).
- The integration is offering a hint, not enforcing it.
In those cases skip the POST /v2/route/{id}/optimize call: just
PUT /v2/route/{id}/stops to append the new stop ID at the end and stop
there. The driver app refreshes within a minute and the stop appears at the
bottom of their queue. They reorder it themselves on the device if they want
to.
When to use plan-level re-balance (keep_current_assignment=true)
Reach for it when multiple late orders arrive in a short window and you'd
rather let Routal pick the driver for each than write your own
pickBestRoute. injectLateOrders above adds them all to the plan, then
starts one live run:
for (const order of recentLateOrders) await addStopToPlan(planId, order);
await startRun(planId, 'live'); // keep_current_assignment=true; queued if a run of yours is pendingoptimize/async returns at once. When optimization.succeeded arrives the new
stops are on a route: drivers see them when their app refreshes, and the worker
sends the new ETAs to the OMS.
This is safe even when routes are in_transit. Existing assignments are kept;
only the new stops get assigned. Cheaper than running pickBestRoute + per-
route optimize once per order, but more disruptive than appending without
optimization, because Routal re-sequences any route that receives a new stop.
One run at a time, and optimization.succeeded after every run
A plan runs one optimization at a time; a second call fails with
highway.optimization.error.sync_optimization_already_progress. Late orders
don't wait for each other, so startRun checks pendingRuns first. While a run
of yours is pending it marks the plan in rerunQueued and returns: the stops are
already on the plan. When the pending run's optimization.succeeded arrives,
the worker starts one follow-up live run that places everything that came in
meanwhile. Ten late orders during one run cost one extra run, not ten failed
calls.
optimization.succeeded fires after every run: the nightly one, each live one,
and any run a dispatcher starts from the planner. data.keep_current_assignment
is true on your live runs, and data.live turns true once the plan has
routes in progress. The worker acts only on plans in pendingRuns. On each of
those runs it dispatches only routes that have stops and were never dispatched:
after the nightly run that's every route, during the day only a spare van that
just got its first stops.
optimization.failed carries no plan id today. The worker narrows the suspects
with data.keep_current_assignment and alerts. Give every pending run a
timeout too, say 30 minutes: a run canceled from the planner sends neither
event. Until the timeout releases the plan, late orders wait in rerunQueued
(on the plan, not yet on a route). When it fires, release the plan, alert, and
start the queued run. See
Webhooks → Optimization events.
Notifying the driver and the customer
POST /v2/route/{id}/dispatch re-sends the magic-link email to the driver,
which is not what you want during the day: the driver already has the
route open on their device. That's why dispatchNewRoutes skips every route in
dispatched and only emails a route that has stops for the first time.
The driver app auto-refreshes the stop list periodically; new stops appear without a redispatch. If you need an instant "you have a new stop" push, the driver app does not currently expose a public push API. Talk to support if this is a hard requirement for your operation.
For the customer, the new stop now has a phone and possibly an
email field. Routal sends communications via the customers app
(c.routal.com). syncEtas hands the OMS each stop's
route, planned arrival and tracking_url after every run, and
stop.reported tells it when the driver completes. See
Webhooks → Event catalog.
Stops you didn't create: stop.created
routal.planner.2.stop.created fires for every new stop: the ones your
integration pushes, the ones a dispatcher adds in the planner, and the ones a
driver adds from the driver app. Your own pushes are already confirmed by the
POST /v2/stops response, so the worker drops any stop whose external_id the
OMS already knows. The rest are news to the OMS: import them so they get an
order record, a customer notification and a place in the day's reconciliation.
Cap the daily injection rate
A live-dispatch integration that fires POST /v2/route/{id}/optimize once per
late order can add up. A worst case of 1 late order every 2 minutes from 09:00
to 17:00 = 240 optimizes/day per project, which is fine against the
2,000 req/min cap but doubles your optimization spend if Routal bills by
optimization volume.
Two patterns to soften the cost:
- Batch late orders in a 60-second window. Buffer arrivals, add them all
at once, then re-balance the plan once.
rerunQueuedalready folds the orders that arrive during a run into a single follow-up run. - Skip re-optimization for low-priority orders. Append them (see When NOT to re-optimize) and only re-optimize when the new stop's priority demands it.
What happens when the new stop doesn't fit
POST /v2/route/{id}/optimize keeps the vehicle fixed. When the route's time
window or capacity can't take the new stop, the stop stays on the route,
moved to the end and flagged with optimization_warning. injectLateOrder
returns fits: false in that case: check it before you promise the customer
anything.
With the plan-level re-balance, a late order that fits no route stays on the
plan without a route_id. syncEtas flags it after optimization.succeeded.
Recovery options:
- Try a different route via
pickBestRouteexcluding the one you just tried. Take the stop off the first route withPUT /v2/route/{id}/stops(leave it out of the list). - Fall back to
POST /v2/plan/{id}/optimize/async?keep_current_assignment=truethroughstartRunso Routal picks the best driver globally. Take the stop off its route first: the run keeps every assigned stop where it is. - Page the dispatcher. The new order may genuinely not be servable today and
needs to be moved to tomorrow's plan (
POST /v2/stop/movewith theplan_idset to tomorrow's plan).
Idempotency on the live add
The same external_id-based reconciliation pattern that's load-bearing in
every Routal integration applies here. Before calling addStopToPlan:
const existing = await findExistingExternalIds(planId, [order.id]);
if (existing.has(order.id)) {
// already pushed: fetch it and continue with the existing stop_id
const stop = await fetchStopByExternalId(planId, order.id);
return slotIntoRoute(stop.id, ...);
}If your source system retries the webhook that delivered the late order to your integration, this guard prevents two stops for the same order.
On the Routal side, drop duplicate deliveries by the envelope id, answer
2xx within 10 seconds, and authenticate with the URL token. 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
A deploy at the wrong minute or an OMS outage longer than the retry window
loses deliveries. For a live operation the costly ones are a lost
optimization.succeeded (a plan stuck in pendingRuns, late orders queued
behind it) and a lost stop.reported. The timeout above unblocks the first.
The nightly replayFailedDeliveries job catches the rest: it reads the day's
failed attempts from GET /v2/webhook/{id}/events?status=error, skips the ones
your processed table already has and resends the rest. A resent payload keeps
its id, so running it twice is harmless. See
Webhooks → Delivery log.
What changes when the plan flips to in_progress
A few operations behave slightly differently once any route in the plan has
gone in_transit:
POST /v2/plan/{id}/optimize/async(defaultkeep_current_assignment=false) is never what you want at this point. Routal will gladly reshuffle the driver's morning. Always passkeep_current_assignment=trueduring the day.POST /v2/route/{id}/optimizeis fine: vehicle assignment is fixed and only this route gets re-sequenced.DELETE /v2/route/{id}is rejected withhighway.route.error.lockedif the route was locked ahead of dispatch (a common pattern: lock routes at 06:00 just before dispatch to prevent accidents).POST /v2/stop/moveto tomorrow's plan is safe for stops still inpending. Never move stops that are alreadycompleted/incomplete/canceled: those represent a delivery attempt and moving them rewrites history.
Observability: the metrics that matter
| Metric | What it tells you |
|---|---|
routal.live_dispatch.late_orders_total{outcome} | Volume of late orders and how they were slotted (appended / re_sequenced / re_balanced / bounced_to_tomorrow). |
routal.live_dispatch.injection_latency_ms | P50 / P99 from "order arrives in our queue" to "stop is on a route". The dispatcher cares about this. |
routal.live_dispatch.optimize_route_calls_total | If this is anywhere near 1,000/day per project, batch your late orders. |
routal.live_dispatch.bounce_rate | Late orders that couldn't fit any route today. >5% means the nightly plan is too tight; the optimizer is at its constraint limit. |
routal.live_dispatch.webhook_replays_total | Deliveries the nightly job had to resend. Above zero most days = the receiver is dropping events. |
Log every injection with plan_id, route_id, stop_id, external_id,
strategy used, and the resulting sequence position. The dispatcher will ask.
Common errors
message_id | Cause | What to do |
|---|---|---|
highway.optimization.error.sync_optimization_already_progress | Another optimization is still running for the same plan, usually one started from the planner. | Don't retry. Wait for its optimization.succeeded or optimization.failed webhook. Your own runs never get here: startRun queues a follow-up run instead of calling optimize. |
highway.optimization.error.no_result_found | The new stop cannot be fitted on any active route. | Bounce to tomorrow's plan with POST /v2/stop/move, or page the dispatcher. |
highway.route.error.not_in_transit | An action required the route to be in transit but it isn't yet. | Rare in live dispatch: typically means the driver hasn't opened the app yet. Wait for routal.drivers.2.route.started. |
highway.stop.error.move_not_pending_stops | You tried POST /v2/stop/move on a stop that's already terminal. | Never move stops past pending. Create a new stop for any retry. |
highway.webhook.error.invalid_url | The 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_test | POST /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. |
Next steps
- Nightly batch for B2B distribution: the prerequisite for this recipe. If your nightly batch isn't running yet, start there.
- Webhooks: the full cycle, event catalog, retries, delivery log and authentication patterns.
- Idempotency: Pattern 1 (search-then-create) is the load-bearing guard for the live add.
- API Reference →
POST /v2/route/{id}/optimize: the single-route re-sequence endpoint, exact response shape.
