Skip to main content
Routal

Calendar-driven recurring services

Operations that run on a calendar, not an order book. Bulk gas refills, ITV inspections, elevator maintenance, water cooler service, pest control. The same customer is visited every N weeks at roughly the same time slot, and the value the customer pays for is the reliability of the schedule. This recipe covers schedule-to-Routal materialisation, customer-stable time slots, the webhook cycle that dispatches on optimization.succeeded and books the next visit on stop.reported, and the deviation patterns that keep recurring routes honest.

Who this is for

You operate a fleet where the schedule, not the order book, drives the day. Common shapes:

  • A butane / propane gas distributor swapping bottles on a quarterly rotation. Customer expects the truck to arrive within their contracted window every 90 days, full stop.
  • A vehicle inspection (ITV in Spain, MOT in the UK, TÜV in Germany) service that books recurring inspection slots for fleet customers: same garage, same time, same week of the month, year after year.
  • An elevator / lift maintenance company on a strict regulatory cadence: monthly inspections per cabin, and missing one creates a compliance liability.
  • A water-cooler / coffee-machine vendor topping up consumables and doing preventive maintenance every 4-6 weeks per location.
  • A pest control route servicing restaurants, hotels, supermarkets on a bi-weekly visit cycle to stay ahead of infestation.

What makes you different from event-driven operations:

  • Visits are scheduled weeks or months ahead. The integration doesn't react to an order arriving today; it materialises a known future schedule into Routal day-by-day.
  • The customer is paying for the schedule. If you miss a contracted visit or shift it by an hour, you've broken the product. The day's plan is much closer to a fixed itinerary than an optimization target.
  • Same customer, same slot, every cycle. Loyalty and predictability matter more than density. The optimizer is mostly arranging visits inside the constraints set by the customer's contract.

What the rhythm looks like

Calendar in the FSM → daily materialisation → dispatch on optimization.succeeded → execution:

T-N weeks                      T-1 day                  T (visit day)
─────────────────────────      ───────────────────────  ───────────────────────────
FSM holds the recurring        17:00  ⚡ Nightly job    06:00  Drivers open
schedule. For each contract:   1. Read FSM for visits          the app
- customer                        due tomorrow
- service type                 2. For each visit:       08:00-17:00  Visits run
- skill required                  - external_id =              on contracted slots
- cadence (every N weeks)           VISIT-<id>-<date>          → stop.reported
- contracted window               - push as stop               → FSM sets next_visit_at
  (e.g. Mon 09:00-11:00)          - chain_id when                = date + cadence
- next_visit_at                     multiple visits
                                    at same location    18:00  → route.finished
                               3. Start optimize/async         → incomplete visits:
                                                                 FSM books a make-up
                               17:02  ⚡ optimization.           within SLA
                                      succeeded
                               4. Dispatch every route  22:00  Reconciliation job
                                                               replays failed webhook
                                                               deliveries

Two notes specific to recurring services:

  • The external_id is a deterministic function of (customer, scheduledDate). This makes the nightly push idempotent: re-running it generates the same IDs, so duplicates are impossible.
  • time_windows are narrow. A visit contracted for "Monday 9-11am" is pushed with time_windows: [[32400, 39600]]. The optimizer respects it as a hard constraint; if the day's fleet can't fit all narrow-window stops, the run leaves some without a route. Investigate the schedule density, don't auto-relax.

The integration shape

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

FSM (recurring schedule database)
     │
     │  nightly cron: read visits due in look-ahead window
     ▼
[ visits: { customer_id, scheduled_date, contracted_slot, skill, location } ]
     │
     │  (1) generate deterministic external_ids
     ▼
[ stops: { external_id: 'VISIT-<customer>-<date>', time_windows, requires, ... } ]
     │
     │  (2) push to tomorrow's plan
     ▼
