Nov 23, 20268 min read

Build Shipment Exception Alerts for a Logistics Platform

Catch delivery problems before the customer calls: normalize carrier tracking events, open one exception per shipment and problem, detect silent failures like missing scans and missed promise dates, and alert operations, with a TypeScript example.

Illustration for Build Shipment Exception Alerts for a Logistics Platform

Customers rarely complain about a parcel that arrives on time. They call when it sits in a depot for three days, misses the delivery date or goes back to the sender, and the call goes better when operations already knows.

This guide builds the backend that catches those cases: normalized carrier events, exception records, a sweep for silent failures and alerts, with TypeScript code using Encore.

The Exception Alerts Backend at a Glance

PieceWhat it doesBuilt with
Tracking webhookReceives carrier events, ignores duplicatesAPI endpoint
ShipmentsLatest normalized status, last scan, promised datePostgres
ExceptionsOne open record per shipment and kindPostgres
SweepOpens exceptions for missing scans and late shipmentsCron
AlertsPosts new exceptions to the operations channelPub/Sub

What Counts as an Exception?

Two kinds of problems need handling, and the first is what carriers report: tracking aggregators expose statuses such as failure and return_to_sender in EasyPost trackers, and AttemptFail and Exception (customs hold, undelivered, returned) in AfterShip's delivery statuses. Each carrier names them differently, so map them to your own small set once, in the adapter for each carrier or aggregator.

The second kind is silent, because a parcel that falls off a conveyor produces no event at all, and AfterShip only marks a shipment Expired after 30 days without tracking information. Your backend has to notice the absence of scans and the passing of the promised date itself, which is what the sweep below does.

KindSourceTypical trigger
carrier_exceptionCarrier eventCustoms hold, damage, return to sender
failed_attemptCarrier eventNobody home, access problem
no_scanSweepNo event for 48 hours while in transit
lateSweepPast the promised delivery date

The Data Model

-- exceptions/migrations/1_create_exceptions.up.sql CREATE TABLE shipments ( id text PRIMARY KEY, carrier text NOT NULL, tracking_number text NOT NULL, promised_by date NOT NULL, status text NOT NULL DEFAULT 'in_transit', last_event_at timestamptz, created_at timestamptz NOT NULL DEFAULT now() ); CREATE TABLE tracking_events ( shipment_id text NOT NULL REFERENCES shipments (id), carrier_event_id text NOT NULL, status text NOT NULL, detail text NOT NULL DEFAULT '', occurred_at timestamptz NOT NULL, PRIMARY KEY (shipment_id, carrier_event_id) ); CREATE TABLE shipment_exceptions ( id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, shipment_id text NOT NULL REFERENCES shipments (id), kind text NOT NULL CHECK (kind IN ('carrier_exception', 'failed_attempt', 'no_scan', 'late')), detail text NOT NULL DEFAULT '', opened_at timestamptz NOT NULL DEFAULT now(), resolved_at timestamptz ); -- At most one open exception per shipment and kind. CREATE UNIQUE INDEX shipment_exceptions_one_open ON shipment_exceptions (shipment_id, kind) WHERE resolved_at IS NULL; CREATE INDEX shipments_active ON shipments (last_event_at) WHERE status NOT IN ('delivered', 'returned');

The partial unique index is what keeps alerts quiet: a shipment can only have one open no_scan exception, so the sweep running every 30 minutes does not alert again, and once the exception is resolved a new one can open if the parcel stalls a second time.

Building It with Encore

Encore

Encore is a backend framework with built-in infrastructure, so the database, the alert topic, the sweep schedule and the webhook token below are declared in TypeScript. encore run starts Postgres and Pub/Sub locally, and deploying creates them in your own AWS or GCP account.

Get started
brew install encoredev/tap/encore &&
encore app create
Copy

Run in your terminal to get started locally.

Receiving Tracking Events

