Skip to main content
Routal

Same-day grocery delivery

Dark store and grocery e-commerce. The customer ordered 90 minutes ago and expects the doorbell to ring inside a two-hour window. Orders land continuously, the integration micro-batches them into short waves, the optimizer slots each wave onto active vehicles, and the customers app sends arrival ETAs as the driver gets close. This recipe covers the wave cadence driven by optimization webhooks, the cold-chain stop shape, delivery status relayed to the OMS on stop.reported, and the rate-control patterns that keep dispatchers ahead of the order book.

Who this is for

You run a same-day grocery or dark-store operation. The customer placed their order 30-120 minutes ago, paid online, and expects the doorbell to ring inside a tight delivery window. Common shapes:

  • A dark-store grocer (10-30 minute fulfillment SLA) operating from hyperlocal hubs in dense urban areas, dispatching on bikes / e-bikes / vans.
  • A legacy supermarket chain offering same-day from their existing stores via a fulfillment partner, with a slightly longer window (90-120 min) and van-based fleet.
  • A specialty grocer (organic, premium, gourmet) with a smaller daily volume but tight cold-chain requirements (frozen meat, fresh produce, refrigerated dairy on the same van).
  • A convenience / on-demand vertical (pharmacy, beverage, late-night essentials) where the order shape mirrors grocery (small items, residential delivery, customer waiting) even if the product catalog differs.

What makes you different from last-mile parcel e-commerce:

  • The customer is actively waiting. A 2-hour ETA window for a non-perishable parcel is fine; for an order with ice cream in it, the SLA is the product.
  • Orders are not known the night before. You can't run a nightly batch: the day's plan grows continuously and the optimizer must absorb new stops into in-progress routes without disrupting drivers already on the road.
  • Cold-chain compliance is binding, not nice-to-have. A van without a freezer cannot serve a frozen-foods stop. Use requires / provides skill matching (see Capacitated distribution for the full mechanics).

What the rhythm looks like

Continuous push + wave optimization + selective dispatch on the optimization.succeeded webhook:

T-0          T+5 min        T+10 min       T+15 min       T+20 min
─────────    ───────────    ───────────    ───────────    ───────────
Orders A, B  Orders C, D    Orders E, F    Orders G, H    ...
arrive       arrive         arrive         arrive

             Wave 1 fires   Wave 2 fires   Wave 3 fires   Wave 4 fires
             ⚡ optimize    ⚡ optimize    ⚡ optimize    ⚡ optimize
             (A + B → R1)   (C, D onto R1) (E, F → R2)    (G onto R2,
                                                           H → R3)
             ⚡ optimization.succeeded, seconds later
             Dispatch R1    R1 already     Dispatch R2    Dispatch R3
             Driver gets    dispatched:    Driver R2      Driver R3
             magic link     skip           gets magic     gets magic
                                           link           link

                                                          T+60 min
                                                          ──────────
                                                          Order A
                                                          delivered
                                                          → stop.reported
                                                          → OMS shows
                                                            "Delivered"
                                                          → customer
                                                            rating UI

Two notes specific to same-day grocery:

  • Wave cadence is your operational lever. Faster waves (every 3-5 min) = fresher commitments but more optimizer churn and more dispatch noise. Slower waves (every 15-20 min) = larger batches but worse customer-promise accuracy. Most ops settle at 5-10 min waves.
  • keep_current_assignment=true is load-bearing. Without it, every wave re-optimization could rewrite the route of a driver already on the road, and the customers app would push a new ETA based on a new sequence. Drivers and customers both hate this. Always use it on live re-optimize.

The integration shape

On deploy (once)
POST /v2/webhook  (+ POST /v2/webhook/{id}/test)   find-or-create on url

OMS / dark-store backend
     │
     │  order-created event (webhook from OMS to your integration)
     ▼
[ order: { id, items[], cold_chain_skus[], delivery_address, slot_window } ]
     │
     │  (1) push as Routal stop on today's plan
     ▼
POST /v2/stops                              (idempotent on external_id = OMS order ID)
     │
     │  (2) cron tick every N minutes, only if the previous wave has ended
     ▼
POST /v2/plan/{id}/optimize/async?keep_current_assignment=true
     │
     │  (3) webhook: optimization.succeeded (data.plan.id)
     ▼
GET /v2/plan/{id}/routes → POST /v2/route/{id}/dispatch  (only routes not dispatched yet)
     │
     │  (4) webhooks during execution
     ▼
stop.reported  → OMS marks "delivered" + customer notification
route.finished → driver returns to depot or accepts next wave
     │
     │  (5) nightly
     ▼