POST /v2/stops                              (idempotent: re-runs = no-op)
     │
     │  (3) optimize once: 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)
     │
     │  (5) webhooks during execution
     ▼
stop.reported  → completed: FSM sets next_visit_at, attaches POD, closes ticket
                 canceled: FSM schedules a make-up within SLA
route.finished → any stop left incomplete: FSM schedules a make-up
     │
     │  (6) nightly
     ▼
GET /v2/webhook/{id}/events?status=error → resend what you missed

The single biggest difference vs. the other recipes: the source of truth for the day's stops is not an order book, it's a calendar plus cadence rule per customer. Your integration's first job is to walk the calendar and generate visits; the second is to push them to Routal.

Nothing in this loop polls. The nightly 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://fsm.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 tomorrow's calendar-derived visits as stops. Each carries a
#     narrow window matching the customer's contracted slot and a skill
#     requirement matching the service type.
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": "VISIT-CUST-0042-2026-05-22",
      "label": "Acme Café, quarterly butane refill",
      "location": { "lat": 41.3851, "lng": 2.1734, "address": "Carrer Aragó 215, 08010 Barcelona" },
      "duration": 900,
      "time_windows": [[32400, 39600]],
      "phone": "+34699445566",
      "requires": ["butane-licensed"],
      "tasks": [
        { "label": "Swap the empty cylinders" },
        { "label": "Leak-test the regulator" }
      ]
    }
  ]'

# (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. The driver gets a magic-link email.
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
#     FSM 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://fsm.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) Materialise the calendar ─────────────────────────────────────────

type Visit = {
  customerId: string;
  scheduledDate: string;        // 'YYYY-MM-DD' in the project's local TZ
  customerName: string;
  lat: number;
  lng: number;
  address: string;
  phoneE164: string;
  slotFromSec: number;          // contracted window start (seconds from midnight)
  slotToSec: number;
  serviceDurationSec: number;
  skillRequired: string;        // e.g. 'butane-licensed'
};

/** Deterministic external_id makes the nightly push idempotent. */
function visitExternalId(visit: Visit): string {
  return `VISIT-${visit.customerId}-${visit.scheduledDate}`;
}

export async function materialiseDay(planId: string, visits: Visit[]) {
  if (visits.length === 0) return { pushed: 0 };

  const payload = visits.map((v) => ({
    external_id: visitExternalId(v),
    label: `${v.customerName}, ${v.scheduledDate}`,
    location: { lat: v.lat, lng: v.lng, address: v.address },
    duration: v.serviceDurationSec,
    time_windows: [[v.slotFromSec, v.slotToSec]] as [number, number][],
    phone: v.phoneE164,
    requires: [v.skillRequired],
    tasks: [{ label: 'Inspect the installation' }, { label: 'Check equipment serials' }],
  }));

  for (let i = 0; i < payload.length; i += 250) {
    const chunk = payload.slice(i, i + 250);
    const { error } = await routal.POST('/v2/stops', {
      params: { query: { ...key, plan_id: planId, project_id: PROJECT_ID } },
      body: chunk as never,
    });
    if (error) throw error;
  }
  return { pushed: payload.length };
}

// ── (2) Nightly job: start the run and return ────────────────────────────

/** Once per day and plan. No polling: the optimization.succeeded webhook picks up. */
export async function optimizeDay(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) 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 escalateUnassigned(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 onVisitReported(event.data);
      break;
    case 'routal.drivers.2.route.finished':
      for (const stop of event.data.stops ?? []) {
        // The route ended without closing the visit: book a make-up.
        if (stop.status === 'incomplete') await fsm.scheduleMakeUp(stop.external_id, { reason: 'incomplete' });
      }
      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);
  }
}

/** Contracted visits the run could not place: a person decides, never auto-relax. */
async function escalateUnassigned(planId: string) {
  const { data } = await routal.GET('/v2/plan/{id}/stops', {
    params: { path: { id: planId }, query: key },
  });
  const unassigned = ((data as Array<{ external_id?: string; route_id?: string }>) ?? []).filter((s) => !s.route_id);
  if (unassigned.length) await alertOps('Visits without a route', { visits: unassigned.map((s) => s.external_id) });
}

