How to receive shipment tracking webhooks from carriers or a tracking aggregator, verify them, drop duplicates, handle out-of-order events and a polling fallback, and publish status changes, built with Encore.
Carriers push an event on every scan, and customers expect a shipment page that stays correct. A handler looks like one POST route until the same scan arrives three times, delivered lands before out-for-delivery, and a slow database gets the endpoint marked as failing.
This guide designs the receiver around those cases and then builds it with Encore.
EasyPost's webhook docs describe the contract most providers share: events are sent as an HTTP POST, the endpoint must return a 2xx status to confirm receipt, and endpoints that repeatedly fail may be disabled. The handler therefore verifies the signature, writes the raw event and returns, and everything else reads from the stored row.
Verification needs the exact bytes the provider signed, so read the raw body first and parse JSON afterwards. Compare the HMAC with a constant-time function such as Node's timingSafeEqual, and reject anything that fails with a 401 before any database call.
Providers retry, and carriers rescan, so the same event ID can arrive more than once. A unique constraint on the provider's event ID turns the second delivery into a no-op. Ordering needs a second rule: each event carries the time the scan happened, and the shipment row changes only when that time is newer than the one already applied. A delivered shipment then stays delivered when an older in-transit scan arrives late.
Keep the events table append-only, since it is the audit trail for customer disputes and lets you recompute statuses if you change the mapping.
Carriers each describe a parcel differently, and aggregators already collapse them: EasyPost's tracker statuses include pre_transit, in_transit, out_for_delivery, delivered, return_to_sender and failure. Map whatever you receive to a small internal set in one function, so the rest of the product reads one vocabulary and a new carrier means one new mapping.
Webhooks can be lost, and some carriers update slowly. A scheduled job that fetches the latest status for shipments with no event in a day or so closes the gap, and it feeds the same ingest function, so the dedupe and ordering rules apply to polled data too.
Encore is a backend framework with built-in infrastructure, and the tracking service declares its Postgres database, the webhook signing key as a secret, a status-change Pub/Sub topic and a raw endpoint for the webhook in code, and provisions the resources in your AWS or GCP account.