// exceptions/encore.service.ts import { Service } from "encore.dev/service"; export default new Service("exceptions");
// exceptions/exceptions.ts import { api, APIError, Header } from "encore.dev/api"; import { secret } from "encore.dev/config"; import { Topic } from "encore.dev/pubsub"; import { SQLDatabase } from "encore.dev/storage/sqldb"; import { timingSafeEqual } from "node:crypto"; const db = new SQLDatabase("exceptions", { migrations: "./migrations" }); const webhookToken = secret("TrackingWebhookToken"); type Status = | "in_transit" | "out_for_delivery" | "failed_attempt" | "exception" | "returned" | "delivered"; export type ExceptionKind = "carrier_exception" | "failed_attempt" | "no_scan" | "late"; export interface ExceptionOpened { exceptionId: number; shipmentId: string; kind: ExceptionKind; detail: string; } export const exceptionOpened = new Topic<ExceptionOpened>("shipment-exception-opened", { deliveryGuarantee: "at-least-once", }); interface TrackingEvent { token: Header<"X-Webhook-Token">; shipmentId: string; carrierEventId: string; status: Status; // already mapped from the carrier's own codes detail: string; occurredAt: string; } function validToken(got: string): boolean { const a = Buffer.from(got); const b = Buffer.from(webhookToken()); return a.length === b.length && timingSafeEqual(a, b); } async function openException(shipmentId: string, kind: ExceptionKind, detail: string) { const row = await db.queryRow<{ id: number }>` INSERT INTO shipment_exceptions (shipment_id, kind, detail) VALUES (${shipmentId}, ${kind}, ${detail}) ON CONFLICT (shipment_id, kind) WHERE resolved_at IS NULL DO NOTHING RETURNING id `; if (row) { await exceptionOpened.publish({ exceptionId: Number(row.id), shipmentId, kind, detail }); } } async function resolveException(shipmentId: string, kind: ExceptionKind) { await db.exec` UPDATE shipment_exceptions SET resolved_at = now() WHERE shipment_id = ${shipmentId} AND kind = ${kind} AND resolved_at IS NULL `; } export const trackingEvent = api( { expose: true, method: "POST", path: "/tracking/events" }, async (e: TrackingEvent): Promise<void> => { if (!validToken(e.token)) { throw APIError.unauthenticated("invalid webhook token"); } const fresh = await db.queryRow` INSERT INTO tracking_events (shipment_id, carrier_event_id, status, detail, occurred_at) VALUES (${e.shipmentId}, ${e.carrierEventId}, ${e.status}, ${e.detail}, ${e.occurredAt}::timestamptz) ON CONFLICT DO NOTHING RETURNING shipment_id `; if (!fresh) { return; // carrier sent the same event again } // Events can arrive out of order, so only a newer event changes the status. await db.exec` UPDATE shipments SET status = CASE WHEN last_event_at IS NULL OR ${e.occurredAt}::timestamptz >= last_event_at THEN ${e.status} ELSE status END, last_event_at = GREATEST(last_event_at, ${e.occurredAt}::timestamptz) WHERE id = ${e.shipmentId} `; // Any scan means the parcel is moving again. await resolveException(e.shipmentId, "no_scan"); switch (e.status) { case "exception": case "returned": await openException(e.shipmentId, "carrier_exception", e.detail); break; case "failed_attempt": await openException(e.shipmentId, "failed_attempt", e.detail); break; case "delivered": for (const kind of ["carrier_exception", "failed_attempt", "late"] as const) { await resolveException(e.shipmentId, kind); } break; } }, );

The webhook is idempotent because the carrier's event ID is part of the primary key, and carriers and aggregators do resend events. Comparing the token with timingSafeEqual avoids leaking it through response timing, and if your provider signs payloads, verify the signature instead, as in webhook signature verification.

Finding Silent Failures

// exceptions/sweep.ts import { api } from "encore.dev/api"; import { CronJob } from "encore.dev/cron"; import { SQLDatabase } from "encore.dev/storage/sqldb"; import { exceptionOpened, ExceptionKind } from "./exceptions"; const db = SQLDatabase.named("exceptions"); export const sweep = api({}, async (): Promise<{ opened: number }> => { const rows = db.query<{ id: number; shipment_id: string; kind: ExceptionKind; detail: string }>` INSERT INTO shipment_exceptions (shipment_id, kind, detail) SELECT id, 'no_scan', 'no carrier scan for 48 hours' FROM shipments WHERE status NOT IN ('delivered', 'returned') AND COALESCE(last_event_at, created_at) < now() - interval '48 hours' UNION ALL SELECT id, 'late', 'past promised date ' || promised_by FROM shipments WHERE status NOT IN ('delivered', 'returned') AND promised_by < current_date ON CONFLICT (shipment_id, kind) WHERE resolved_at IS NULL DO NOTHING RETURNING id, shipment_id, kind, detail `; let opened = 0; for await (const r of rows) { await exceptionOpened.publish({ exceptionId: Number(r.id), shipmentId: r.shipment_id, kind: r.kind, detail: r.detail, }); opened++; } return { opened }; }); new CronJob("exception-sweep", { title: "Open exceptions for stalled and late shipments", every: "30m", endpoint: sweep, });