GET /v2/webhook/{id}/events?status=error → resend what you missed

The two main differences vs. nightly-batch + live-dispatch:

  • Plan duration is shorter. A grocery plan often covers a single shift (e.g., 14:00-22:00) instead of a full day. Some ops create a fresh plan every 4 hours; others use one plan per day but optimize many times.
  • Wave optimization runs against a fixed cron. Each fire is fast (≤ 30s) because of keep_current_assignment=true: most of the existing assignment is locked, only new stops + a few unassigned ones are placed.

Nothing in this loop polls. A cron tick ends right after it starts the wave; the optimization.succeeded webhook dispatches the result and frees the plan for the next tick.

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.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) Push a new order as a stop as soon as it lands in your OMS.
#     external_id = OMS order ID. cold-chain SKUs add requires=["frozen"].
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-DKS-22301",
      "label": "B. Garcia, 18 Sant Pere més Alt",
      "location": { "lat": 41.3870, "lng": 2.1741, "address": "Sant Pere més Alt 18, 08003 Barcelona" },
      "duration": 120,
      "time_windows": [[51000, 58200]],
      "phone": "+34699111222",
      "email": "garcia@example.com",
      "weight": 4.2,
      "requires": ["refrigerated"]
    }
  ]'

# (2) Wave optimize: a cron tick every N minutes, fired only once the previous
#     wave's optimization.succeeded or optimization.failed webhook has arrived.
#     Returns at once. Always pass keep_current_assignment=true to protect
#     drivers on the road.
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: read the routes, then dispatch each one that
#     has stops and that you haven't dispatched yet. Dispatch re-sends the
#     driver email, so never dispatch a route twice.
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) 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.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) Push each order as it lands ──────────────────────────────────────

type GroceryOrder = {
  id: string;
  customer: string;
  lat: number;
  lng: number;
  address: string;
  phoneE164: string;
  email: string;
  weightKg: number;
  windowFromSec: number;        // promised slot start (seconds from midnight)
  windowToSec: number;          // promised slot end
  coldChain: 'ambient' | 'refrigerated' | 'frozen';
};

/** Push a single order as soon as it lands in the OMS. */
export async function pushOrder(planId: string, order: GroceryOrder) {
  const { error } = await routal.POST('/v2/stops', {
    params: { query: { ...key, plan_id: planId, project_id: PROJECT_ID } },
    body: [
      {
        external_id: order.id,
        label: `${order.customer}, ${order.address}`,
        location: { lat: order.lat, lng: order.lng, address: order.address },
        duration: 120,
        time_windows: [[order.windowFromSec, order.windowToSec]],
        phone: order.phoneE164,
        email: order.email,
        weight: order.weightKg,
        requires: order.coldChain === 'ambient' ? [] : [order.coldChain],
      },
    ] as never,
  });
  if (error) throw error;
}

// ── (2) Wave tick: cron every N minutes ──────────────────────────────────

// A wave takes seconds. A run canceled in the planner sends neither event,
// so a wave older than this counts as ended.
const WAVE_TIMEOUT_MS = 10 * 60_000;
const SKIP_TICK = new Set([
  'highway.optimization.error.sync_optimization_already_progress', // a run started from the planner is going
  'highway.optimization.error.nothing_to_optimize',                // no pending stop left on the plan
]);

/** Starts a wave only when the previous one has ended. No polling: the
 *  optimization.succeeded webhook dispatches the result. */
export async function waveTick(planId: string) {
  const startedAt = await pendingRuns.get(planId); // your DB: plan → when its wave started
  if (startedAt && Date.now() - startedAt.getTime() < WAVE_TIMEOUT_MS) {
    metrics.increment('grocery.wave_skipped_running_total');
    return; // previous wave still running: never stack runs
  }
  await pendingRuns.set(planId, new Date());
  const { error } = await routal.POST('/v2/plan/{id}/optimize/async', {
    params: { path: { id: planId }, query: { ...key, keep_current_assignment: true } },
  });
  if (error) {
    await pendingRuns.remove(planId);
    if (SKIP_TICK.has((error as { message_id?: string }).message_id ?? '')) return; // next tick catches up
    throw error;
  }
}

// ── (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 your waves.
      if (await pendingRuns.remove(planId)) { // also frees the plan for the next tick
        await dispatchNewRoutes(planId);
        await trackUnrouted(planId);
      }
      break;
    }
    case 'routal.optimizer.2.optimization.failed':
      // The failed event carries no plan id today: alert with every pending wave
      // and free them all. A wave still running makes its next tick skip.
      await alertOps('Routal wave failed', { error: event.data.error, pending: await pendingRuns.list() });
      await pendingRuns.clear();
      break;
    case 'routal.planner.2.stop.reported':
      await relayDelivery(event.data);
      break;
    case 'routal.drivers.2.route.finished':
      await reconcileRoute(event.data); // stops of event.data.stops still incomplete: re-slot or refund
      break;
  }
  await processed.add(event.id!);
}