Run in your terminal to get started locally.
The secret values are stored by Encore, not in the repository.
-- tracking/migrations/1_create_tracking.up.sql
CREATE TABLE shipments (
id BIGSERIAL PRIMARY KEY,
tracking_code TEXT NOT NULL UNIQUE,
status TEXT NOT NULL DEFAULT 'label_created',
last_event_at TIMESTAMPTZ,
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE TABLE tracking_events (
event_id TEXT PRIMARY KEY, -- provider event ID, so repeats are dropped
tracking_code TEXT NOT NULL,
raw_status TEXT NOT NULL,
occurred_at TIMESTAMPTZ NOT NULL,
payload JSONB NOT NULL,
received_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
// tracking/tracking.ts
import { api } from "encore.dev/api";
import { SQLDatabase } from "encore.dev/storage/sqldb";
import { Topic } from "encore.dev/pubsub";
import { secret } from "encore.dev/config";
import { createHmac, timingSafeEqual } from "node:crypto";
const db = new SQLDatabase("tracking", { migrations: "./migrations" });
const webhookSecret = secret("TrackingWebhookSecret");
interface StatusChanged {
trackingCode: string;
status: string;
occurredAt: string;
}
export const statusChanged = new Topic<StatusChanged>("shipment-status-changed", {
deliveryGuarantee: "at-least-once",
});
// One place that maps provider wording to the statuses the product uses.
function normalize(raw: string): string {
switch (raw) {
case "pre_transit": return "label_created";
case "in_transit": return "in_transit";
case "out_for_delivery": return "out_for_delivery";
case "delivered": return "delivered";
case "return_to_sender": return "returned";
case "failure": return "exception";
default: return "unknown";
}
}
interface TrackingEvent {
id: string;
trackingCode: string;
status: string;
occurredAt: string;
}
// Shared by the webhook and the polling fallback, so both get the same
// duplicate and ordering rules.
export async function ingest(evt: TrackingEvent, payload: unknown): Promise<void> {
// Commit only after the publish, so a failed publish rolls back and the retry runs it again.
// A commit that fails after the publish can repeat a message, so subscribers must be idempotent.
const tx = await db.begin();
try {
const inserted = await tx.queryRow<{ event_id: string }>`
INSERT INTO tracking_events (event_id, tracking_code, raw_status, occurred_at, payload)
VALUES (${evt.id}, ${evt.trackingCode}, ${evt.status}, ${evt.occurredAt}, ${JSON.stringify(payload)}::jsonb)
ON CONFLICT (event_id) DO NOTHING
RETURNING event_id`;
if (!inserted) {
await tx.rollback();
return; // duplicate delivery
}
const status = normalize(evt.status);
// Only a newer scan may move the shipment, so late events cannot go backwards.
const moved = await tx.queryRow<{ id: number }>`
UPDATE shipments
SET status = ${status}, last_event_at = ${evt.occurredAt}, updated_at = now()
WHERE tracking_code = ${evt.trackingCode}
AND (last_event_at IS NULL OR last_event_at < ${evt.occurredAt})
RETURNING id`;
if (moved) {
await statusChanged.publish({
trackingCode: evt.trackingCode,
status,
occurredAt: evt.occurredAt,
});
}
await tx.commit();
} catch (err) {
await tx.rollback();
throw err;
}
}
export const webhook = api.raw(
{ expose: true, method: "POST", path: "/webhooks/tracking" },
async (req, resp) => {
const chunks: Buffer[] = [];
for await (const chunk of req) chunks.push(chunk as Buffer);
const body = Buffer.concat(chunks);
const expected = createHmac("sha256", webhookSecret()).update(body).digest("hex");
const given = String(req.headers["x-signature"] ?? "");
const ok =
given.length === expected.length &&
timingSafeEqual(Buffer.from(given), Buffer.from(expected));
if (!ok) {
resp.statusCode = 401;
resp.end("bad signature");
return;
}
const payload = JSON.parse(body.toString("utf8"));
await ingest(
{
id: payload.id,
trackingCode: payload.tracking_code,
status: payload.status,
occurredAt: payload.occurred_at,
},
payload,
);
resp.statusCode = 204;
resp.end();
},
);
With an encore.service.ts file in tracking/, encore run starts a local Postgres, applies the migration and serves the endpoint, so you can post signed sample events from a test and check that a repeated or older event changes nothing. On deploy, the database runs on RDS or Cloud SQL and the topic on SNS and SQS or GCP Pub/Sub, and Encore provisions an IAM role for the service. The polling fallback is a cron job that calls ingest; cron jobs are managed by the Encore platform and do not run locally or in preview environments.
A coding agent adding a customer notification service subscribes to shipment-status-changed in the same change and runs it locally, with no queue to create and no permissions to wire up separately.
Best fit: Teams that need tracking updates in their own product and want signature checks, ordering rules and the infrastructure kept together in one repository.
On AWS the same receiver needs an API Gateway or ALB endpoint, a container or Lambda function, an RDS database, an SNS topic with SQS queues per consumer, the signing key in Secrets Manager and IAM for each piece, written in Terraform. The TypeScript stays close to the code above, and the difference is the infrastructure definitions around it.
Store every event by its provider event ID with a unique constraint to drop duplicates, and only update the shipment when the event's occurred-at time is newer than the last one applied. Keep the raw event either way, so you can replay history if the mapping changes.
Compute an HMAC-SHA256 of the raw request body with the shared webhook secret and compare it to the signature header with a constant-time comparison. Read the raw bytes before any JSON parsing, because re-serializing the body changes the signature.
Return a 2xx status as soon as the event is stored, and do the slow work afterwards. Providers such as EasyPost treat only a 2xx response as received, and endpoints that keep failing may be disabled automatically.
With Encore, declare a raw webhook endpoint, a Postgres database, the webhook secret and a status-change Pub/Sub topic in the service. Encore provisions the database and topic in your AWS or GCP account, and secret values are stored by Encore rather than in the repository.
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.