COALESCE(last_event_at, created_at) covers labels that were created but never scanned, a common silent failure when a parcel is not handed over. Forty-eight hours is a starting point, and since express parcels deserve a shorter threshold than freight, a threshold column per service level is a natural next step.

The cron job is managed by the Encore platform and runs in deployed environments, not under encore run or in preview environments, so locally you call sweep from the local development dashboard or from a test.

Alerting Operations

// exceptions/alerts.ts import { secret } from "encore.dev/config"; import { Subscription } from "encore.dev/pubsub"; import { exceptionOpened } from "./exceptions"; const opsWebhookURL = secret("OpsSlackWebhookURL"); new Subscription(exceptionOpened, "alert-ops", { handler: async (e) => { const res = await fetch(opsWebhookURL(), { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ text: `Shipment ${e.shipmentId}: ${e.kind.replace("_", " ")} (${e.detail})`, }), }); if (!res.ok) { throw new Error(`alert webhook returned ${res.status}`); } }, });

The handler posts to a Slack incoming webhook, and a failed post throws so Pub/Sub retries it. Delivery is at least once, so a rare duplicate alert is possible. A second subscription on the same topic can email the customer about failed attempts without touching this one, as the Pub/Sub docs describe. Publishing happens after the insert, and if a lost alert matters more than a duplicate, the transactional outbox pattern closes that gap.

On AWS the database runs on RDS and the topic on SNS with SQS, in your own account, and Encore provisions an IAM role for the service, or a service account on GCP, as the AWS infrastructure docs describe. Quiqup built a scalable platform connecting order sources, fulfillment centers, and delivery partners, as its case study describes. Adding a new exception kind, such as "out for delivery too long", is a migration for the check constraint, one more SELECT in the sweep and a test, and a coding agent can write and run all three against the local database in a single change.

Best fit: logistics and delivery platforms that want carrier problems and silent stalls in front of operations within the hour, running in their own AWS or GCP account.

Things to Decide Early

  • Thresholds per service level. Same-day, express and freight need different no-scan windows and grace periods after the promised date.
  • Ownership. Assign exceptions to a team or person and track time to resolution, or the alerts channel turns into noise.
  • Customer messaging. Decide which kinds the customer hears about proactively, usually failed attempts and late deliveries.
  • Carrier mapping. Keep the mapping from carrier codes to your statuses in one place and log unmapped codes, which appear whenever a carrier changes its API.
  • Business days. A parcel picked up on Friday evening may not scan until Monday, so decide whether weekends count toward the no-scan window.

Frequently asked questions

What is a shipment exception?

A shipment exception is any event that puts a delivery at risk: a failed delivery attempt, a customs hold, damage, an address problem, a return to sender, or a parcel that stops getting scans or misses its promised date. Carriers report some of these as statuses, the rest you detect yourself.

How do I detect shipments that are stuck without a carrier exception?

Run a periodic job that looks for undelivered shipments with no tracking event in the last 48 hours, or past their promised delivery date, and opens an exception for each. Carriers do not send an event for a parcel that stopped moving, so this check has to live in your backend.

How do I avoid duplicate alerts for the same shipment problem?

Keep exceptions in a table with a partial unique index on shipment and kind where the exception is unresolved, and insert with ON CONFLICT DO NOTHING. Only a newly opened exception triggers an alert, and a resolved one can open again later.

How do I schedule the exception sweep with Encore?

Declare a CronJob that calls the sweep endpoint, for example every 30 minutes. Encore cron jobs are managed by the Encore platform and run in deployed environments, not locally or in preview environments, so locally you call the endpoint directly from the local development dashboard or a test.

Deploy to your cloud on AWS and Google Cloud
without managing infrastructure

Encore lets developers and agents define application infrastructure directly in code, then automatically provisions it from local development to production in your AWS or GCP account.

~/orders — claude
Claude Code
Claude Code v2.1.180Opus 5.5~/orders