/** Every wave fires optimization.succeeded: dispatch only what is new. */
async function dispatchNewRoutes(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;           // vehicle with nothing assigned yet
    if (await dispatched.has(route.id)) continue; // already on the road: 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 this wave could not place (cold chain or capacity). The next wave tries again. */
async function trackUnrouted(planId: string) {
  const { data } = await routal.GET('/v2/plan/{id}/stops', {
    params: { path: { id: planId }, query: key },
  });
  const stops = (data as Array<{ external_id?: string; route_id?: string; status?: string }>) ?? [];
  const unrouted = stops.filter((s) => s.status === 'pending' && !s.route_id);
  metrics.gauge('grocery.unassigned_at_dispatch_total', unrouted.length);
  if (unrouted.length) await oms.flagAtRisk(unrouted.map((s) => s.external_id!));
}

const OMS_STATUS = {
  service_report_completed: 'delivered',
  service_report_attempted: 'delivery_failed', // the stop stays pending: the driver may try again
  service_report_canceled: 'canceled',
} as const;

/** data is the stop; its newest report is the last one. An UPSERT, so a duplicate is harmless. */
async function relayDelivery(stop: any) {
  const report = stop.reports?.at(-1);
  if (!report) return;
  await oms.setOrderStatus(stop.external_id, OMS_STATUS[report.type as keyof typeof OMS_STATUS]);
}

// ── 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 datetime, timedelta, timezone
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.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) Push each order as it lands ──────────────────────────────────────

def push_order(plan_id: str, order: dict) -> None:
    """order: {id, customer, address, lat, lng, phone, email, weight_kg, window_from_sec, window_to_sec, cold_chain}"""
    requires = [] if order["cold_chain"] == "ambient" else [order["cold_chain"]]
    payload = [{
        "external_id": order["id"],
        "label": f"{order['customer']}, {order['address']}",
        "location": {"lat": order["lat"], "lng": order["lng"], "address": order["address"]},
        "duration": 120,
        "time_windows": [[order["window_from_sec"], order["window_to_sec"]]],
        "phone": order["phone"],
        "email": order["email"],
        "weight": order["weight_kg"],
        "requires": requires,
    }]
    requests.post(
        f"{BASE}/v2/stops",
        params={**KEY, "plan_id": plan_id, "project_id": PROJECT_ID},
        json=payload,
        timeout=30,
    ).raise_for_status()


# ── (2) Wave tick: cron every N minutes ──────────────────────────────────

# A wave takes seconds. A run canceled in the planner sends neither event,
# so a wave older than this counts as ended.
WAVE_TIMEOUT = timedelta(minutes=10)
SKIP_TICK = {
    "highway.optimization.error.sync_optimization_already_progress",  # a run started from the planner is going
    "highway.optimization.error.nothing_to_optimize",                 # no pending stop left on the plan
}


def wave_tick(plan_id: str) -> None:
    """Starts a wave only when the previous one has ended. No polling: the
    optimization.succeeded webhook dispatches the result."""
    now = datetime.now(timezone.utc)
    started_at = pending_runs.get(plan_id)  # your DB: plan -> when its wave started
    if started_at and now - started_at < WAVE_TIMEOUT:
        metrics.increment("grocery.wave_skipped_running_total")
        return  # previous wave still running: never stack runs
    pending_runs.set(plan_id, now)
    resp = requests.post(
        f"{BASE}/v2/plan/{plan_id}/optimize/async",
        params={**KEY, "keep_current_assignment": "true"},
        timeout=60,
    )
    if not resp.ok:
        pending_runs.remove(plan_id)
        body = resp.json() if resp.headers.get("content-type", "").startswith("application/json") else {}
        if body.get("message_id") in SKIP_TICK:
            return  # next tick catches up
        resp.raise_for_status()


# ── (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


