Last-mile e-commerce
B2C parcel delivery. Orders flow from your OMS or WMS into Routal throughout the day, the optimizer batches them into dense neighborhood routes, drivers execute with barcode-scan tasks, and customers get tracking links automatically. This recipe covers the full OMS→Routal→OMS loop, from registering the webhook to closing each order on stop.reported, and the high-density stop patterns specific to parcel logistics.
Who this is for
You run a B2C parcel operation delivering physical goods to end customers who placed the order online. Common shapes:
- A direct-to-consumer brand (apparel, beauty, home goods) shipping out of one or two fulfillment centers to households across a region.
- A marketplace fulfillment operation (3PL serving multiple Shopify / WooCommerce stores) consolidating outbound flow into the same daily fleet.
- A same-day or next-day urban delivery service (food retail, pharmacy e-commerce, beverage on-demand) where the customer expects an arrival window notification before the driver shows up.
- A post-checkout fulfillment layer for retail (click-and-collect's cousin, click-and-ship-from-store) where the order originates in the store POS and needs to be sequenced into a delivery route.
What makes you different from a B2B distributor:
- Every stop has a real human at the door who wants to know "when will the
driver be here?". The integration must populate
phoneandemailon every stop and rely on Routal's customers app at c.routal.com to send tracking links automatically. - Stops per route are high. 50-150 stops per van per day is normal for parcel; a B2B route is usually 8-25 stops.
- Time windows are softer. The customer accepts "between 9am and 9pm", but the integration still has to surface a real ETA when the driver gets close (handled by Routal, see Customer notifications).
- Address quality is variable. Customers type their own delivery
addresses; you'll geocode misses constantly. The integration must handle
highway.geocoding.error.wrong_lat_lnggracefully: flag the order for customer outreach instead of dropping it on the floor.
What the rhythm looks like
E-commerce flow is continuous push during the day, optimize at a cutoff and dispatch when Routal says the routes are ready, react to webhooks during execution:
Throughout the day Cutoff (e.g. 16:00) Execution day
────────────────────────────── ───────────────────── ──────────────────────────────
08:00 Orders arrive in OMS 16:00 ORDER BOOK CLOSES 05:00 Drivers open the app
(Shopify webhook, manual → routes flip in_transit
entry, store POS, etc.) 16:05 ⚡ Push job fires
1. Create tomorrow's plan 09:00 First deliveries land
2. Bulk-push stops (with → c.routal.com sends
phone + email) tracking link
3. Start optimize/async 10:00-19:00 Drivers complete
stops, scan barcodes,
16:07 ⚡ optimization. attach POD
succeeded webhook → stop.reported
4. Dispatch routes closes each order
(driver email + SMS)
5. Roll stops left 19:00 Last delivery
without a route to → route.finished
tomorrow → plan flips finished
22:00 Reconciliation job
replays failed webhook
deliveries, verifies all
stops closed in OMSTwo notes specific to last-mile e-commerce:
- Cutoff is your operational lever. Move it earlier and you ship the same day; move it later and you risk no-result-found because the optimizer can't fit all overflow on the available fleet.
- Customer notifications are NOT your responsibility once the stop has
phoneandemail. Routal's customers app sends the tracking link on dispatch and an ETA SMS when the driver gets close. Your integration just makes sure the contact fields are populated.
The integration shape
On deploy (once)
POST /v2/webhook (+ POST /v2/webhook/{id}/test) find-or-create on url
OMS / WMS (Shopify / Woo / Magento / custom)
│
│ (1) read pending orders, normalize address + contact
▼
[ orders: { external_id, address, phone, email, weight?, volume? } ]
│
│ (2) bulk-create as Routal stops in tomorrow's plan
▼
POST /v2/stops (idempotent on external_id)
│
│ (3) optimize once order book closes: returns at once
▼
POST /v2/plan/{id}/optimize/async
│
│ (4) webhook: optimization.succeeded (data.plan.id)
▼
GET /v2/plan/{id}/routes → POST /v2/route/{id}/dispatch (one call per route)
│ driver gets magic link, customer gets tracking link
│
│ (5) webhooks during execution
▼
route.started → driver is on the road
stop.reported → close order in OMS, attach POD
route.finished → reconcile day-of metrics
│
│ (6) nightly
▼
GET /v2/webhook/{id}/events?status=error → resend what you missedThe single biggest difference vs. nightly-batch B2B: every stop carries
phone + email, and Routal's customers app handles tracking outreach
automatically. You don't build a tracking page; you populate two fields.
Nothing in this loop polls. The cutoff job ends right after it starts the
optimization; the optimization.succeeded webhook picks up from there.
Production code
# (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.drivers.2.route.started",
"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) Ensure tomorrow's plan exists (idempotent on execution_date + label).
curl -X POST "https://api.routal.com/v2/plan?private_key=YOUR_KEY&project_id=YOUR_PROJECT_ID" \
-H 'Content-Type: application/json' \
-d '{
"label": "Daily 2026-05-22",
"execution_date": "2026-05-22"
}'
# (2) Bulk-push the day's orders. Each stop carries phone + email so the
# customers app at c.routal.com can send tracking links automatically.
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": "ORD-10042",
"label": "Alice Doe, 12 Carrer del Bruc",
"location": { "lat": 41.3955, "lng": 2.1734, "address": "Carrer del Bruc 12, 08010 Barcelona" },
"duration": 180,
"time_windows": [[32400, 75600]],
"phone": "+34600111222",
"email": "alice@example.com",
"weight": 1.4,
"tasks": [
{ "label": "Scan tracking barcode", "barcode": "1Z999AA10123456784" }
]
}
]'
# (3) Optimize. Returns at once: the routes are ready when the
# routal.optimizer.2.optimization.succeeded webhook arrives 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, then dispatch each one that
# has stops. The driver gets a magic-link email; the customer gets a
# tracking link from c.routal.com.
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"
# (5) Nightly: list yesterday'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.drivers.2.route.started',
'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) Push orders ────────────────────────────────────────────────────
type EcommerceOrder = {
id: string; // order number, becomes external_id
customerName: string;
addressLine: string;
lat: number;
lng: number;
phoneE164: string; // E.164 always; Routal validates
email: string;
trackingBarcode: string; // the label on the parcel; the driver scans it
weightKg: number;
windowFromSec: number; // e.g. 32400 = 9:00
windowToSec: number; // e.g. 75600 = 21:00
};
/** Idempotent: re-running with the same orders is a no-op. */
export async function pushDailyOrders(planId: string, orders: EcommerceOrder[]) {
if (orders.length === 0) return { created: 0 };
// De-dup against what's already in the plan (cron retries, deploy windows).
const existing = new Set((await listStops(planId)).map((s) => s.external_id ?? ''));
const newOnes = orders.filter((o) => !existing.has(o.id));
if (newOnes.length === 0) return { created: 0 };
// Chunk by 250: bulk endpoints accept arrays but very large arrays
// become harder to debug if one item fails validation.
for (let i = 0; i < newOnes.length; i += 250) {
const chunk = newOnes.slice(i, i + 250);
const { error } = await routal.POST('/v2/stops', {
params: { query: { ...key, plan_id: planId, project_id: PROJECT_ID } },
body: chunk.map((o) => ({
external_id: o.id,
label: `${o.customerName}, ${o.addressLine}`,
location: { lat: o.lat, lng: o.lng, address: o.addressLine },
duration: 180,
time_windows: [[o.windowFromSec, o.windowToSec]],
phone: o.phoneE164,
email: o.email,
weight: o.weightKg,
tasks: [{ label: 'Scan tracking barcode', barcode: o.trackingBarcode }],
})) as never,
});
if (error) throw error;
}
return { created: newOnes.length };
}
async function listStops(planId: string) {
const { data } = await routal.GET('/v2/plan/{id}/stops', {
params: { path: { id: planId }, query: key },
});
return (data as Array<{ id: string; external_id?: string; route_id?: string }>) ?? [];
}
// ── (3) Cutoff job: start the run and return ─────────────────────────────
/** No polling: the optimization.succeeded webhook picks up from here. */
export async function optimizeAtCutoff(planId: string) {
// 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-5) 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 dispatch yours.
if (await pendingRuns.remove(planId)) {
await dispatchRoutes(planId);
await flagOverflow(planId);
}
break;
}
case 'routal.optimizer.2.optimization.failed':
// The failed event carries no plan id today: alert with every run still pending.
await alertOps('Routal optimization failed', { error: event.data.error, pending: await pendingRuns.list() });
break;
case 'routal.drivers.2.route.started':
metrics.timing('lastmile.driver_app_open_lag_seconds', event.data.id, event.created_at);
break;
case 'routal.planner.2.stop.reported':
await closeOrder(event.data);
break;
case 'routal.drivers.2.route.finished':
await reconcileRoute(event.data); // every stop of event.data.stops closed in the OMS?
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 the run could not place: roll them to tomorrow (see Overflow below). */
async function flagOverflow(planId: string) {
const overflow = (await listStops(planId)).filter((s) => !s.route_id);
if (overflow.length) await oms.flagRollover(overflow.map((s) => s.external_id!));
}
const OMS_STATE = {
service_report_completed: 'delivered',
service_report_attempted: 'delivery_failed',
service_report_canceled: 'canceled',
} as const;
async function closeOrder(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 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.drivers.2.route.started",
"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) Push orders ────────────────────────────────────────────────────
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 push_daily_orders(plan_id: str, orders: list[dict]) -> dict:
"""orders: [{id, customer, address, lat, lng, phone, email, tracking_barcode, weight_kg, window_from_sec, window_to_sec}, ...]"""
if not orders:
return {"created": 0}
existing = {s.get("external_id", "") for s in list_stops(plan_id)}
new_ones = [o for o in orders if o["id"] not in existing]
if not new_ones:
return {"created": 0}
for i in range(0, len(new_ones), 250):
chunk = new_ones[i:i + 250]
payload = [
{
"external_id": o["id"],
"label": f"{o['customer']}, {o['address']}",
"location": {"lat": o["lat"], "lng": o["lng"], "address": o["address"]},
"duration": 180,
"time_windows": [[o["window_from_sec"], o["window_to_sec"]]],
"phone": o["phone"],
"email": o["email"],
"weight": o["weight_kg"],
"tasks": [{"label": "Scan tracking barcode", "barcode": o["tracking_barcode"]}],
}
for o in chunk
]
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()
return {"created": len(new_ones)}
# ── (3) Cutoff job: start the run and return ─────────────────────────────
def optimize_at_cutoff(plan_id: str) -> None:
"""No polling: the optimization.succeeded webhook picks up from here."""
# 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-5) 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"]
# Runs started from the planner fire this too: only dispatch yours.
if pending_runs.remove(plan_id):
dispatch_routes(plan_id)
flag_overflow(plan_id)
elif kind == "routal.optimizer.2.optimization.failed":
# The failed event carries no plan id today: alert with every run still pending.
alert_ops("Routal optimization failed", error=data.get("error"), pending=pending_runs.list())
elif kind == "routal.planner.2.stop.reported":
close_order(data)
elif kind == "routal.drivers.2.route.finished":
reconcile_route(data) # every stop of data["stops"] closed in the OMS?
processed.add(event["id"])
def dispatch_routes(plan_id: str) -> None:
routes = requests.get(f"{BASE}/v2/plan/{plan_id}/routes", params=KEY, timeout=30).json()
for route in routes:
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 flag_overflow(plan_id: str) -> None:
"""Stops the run could not place: roll them to tomorrow (see Overflow below)."""
overflow = [s for s in list_stops(plan_id) if not s.get("route_id")]
if overflow:
oms.flag_rollover([s["external_id"] for s in overflow])
def close_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, processed, dispatched, jobs and oms stand for your own
storage, queue and OMS client. processed and dispatched only need an
insert and a lookup by id.
The scan task carries the code the driver is expected to scan in barcode.
Signature and photos are not tasks: you require them once, in the project's
proof-of-delivery settings in the planner, and they come back on the report as
signature.url and images[].url.
Production hardening
Customer notifications: populate phone + email, the rest is automatic
The single biggest cost for e-commerce ops is "where's my driver?" tickets.
Routal's customers app at c.routal.com handles this for
you as long as every stop has phone and/or email:
- At dispatch the customer receives a link to a live page showing the route on a map and the estimated arrival window for their stop.
- As the driver gets close the customer is pinged again with a tighter ETA.
- On completion the customer can rate the experience and download the POD.
Your integration's job: validate phone (E.164) and email at ingestion time, and refuse to push a stop without at least one. A stop with neither is a guaranteed support ticket.
function requireContact(order: EcommerceOrder) {
if (!order.phoneE164 && !order.email) {
throw new Error(`order ${order.id} has no phone or email: refusing to push`);
}
if (order.phoneE164 && !/^\+[1-9]\d{6,14}$/.test(order.phoneE164)) {
throw new Error(`order ${order.id} phone is not E.164: ${order.phoneE164}`);
}
}Address quality: geocode early, fail the order, never the route
Customer-entered addresses are inconsistent. Routal will reject a stop with an
out-of-range lat/lng (highway.geocoding.error.wrong_lat_lng) and the optimizer
will move stops to the unassigned bucket if they geocode to a point with no
roads (e.g., the middle of a lake).
Pattern:
- Geocode before push. Either call
POST /v2/stops/geocodeupstream, or geocode in your OMS using your own provider (Google Maps, Mapbox) before the nightly push. - Cache and revalidate. Address strings rarely change between a customer's
orders; cache the geocoded
(lat, lng)against a normalized address hash. - Refuse, don't auto-fix. If geocoding returns confidence below a
threshold (e.g., Google's
GEOMETRIC_CENTERorAPPROXIMATE), flag the order for manual review in your OMS. Don't ship a probably-wrong stop and hope.
Overflow: when the day's orders don't fit
When the order book grows past what the fleet can deliver inside the day's windows, the optimizer leaves some stops without a route. For e-commerce this usually means "order book grew past fleet capacity at the cutoff", and the integration must roll those orders over gracefully.
The run still ends with optimization.succeeded, so check for leftovers in the
same handler that dispatches: flagOverflow above lists the plan's stops with
no route_id. Move them to tomorrow's plan with POST /v2/stop/move (they are
still pending, so moving is safe) and mark them "rolled over" in the OMS so
customer service can notify.
When the run itself fails, optimization.failed arrives instead and the plan
keeps the routes it had. Don't dispatch: alert, fix the cause (often a vehicle
without working hours or a stop without a valid location) and optimize again.
Give every pending run a timeout too, say 30 minutes: a run canceled from the
planner sends neither event.
Reconciling stop.reported back into the OMS
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 OMS state
machine:
Latest report.type | Stop status | OMS action |
|---|---|---|
service_report_completed | completed | Mark order delivered, attach signature + photo URLs, close ticket. |
service_report_attempted | pending | Mark delivery failed, capture the cancel_reason. The driver may try again later in the day, so wait for the next report or route.finished before triggering your retry rule. |
service_report_canceled | canceled | Mark order canceled, refund flow if applicable. |
A stop the route ended without delivering arrives as incomplete in
route.finished: that's the moment to schedule the next-day re-attempt.
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
A deploy at the wrong minute, an OMS outage longer than the retry window, a
bug in the handler: some deliveries end up lost. 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.
Close the day with a check that every stop of the plan has a final state in
the OMS. Anything left is a webhook that never arrived: read it with
GET /v2/stop/{stop_id}.
Observability: the metrics that matter
| Metric | What it tells you |
|---|---|
lastmile.orders_pushed_total{plan_id} | Daily order volume reaching Routal. Drops to 0 = push job broken. |
lastmile.geocoding_failures_total | Bad addresses caught before push. Spike = OMS data quality regressing. |
lastmile.rollover_orders_total | Stops left without a route after optimization.succeeded. Trending up = need more vehicles. |
lastmile.first_attempt_success_rate | completed over (completed + incomplete + canceled). >92% = healthy. |
lastmile.driver_app_open_lag_seconds | Time from route/dispatch to route.started webhook. Long lag = driver onboarding issue. |
lastmile.webhook_replays_total | Deliveries the nightly job had to resend. Above zero most days = the receiver is dropping events. |
Common errors
message_id | Cause | What to do |
|---|---|---|
highway.geocoding.error.wrong_lat_lng | Stop location.lat/lng out of range, or address geocoded to nowhere. | Geocode upstream; flag for manual review when confidence is low. |
highway.optimization.error.no_result_found | Orders exceed fleet capacity inside the day's windows. | Roll overflow to next day's plan; notify customer service via OMS flag. |
highway.optimization.error.sync_optimization_already_progress | Another optimization is still running for the same plan. | Wait for its optimization.succeeded or optimization.failed webhook. Do not 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. |
highway.stop.error.custom_fields_invalid | Custom fields on the stop don't match project definitions. | Fix the field schema in the dashboard, or strip the offending field from the payload. |
400 Bad Request on phone validation | Phone is not E.164 (must start with + and be 7-15 digits). | Validate upstream and refuse the order before pushing. |
429 Too Many Requests | Exceeded the 2,000 req/min cap with too many parallel pushes. | Chunk by 250, sleep 200ms between chunks, or run with a single worker. |
Next steps
- Nightly batch for B2B distribution: the scaffolding pattern this recipe builds on; reuse the cron + recovery logic.
- Nightly batch + live dispatch: when your e-commerce flow accepts orders during execution (same-day cutoffs) instead of a single nightly cut.
- Package tracking: when a single delivery
carries several tracked parcels and you need per-parcel
pending → picked → deliveredstatus, not just one stop outcome. - Webhooks: the full cycle, event catalog, retries, delivery log and authentication patterns.
- Idempotency: the search-then-create pattern that keeps the daily push safe under cron retries.
