Package tracking
Parcel-level tracking inside a delivery stop. One stop carries many package identifiers, each advancing pending → picked → delivered. Push the identifiers when you create the stop, then reconcile per-parcel status, partial deliveries included, back into your WMS or ERP. This recipe covers the data model (packages vs tasks vs capacity), the delivery-only constraint, and the webhook cycle that dispatches on optimization.succeeded and reconciles every parcel on stop.reported and route.finished, with no package webhook.
Who this is for
You deliver more than one tracked parcel to a single address and your system of record needs to know the fate of each parcel, not just whether the stop was completed. Common shapes:
- A 3PL / parcel operation where one delivery address routinely receives several boxes, each with its own barcode, and the customer or shipper expects parcel-level scan visibility.
- A multi-box B2B distributor (pharma, industrial supply, food service) delivering palletized or multi-case orders where partial acceptance is normal: the receiver signs for 8 of 10 cases and rejects 2.
- An e-commerce consolidator shipping multiple line-items that were split across boxes but land at the same door, where the OMS tracks fulfillment at the parcel/SSCC level.
- Anyone who today encodes "3 boxes" in the stop label or a custom field and wants a first-class, status-bearing list instead.
What makes you different from the last-mile e-commerce
recipe: that flow tracks one shipment per stop and closes it with a single
stop.reported outcome. Here, the stop is a container and the unit you
reconcile is the individual package.
Packages, tasks, and capacity: three different things
Stops carry three overlapping-sounding fields. Using the right one is the whole game:
| Field | What it is | Status-bearing? | Use it for |
|---|---|---|---|
packages | A list of individual parcels, each { identifier }, with its own lifecycle | Yes, pending → picked → delivered per parcel | Tracking which boxes were actually handed over (incl. partial deliveries) |
tasks | Checklist items at the stop, each a label and optionally a barcode to scan | Completed/not, per task | Checks the driver ticks off at the stop |
weight / volume | Scalar load the stop adds to the vehicle | No, pure capacity input | Letting the optimizer respect vehicle capacity (capacitated distribution) |
A stop can use all three at once: 3 packages to track, a "check the seal"
task, and a weight of 14 kg for the optimizer. They are independent.
Packages do not feed the optimizer. Declare weight/volume if capacity
matters. Signature and photos are none of these: you require them in the
project's proof-of-delivery settings in the planner, not on each stop.
The package lifecycle
Each package has its own status, independent of the stop's status:
| Status | Meaning | Timestamp |
|---|---|---|
pending | Created via the API, not yet handled in the field | — |
picked | Collected / loaded onto the vehicle (scanned out) | picked_at |
delivered | Handed to the recipient (scanned at the door) | delivered_at |
API create Depot / loading At the door
────────── ─────────────── ───────────
packages: [ driver scans parcel driver scans parcel
{ identifier } ──▶ onto the van ──▶ on hand-off
] status: picked status: delivered
status: pending picked_at set delivered_at setThe exact scan points are driven by your driver-app configuration; the API surfaces whatever the field operation reports. Two rules hold regardless:
- You only ever send
identifier.status,picked_at,delivered_at, andupdated_atare server-managed. They are returned on reads and ignored on writes. - A stop can finish with packages in mixed states. The stop reports
completed/incomplete, but the parcels tell you 8 delivered, 2 stillpicked(came back on the van). That nuance is the reason packages exist.
The integration shape
On deploy (once)
POST /v2/webhook (+ POST /v2/webhook/{id}/test) find-or-create on url
WMS / OMS / ERP (system of record for parcels)
│
│ (1) for each delivery: external_id + packages: [{ identifier }, ...]
▼
POST /v2/stops (deliveries only: pickups reject packages)
│
│ (2) optimize: returns at once, unchanged from any other plan
▼
POST /v2/plan/{id}/optimize/async
│
│ (3) webhook: optimization.succeeded (data.plan.id)
▼
GET /v2/plan/{id}/routes → POST /v2/route/{id}/dispatch (one call per route)
│
│ (4) execution: drivers scan parcels → picked → delivered
▼
stop.reported ──▶ GET /v2/stop/{stop_id} ──▶ read packages[].status
│ (the webhook does NOT carry package status)
▼
write each parcel's state back to the WMS (partial-aware)
│
│ (5) route.finished: re-read the route's stops with open parcels
▼
not delivered by now → picked = back on the van, pending = never loaded
│
│ (6) nightly
▼
GET /v2/webhook/{id}/events?status=error → resend what you missedThe one non-obvious piece: there is no package.* webhook. stop.reported
is your trigger; the parcel detail lives on the stop, which you read back.
route.finished is the backstop: by then every parcel has its end-of-day
state, including those on stops the driver never reported.
Nothing in this loop polls for the optimization result. The job that starts
the run ends right away; the optimization.succeeded webhook picks up from
there. If the run fails, optimization.failed arrives instead and the plan
keeps the routes it had: don't dispatch, alert and optimize again. Give every
pending run a timeout too, say 30 minutes: a run canceled from the planner
sends neither event.
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://wms.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) Create a delivery stop carrying three tracked parcels. Only `identifier`
# is accepted per package; status is server-managed.
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-7741",
"label": "Pharma Plus, Calle Mayor 3",
"location": { "lat": 40.4168, "lng": -3.7038, "address": "Calle Mayor 3, 28013 Madrid" },
"duration": 240,
"weight": 14.0,
"packages": [
{ "identifier": "PKG-7741-01" },
{ "identifier": "PKG-7741-02" },
{ "identifier": "PKG-7741-03" }
]
}
]'
# (2) 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"
# (3) On optimization.succeeded: read the routes, then dispatch each one that
# has stops. Identical to any other plan.
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"
# (4) On stop.reported (data.id is the stop), and on route.finished for the
# stops that still have open parcels: read per-parcel status off the stop.
curl -s "https://api.routal.com/v2/stop/STOP_ID?private_key=YOUR_KEY" | \
jq '.packages[] | { identifier, status, delivered_at }'
# => { "identifier": "PKG-7741-01", "status": "delivered", "delivered_at": "..." }
# { "identifier": "PKG-7741-02", "status": "delivered", "delivered_at": "..." }
# { "identifier": "PKG-7741-03", "status": "picked", "delivered_at": null } ← came back on the van
# (5) Nightly: list yesterday's failed deliveries and resend the ones your
# WMS 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://wms.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) Create delivery stops with their parcels ─────────────────────────
type ParcelDelivery = {
orderId: string; // becomes external_id
receiver: string;
addressLine: string;
lat: number;
lng: number;
weightKg: number;
parcelIds: string[]; // your barcodes / SSCCs, become package identifiers
};
/** Create one delivery stop per order, each carrying its tracked parcels. */
export async function pushDeliveries(planId: string, deliveries: ParcelDelivery[]) {
if (deliveries.length === 0) return { created: 0 };
const { error } = await routal.POST('/v2/stops', {
params: { query: { ...key, plan_id: planId, project_id: PROJECT_ID } },
body: deliveries.map((d) => ({
external_id: d.orderId,
label: `${d.receiver}, ${d.addressLine}`,
location: { lat: d.lat, lng: d.lng, address: d.addressLine },
duration: 240,
weight: d.weightKg,
// Only `identifier` is read on input. Never set status here.
packages: d.parcelIds.map((identifier) => ({ identifier })),
})) as never,
});
if (error) throw error;
return { created: deliveries.length };
}
// ── (2) Start the run and return ─────────────────────────────────────────
/** No polling: the optimization.succeeded webhook picks up from here. */
export async function optimizePlan(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
}
}
// ── (3-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 dispatch yours.
if (await pendingRuns.remove(planId)) await dispatchRoutes(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.planner.2.stop.reported':
await reconcileStopParcels(event.data.id); // data is the stop
break;
case 'routal.drivers.2.route.finished':
await settleRoute(event.data);
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);
}
}
type Package = {
identifier: string;
status: 'pending' | 'picked' | 'delivered';
picked_at?: string;
delivered_at?: string;
};
/**
* Reconcile parcels after `stop.reported`. The webhook payload does NOT carry
* package status; read it off the stop. Partial-aware: every parcel is written
* back individually, never collapsed into one stop outcome.
*/
export async function reconcileStopParcels(stopId: string, endOfRoute = false) {
const { data, error } = await routal.GET('/v2/stop/{stop_id}', {
params: { path: { stop_id: stopId }, query: key },
});
if (error) throw error;
const packages = ((data as { packages?: Package[] }).packages ?? []);
const delivered = packages.filter((p) => p.status === 'delivered');
const notDelivered = packages.filter((p) => p.status !== 'delivered');
for (const p of delivered) {
await markParcelInWms(p.identifier, 'delivered', p.delivered_at);
}
for (const p of notDelivered) {
// Mid-route the driver may still retry: record the status as it is. Once the
// route is finished, 'picked' is back on the van and 'pending' never left the
// depot: trigger the WMS rule (re-attempt tomorrow, return to stock, outreach).
const state = !endOfRoute ? p.status : p.status === 'picked' ? 'back_on_van' : 'never_loaded';
await markParcelInWms(p.identifier, state);
}
return {
total: packages.length,
delivered: delivered.length,
partial: delivered.length > 0 && notDelivered.length > 0,
};
}
/** route.finished: settle every stop that still has open parcels, reported or not. */
async function settleRoute(route: any) {
for (const stop of (route.stops ?? []) as Array<{ id: string; external_id?: string }>) {
if (!(await wmsHasOpenParcels(stop.external_id))) continue; // already all delivered
await reconcileStopParcels(stop.id, true);
}
}
// ── 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;
}
}
declare function markParcelInWms(id: string, status: string, at?: string): Promise<void>;
declare function wmsHasOpenParcels(orderId?: string): Promise<boolean>;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://wms.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) Create delivery stops with their parcels ─────────────────────────
def push_deliveries(plan_id: str, deliveries: list[dict]) -> dict:
"""deliveries: [{order_id, receiver, address, lat, lng, weight_kg, parcel_ids}, ...]"""
if not deliveries:
return {"created": 0}
payload = [
{
"external_id": d["order_id"],
"label": f"{d['receiver']}, {d['address']}",
"location": {"lat": d["lat"], "lng": d["lng"], "address": d["address"]},
"duration": 240,
"weight": d["weight_kg"],
# Only `identifier` is read on input. Status is server-managed.
"packages": [{"identifier": pid} for pid in d["parcel_ids"]],
}
for d in deliveries
]
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(deliveries)}
# ── (2) Start the run and return ─────────────────────────────────────────
def optimize_plan(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
# ── (3-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
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)
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":
reconcile_stop_parcels(data["id"]) # data is the stop
elif kind == "routal.drivers.2.route.finished":
settle_route(data)
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 reconcile_stop_parcels(stop_id: str, end_of_route: bool = False) -> dict:
"""Call on stop.reported. The webhook does NOT carry package status, read the stop."""
resp = requests.get(f"{BASE}/v2/stop/{stop_id}", params=KEY, timeout=30)
resp.raise_for_status()
packages = resp.json().get("packages", [])
delivered = [p for p in packages if p.get("status") == "delivered"]
not_delivered = [p for p in packages if p.get("status") != "delivered"]
for p in delivered:
mark_parcel_in_wms(p["identifier"], "delivered", p.get("delivered_at"))
for p in not_delivered:
# Mid-route the driver may still retry. At route end, 'picked' = back on
# the van and 'pending' = never loaded: trigger the WMS rule.
status = p.get("status")
if end_of_route:
status = "back_on_van" if status == "picked" else "never_loaded"
mark_parcel_in_wms(p["identifier"], status, None)
return {
"total": len(packages),
"delivered": len(delivered),
"partial": len(delivered) > 0 and len(not_delivered) > 0,
}
def settle_route(route: dict) -> None:
"""route.finished: settle every stop that still has open parcels, reported or not."""
for stop in route.get("stops") or []:
if not wms_has_open_parcels(stop.get("external_id")):
continue # already all delivered
reconcile_stop_parcels(stop["id"], end_of_route=True)
# ── 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 and jobs stand for your own storage
and queue; markParcelInWms and wmsHasOpenParcels for your WMS client.
processed and dispatched only need an insert and a lookup by id.
Production hardening
Packages are delivery-only: pickups reject the field
A stop's delivery leg can carry packages; the pickup leg cannot. The API
rejects packages set on a pickup (the field is reserved on pickups). If you run
mixed delivery + pickup routes via the chain mechanic (see
reverse logistics), attach the parcels to the
delivery stop only. For pure returns/recovery flows, track the recovered
items with your own custom fields, not packages.
The system owns status, you own the identifier
On input, only identifier is read. Anything else you put inside a package
object (status, picked_at, …) is ignored. This means:
- You cannot "force" a parcel to
deliveredthrough the API: status only moves via the field operation (driver scans). Treat Routal as the source of truth for parcel state and your WMS as the source of truth for which parcels exist. - Keep identifiers stable and unique per stop. Use the real barcode / SSCC / tracking number so the field scan matches what you sent, and so your reconciliation join is unambiguous.
Partial deliveries: the case a single stop status can't express
A stop reports one outcome (completed / incomplete / canceled), but a
multi-parcel delivery is frequently partial: the receiver takes most boxes and
refuses a damaged one. Always reconcile at the parcel level: iterate
packages[] and write each parcel's terminal state back individually. Collapsing
to the stop outcome silently loses the rejected box and creates an inventory
discrepancy.
Reconciliation without a package webhook
There is no package.created / package.delivered event, and the
stop.reported payload does not embed package status. The robust pattern:
- Per stop, on
stop.reported:GET /v2/stop/{stop_id}(the stop isdata.id) and readpackages[].status. The event fires once per report, so a stop attempted in the morning and delivered in the afternoon triggers it twice. Writing the current state each time makes that harmless. - Per route, on
route.finished: re-read every stop of the route that still has open parcels in your WMS. A parcel notdeliveredby now is back on the van (picked) or never left the depot (pending). This also covers stops the driver never reported, which send nostop.reportedat all. - Nightly: replay the deliveries your receiver missed (see Missed events).
- In-flight visibility (optional): if you need to see
pickedbefore the stop closes (e.g. confirm everything was loaded at the depot), pollGET /v2/plan/{id}/stopson an interval and diffpackages[].status. Don't poll tighter than you need. This is the only polling in the recipe: the routes are still dispatched onoptimization.succeeded, and every parcel's final state still arrives throughstop.reportedandroute.finished.
Authenticate the webhook handler with a URL token, drop duplicates by the
envelope id, and answer 2xx within 10 seconds: the GET /v2/stop call runs
in the worker, not in the request. 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, a WMS outage longer than the retry window, a
bug in the handler: some deliveries end up lost, and with them the trigger to
read a stop's parcels. 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 parcel of the plan has a final state in
the WMS. Anything left is a webhook that never arrived: read its stop with
GET /v2/stop/{stop_id}.
Idempotency: treat the package set as declarative
Push stops idempotently on external_id (search-then-create, see
Idempotency). When you re-send or update a stop, treat its
packages array as the full declarative set of parcels that belong to that
stop: send every parcel you want present, not a delta. Resolve parcel adds/drops
in your WMS first, then push the complete list.
Common errors
| Symptom | Cause | What to do |
|---|---|---|
| Packages set on a pickup are dropped / rejected | Pickups cannot carry packages; the field is reserved on the pickup leg. | Attach packages to the delivery stop; track recovered items via custom fields. |
Sent status: "delivered", read back pending | Status is server-managed; only identifier is read on input. | Don't send status. Let driver scans advance it; reconcile by reading the stop. |
Stop is completed but a parcel is still picked | Partial delivery, not an error. The box came back on the van. | Reconcile per parcel; trigger your re-attempt / return-to-depot rule for the non-delivered ones. |
| Package status never updates in the field | No scan happened, or the driver app isn't configured to scan parcels. | Confirm the operation scans packages; verify identifiers match the barcodes drivers scan. |
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 and friends | Generic stop validation, unrelated to packages. | See last-mile e-commerce → Common errors. |
Next steps
- Last-mile e-commerce: the one-shipment-per-stop flow with customer tracking links; reuse its push + webhook scaffolding.
- Capacitated distribution: when the
parcels also need
weight/volumeso the optimizer respects vehicle capacity. - Reverse logistics: pickups, returns, and the delivery+pickup chain mechanic (and why packages live on the delivery leg).
- Lifecycle: how stop, route, and plan statuses advance, and where package transitions sit within execution.
- Webhooks: the full cycle, the
stop.reportedenvelope you trigger reconciliation from, retries and the delivery log.