/** On stop.reported, book the next visit or a make-up from the latest report. */
async function onVisitReported(stop: any) {
  const report = stop.reports?.at(-1); // data is the stop; its latest report is the new one
  if (!report) return;
  switch (report.type) {
    case 'service_report_completed':
      // next_visit_at = this visit's scheduled date + cadence: a duplicate writes the same value.
      await fsm.completeVisit(stop.external_id, {
        signatureUrl: report.signature?.url,
        photoUrls: (report.images ?? []).map((i: { url: string }) => i.url),
      });
      break;
    case 'service_report_canceled':
      await fsm.scheduleMakeUp(stop.external_id, { reason: report.cancel_reason });
      break;
    case 'service_report_attempted':
      break; // the stop stays pending: the driver may come back; route.finished settles it
  }
}

// ── (4) 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://fsm.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) Materialise the calendar ─────────────────────────────────────────

def visit_external_id(visit: dict) -> str:
    return f"VISIT-{visit['customer_id']}-{visit['scheduled_date']}"


def materialise_day(plan_id: str, visits: list[dict]) -> dict:
    if not visits:
        return {"pushed": 0}

    payload = [
        {
            "external_id": visit_external_id(v),
            "label": f"{v['customer_name']}, {v['scheduled_date']}",
            "location": {"lat": v["lat"], "lng": v["lng"], "address": v["address"]},
            "duration": v["service_duration_sec"],
            "time_windows": [[v["slot_from_sec"], v["slot_to_sec"]]],
            "phone": v["phone"],
            "requires": [v["skill_required"]],
            "tasks": [{"label": "Inspect the installation"}, {"label": "Check equipment serials"}],
        }
        for v in visits
    ]

    for i in range(0, len(payload), 250):
        chunk = payload[i:i + 250]
        requests.post(
            f"{BASE}/v2/stops",
            params={**KEY, "plan_id": plan_id, "project_id": PROJECT_ID},
            json=chunk,
            timeout=60,
        ).raise_for_status()
    return {"pushed": len(payload)}


# ── (2) Nightly job: start the run and return ────────────────────────────

def optimize_day(plan_id: str) -> None:
    """Once per day and plan. No polling: the optimization.succeeded webhook picks up."""
    # 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) 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)
            escalate_unassigned(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":
        on_visit_reported(data)
    elif kind == "routal.drivers.2.route.finished":
        for stop in data.get("stops") or []:
            if stop.get("status") == "incomplete":
                # The route ended without closing the visit: book a make-up.
                fsm.schedule_make_up(stop["external_id"], reason="incomplete")

    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 escalate_unassigned(plan_id: str) -> None:
    """Contracted visits the run could not place: a person decides, never auto-relax."""
    stops = requests.get(f"{BASE}/v2/plan/{plan_id}/stops", params=KEY, timeout=30).json()
    unassigned = [s.get("external_id") for s in stops if not s.get("route_id")]
    if unassigned:
        alert_ops("Visits without a route", visits=unassigned)


def on_visit_reported(stop: dict) -> None:
    """On stop.reported, book the next visit or a make-up from the latest report."""
    reports = stop.get("reports") or []
    if not reports:
        return
    report = reports[-1]  # data is the stop; its latest report is the new one
    if report["type"] == "service_report_completed":
        # next_visit_at = this visit's scheduled date + cadence: a duplicate writes the same value.
        fsm.complete_visit(
            stop["external_id"],
            signature_url=(report.get("signature") or {}).get("url"),
            photo_urls=[i["url"] for i in report.get("images") or []],
        )
    elif report["type"] == "service_report_canceled":
        fsm.schedule_make_up(stop["external_id"], reason=report.get("cancel_reason"))
    # service_report_attempted: the stop stays pending; route.finished settles it.


# ── (4) 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, fsm and alertOps stand for your own storage, queue, FSM client and paging. processed and dispatched only need an insert and a lookup by id.

Tasks are checklist items: a label, plus a barcode when the driver must scan a known code. 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

Deterministic external_id: the load-bearing idempotency lever

For event-driven flows, idempotency is usually about handling duplicate webhooks. For recurring services, idempotency is also about safe cron retries.

A visit is uniquely identified by (customer_id, scheduled_date). Use that pair as the external_id:

external_id = `VISIT-${customerId}-${scheduledDate}`

Re-running the nightly materialisation must produce identical IDs. Routal's storage doesn't enforce uniqueness on external_id, but with deterministic generation + a search-before-create check on your side, duplicates become impossible:

async function materialiseVisitIdempotent(planId: string, visit: Visit) {
  const extId = visitExternalId(visit);
  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: extId, type: 'string' },
      ],
    } as never,
  });
  if ((data as { docs?: unknown[] })?.docs?.length) return { skipped: true };
  await materialiseDay(planId, [visit]);
  return { skipped: false };
}