OMS_STATUS = {
    "service_report_completed": "delivered",
    "service_report_attempted": "delivery_failed",  # the stop stays pending: the driver may try again
    "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 your waves.
        if pending_runs.remove(plan_id):  # also frees the plan for the next tick
            dispatch_new_routes(plan_id)
            track_unrouted(plan_id)
    elif kind == "routal.optimizer.2.optimization.failed":
        # The failed event carries no plan id today: alert with every pending wave
        # and free them all. A wave still running makes its next tick skip.
        alert_ops("Routal wave failed", error=data.get("error"), pending=pending_runs.list())
        pending_runs.clear()
    elif kind == "routal.planner.2.stop.reported":
        relay_delivery(data)
    elif kind == "routal.drivers.2.route.finished":
        reconcile_route(data)  # stops of data["stops"] still incomplete: re-slot or refund

    processed.add(event["id"])


def dispatch_new_routes(plan_id: str) -> None:
    """Every wave fires optimization.succeeded: dispatch only what is new."""
    resp = requests.get(f"{BASE}/v2/plan/{plan_id}/routes", params=KEY, timeout=30)
    resp.raise_for_status()
    for route in resp.json():
        if not route.get("stops"):
            continue  # vehicle with nothing assigned yet
        if dispatched.has(route["id"]):
            continue  # already on the road: 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 track_unrouted(plan_id: str) -> None:
    """Stops this wave could not place (cold chain or capacity). The next wave tries again."""
    resp = requests.get(f"{BASE}/v2/plan/{plan_id}/stops", params=KEY, timeout=30)
    resp.raise_for_status()
    unrouted = [s for s in resp.json() if s.get("status") == "pending" and not s.get("route_id")]
    metrics.gauge("grocery.unassigned_at_dispatch_total", len(unrouted))
    if unrouted:
        oms.flag_at_risk([s["external_id"] for s in unrouted])


def relay_delivery(stop: dict) -> None:
    """data is the stop; its newest report is the last one. An UPSERT, so a duplicate is harmless."""
    reports = stop.get("reports") or []
    if not reports:
        return
    oms.set_order_status(stop["external_id"], OMS_STATUS[reports[-1]["type"]])


# ── Nightly: replay what the receiver missed ─────────────────────────────

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

pendingRuns, processed, dispatched, jobs, metrics and oms stand for your own storage, queue, metrics and OMS client. pendingRuns maps a plan id to the time its wave started; processed and dispatched only need an insert and a lookup by id.

Production hardening

Wave cadence: pick a number and stick to it

The cron interval is the most consequential operational tunable. Three failure modes if you get it wrong:

  • Too fast (1-3 min): ticks keep finding the previous wave still running and skip, and drivers see new ETAs more often than makes sense.
  • Too slow (20+ min): an order placed at minute 14 of a 20-min wave waits ~6 minutes before any optimize considers it, bad for a sub-2-hour SLA.
  • Variable: worse than either fixed extreme. Drivers and customers learn to expect rhythm; randomness erodes trust.

Start at 5-minute waves for a sub-2-hour SLA, 3-minute waves for sub-60. Tune only after a week of metrics.

One wave per plan at a time

Routal runs one optimization per plan at a time and rejects a second one with highway.optimization.error.sync_optimization_already_progress. Don't let the cron find that out. waveTick above records each wave in pendingRuns and fires the next one only after the previous wave has ended:

  • optimization.succeeded with your plan's data.plan.id: dispatch the new routes and free the plan.
  • optimization.failed: it carries no plan id today, so alert with every pending wave and free them all. The plan keeps the routes it had.
  • No event after 10 minutes: a run canceled from the planner sends neither event. Treat the wave as ended.

Runs started from the planner or the MCP server also fire optimization.succeeded. They are not in pendingRuns, so the handler ignores them; when one is still going, the tick gets already_progress, skips, and the next tick catches up.

Cold chain: explicit requires/provides per SKU class

A van without a freezer cannot serve a frozen stop. Routal enforces this as a hard constraint when you set the matching requires on the stop and the matching provides on the vehicle (sent to POST /v3/vehicles; it reads back as default_provides):

// vehicle
{ provides: ['ambient', 'refrigerated', 'frozen'] }   // fully-equipped truck
{ provides: ['ambient'] }                              // bike or unrefrigerated van

// stop
{ requires: ['frozen'] }   // ice cream, frozen meat
{ requires: ['refrigerated'] }   // dairy, fresh produce
{ requires: [] }           // ambient: any vehicle is fine

If no active vehicle provides a stop's requires, the wave still ends in optimization.succeeded and leaves that stop without a route. trackUnrouted catches it after every wave: log which skill was unmet, and either scale the fleet (call in an extra cold-chain van) or refund the order before its slot runs out.

See Capacitated distribution for the full constraint matrix (weight, volume, skill matching).

Idempotency on the wave push

Your OMS may fire the order-created event more than once (retry on its own network failure, replay during deploy). Make the per-order push idempotent via external_id:

async function pushOrderIdempotent(planId: string, order: GroceryOrder) {
  // Cheap pre-check: skip the POST if the order is already on the plan.
  const { data } = await routal.POST('/v2/stops/search', {
    params: { query: { private_key: ROUTAL_API_KEY, project_id: PROJECT_ID } },
    body: {
      limit: 1,
      predicates: [
        { field: 'external_id', operator: 'eq', value: order.id, type: 'string' },
      ],
    } as never,
  });
  const existing = (data as { docs?: Array<{ id: string }> } | undefined)?.docs?.[0];
  if (existing) return { skipped: 'already_exists' };
  await pushOrder(planId, order);
  return { skipped: null };
}

Relaying stop.reported to the OMS

stop.reported fires once per report, and data is the stop with all its reports. The newest one is the last. Its type sets the order status the customer sees:

Latest report.typeStop statusOMS status
service_report_completedcompletedDelivered. The order page flips within seconds.
service_report_attemptedpendingDelivery failed. The driver may try again within the slot, so wait for the next report or route.finished.
service_report_canceledcanceledCanceled. Start the refund flow.

A stop the route ended without delivering arrives as incomplete in route.finished: re-slot or refund it there.

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

Retries cover about 36 minutes. A longer OMS outage or a handler bug loses events for good, and the nightly replayFailedDeliveries job above brings them back: it reads yesterday'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 the job twice is harmless.

A lost optimization.succeeded costs less than it looks: the wave times out, and the next wave's dispatchNewRoutes dispatches every route still waiting. See Webhooks → Delivery log.

Rate limit: cap concurrent pushes

Same-day grocery has spiky traffic: lunch and dinner pushes can land 100+ orders in a 90-second burst. The Routal API caps you at 2,000 req/min per credential. Single-stop pushes are cheap individually but the per-stop POST shape doesn't take an array efficiently for many small orders.

Compromise: micro-batch by 10-25 orders per push with a single-worker queue that drains at most every 200ms. This stays well under 2,000 req/min and keeps P95 push latency under 1 second.

Observability: the metrics that matter

MetricWhat it tells you
grocery.orders_pushed_per_minuteReal-time order velocity. Spike = lunch/dinner rush; drop = OMS broken.
grocery.wave_skipped_running_totalTicks skipped because the previous wave had not ended yet. Sustained > 5% per hour = waves too fast or optimizer slow.
grocery.median_optimize_secondsTime from a wave's POST to its optimization.succeeded. Trending up = plan is too large; chunk into shifts.
grocery.unassigned_at_dispatch_totalStops left without a route after a wave's optimization.succeeded. Spike = cold-chain or capacity overflow.
grocery.median_promise_to_delivery_secondsTime from customer order to stop.reported. The headline customer-experience metric.
grocery.webhook_replays_totalDeliveries the nightly job had to resend. Above zero most days = the receiver is dropping events.

Common errors

message_idCauseWhat to do
highway.optimization.error.sync_optimization_already_progressAnother run is still going on the plan, usually one started from the planner.Wait for its optimization.succeeded or optimization.failed webhook; skip this tick and let the next one pick it up. Do not retry.
highway.optimization.error.nothing_to_optimizeThe plan has no pending stop left, or every route is locked.Nothing to do: skip the tick. Common at the end of a shift.
highway.optimization.error.no_result_foundCold-chain capacity exhausted, or all vans full.Scale fleet (extra cold van), or refund unfittable orders with apology + voucher.
highway.geocoding.error.wrong_lat_lngAddress resolves to nonsense (out of region, lake, etc.).Reject the order in the OMS before push; customer outreach.
highway.stop.error.report_already_existsYour integration posted a report on a stop that already has a terminal one, for example an OMS cancel after the driver delivered.Read the stop's status before posting and keep the driver's outcome when it is already final.
highway.webhook.error.invalid_urlThe webhook url is not public: localhost, a private IP, an internal host, or credentials in the URL.Use a public HTTPS URL; a tunnel such as ngrok for local development.
highway.webhook.error.send_testPOST /v2/webhook/{id}/test got no 2xx from your endpoint within 10 seconds.Fix the endpoint before the first real event: check the token, the route and the response time.
429 Too Many RequestsPush velocity exceeded 2,000 req/min.Throttle the per-order pusher; switch to micro-batches of 10-25.

Next steps

  • Nightly batch + live dispatch: the architectural cousin of this recipe. The wave pattern is the same, the cadence is much faster.
  • Capacitated distribution: the full constraint matrix for cold-chain operations, including pre-flight feasibility checks before optimize.
  • Webhooks: the full cycle, event catalog, retries and delivery log. stop.reported is the event your customer-facing order page hangs off.
  • Idempotency: pattern 1 (search-then-create) is the load-bearing guard for the order-created handler.