The same external_id comes back in every stop.reported and route.finished webhook, so the FSM finds the visit without another read.

Skill matching: the technician fit per service type

Recurring services nearly always involve a technical skill (gas certification, elevator licensing, ITV authorisation, pesticide handling). The optimizer respects skill matching via requires (on the stop) and provides (on the vehicle / technician; it reads back as default_provides).

// technician vehicle, created with POST /v3/vehicles
{ provides: ['gas-licensed', 'butane-licensed', 'propane-licensed'] }

// visit stop
{ requires: ['butane-licensed'] }

Maintain the skill catalog in your FSM and mirror it into Routal vehicles nightly (or whenever certifications change): an existing technician is updated with PUT /v2/vehicle/{vehicle_id} and default_provides. A visit pushed with a requires no active vehicle satisfies comes back without a route after optimization.succeeded, the same outcome as a capacity overflow, with a different root cause. escalateUnassigned above lists those visits.

Missed visit handling: make-up SLA per contract

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 the FSM:

Latest report.typeStop statusFSM action
service_report_completedcompletedSet next_visit_at to the scheduled date plus the contract cadence (e.g., 28 days), attach the POD, close the service record.
service_report_attemptedpendingNothing yet. The driver may come back later in the day; wait for the next report or route.finished.
service_report_canceledcanceledThe visit was closed without the service. cancel_reason says why (nobody, wrong_address, missing_information, other). Create a make-up within the contract SLA; fix the customer record first when the reason is wrong_address or missing_information.

A visit the route ended without closing (customer not home, equipment unavailable, access denied, no time left) arrives as incomplete in route.finished. Create a make-up record for it in the FSM within the contract SLA.

Each contract usually has a make-up SLA field (1 day for compliance-bound services like elevators, 3-5 days for grooming-style services like pest control). The FSM enforces it.

Set next_visit_at from the visit's scheduled date plus the cadence, never from today or from the current next_visit_at. A duplicate stop.reported that slips past the processed table then writes the same value twice instead of skipping a cycle.

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 lost stop.reported is a customer whose next visit never gets booked. The nightly replayFailedDeliveries job above reads yesterday's failed attempts from GET /v2/webhook/{id}/events?status=error, skips the ones your processed table already has (a later retry got through) and resends the rest. A resent payload keeps its id, so running the job twice is harmless. See Webhooks → Delivery log.

Close the day with a check that every visit of the plan has either a next_visit_at or a make-up in the FSM. Anything left is a webhook that never arrived: read the stop with GET /v2/stop/{stop_id}.

Look-ahead window: pick a horizon and stick to it

Generating too few days at once = more pushes, more chance of cron failures shifting the plan window. Too many days = lots of stops in distant-future plans that may need re-adjustment if customers reschedule.

Pragmatic defaults:

  • Daily push, T+1 horizon. Simple, robust, but every reschedule means a customer-service human in the loop.
  • Weekly push, T+7 horizon. Most common. Schedule for the whole week on Sunday night; customer reschedules trigger a targeted stop.move / stop.delete + re-create on the affected day's plan.
  • Monthly push, T+30 horizon. Only for very stable contracts (regulatory inspections, multi-year service agreements). Reschedules are rare and manual.

Time-window enforcement: narrow is the product

A customer paying for "Monday morning service" doesn't accept the technician arriving Tuesday afternoon. The integration must push narrow time_windows that match the contracted slot. If the optimizer can't fit them all, the right behaviour is to escalate, not to relax.

function visitTimeWindow(visit: Visit): [number, number][] {
  // 30-minute buffer around the contracted slot for travel + greeting.
  return [[visit.slotFromSec, visit.slotToSec + 1800]];
}

If a particular customer is flexible ("any time on Monday"), encode it explicitly: time_windows: [[0, 86400]]. Don't widen everyone to "8am-6pm" by default: that erodes the schedule discipline that is your product.

Observability: the metrics that matter

MetricWhat it tells you
recurring.visits_materialised_total{date}Visits pushed for a given execution date. Match expected = good.
recurring.missed_visits_total{reason}Canceled + incomplete visits, grouped by cancel_reason. Tells you if churn is technician-side, customer-side, or operations-side.
recurring.make_up_sla_breaches_totalMake-up visits not scheduled within the contract SLA. Goes to compliance dashboard.
recurring.window_breach_rateStops where the driver arrived outside the contracted slot. Headline customer-satisfaction signal.
recurring.no_result_found_rate{day}Optimizer failures. Sustained > 2% = schedule density exceeds fleet capacity.
recurring.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.no_result_foundSchedule density exceeds fleet capacity, OR required skill unavailable on any active vehicle.Either scale the fleet for that day, defer flexible visits, or escalate compliance-bound visits to a supervisor.
highway.optimization.error.sync_optimization_already_progressAnother optimization is still running for the same plan.Wait for its optimization.succeeded or optimization.failed webhook. Do not retry.
highway.webhook.error.invalid_urlThe webhook url is not public: localhost, a private IP, an internal host, or credentials in the URL.Use a public HTTPS URL; a tunnel such as ngrok for local development.
highway.webhook.error.send_testPOST /v2/webhook/{id}/test got no 2xx from your endpoint within 10 seconds.Fix the endpoint before the first real event: check the token, the route and the response time.
highway.stop.error.move_not_pending_stopsTried to reschedule a visit that is no longer pending.The visit already happened; create a make-up via the FSM make-up workflow, don't move.
highway.stop.error.custom_fields_invalidCustom fields (contract_id, service_type) don't match project schema.Update the project's custom-field definitions, then re-push.
400 Bad Request on time_windowContracted slot was modelled with seconds outside [0, 172800].Verify slot conversion to seconds from midnight; cap at [0, 86400] for single-day windows.
highway.optimization.error.too_much_requestsOptimizer rate-limited.Wait 60-90s; if persistent on a large plan, contact support about dedicated capacity.

Next steps

  • Field service with appointments: the closest sibling recipe. If your operation is more order-driven (tickets arrive, technician dispatched) than calendar-driven (visit due every N weeks), start there.
  • Webhooks: the full cycle, event catalog, retries and delivery log. stop.reported drives the FSM's next-visit scheduling, so keep the handler fast and idempotent.
  • Idempotency: deterministic external_id is the load-bearing pattern; this recipe leans on it harder than any other.
  • Capacitated distribution: when your visits also carry physical goods (gas bottles, replacement parts) with hard capacity limits, combine the schedule materialisation here with the constraint matrix there.