How to keep your own copy of Shopify orders current: HMAC verification on the raw body, a five-second response budget, duplicate and out-of-order webhooks, an hourly reconciliation job on the GraphQL Admin API, and an idempotent write path on Postgres.

A brand that runs on Shopify usually needs its own copy of orders, for a warehouse system, a 3PL integration, finance reporting or a custom loyalty program, and the copy has to keep up as orders are paid, edited, fulfilled and refunded.
Webhooks are the obvious feed, but they arrive out of order, sometimes twice, and not always at all. This guide builds the sync service on Postgres, from the signed webhook to the reconciliation job that fills the gaps.
Shopify's webhook best practices say plainly that an app should not rely on receiving every webhook and should run reconciliation jobs, and that ordering is not guaranteed within a topic or across topics for the same resource.
The troubleshooting guide adds the numbers that shape the design: a delivery fails if the app does not respond within five seconds, Shopify retries up to eight times over four hours, and a subscription that keeps failing is removed, at which point the shop silently stops sending you orders.
The endpoint only accepts the delivery: it reads the raw body, verifies the base64 HMAC in X-Shopify-Hmac-Sha256 with the app's client secret as the HTTPS delivery docs describe, inserts the X-Shopify-Webhook-Id into a table with a unique key, and puts the order on a queue. Anything slower, such as calling a warehouse API or recalculating loyalty points, happens in a consumer that can retry for minutes without Shopify noticing.
Out-of-order delivery is handled at write time, where each order row keeps Shopify's updated_at and the upsert only replaces the row when the incoming version is newer, so a delayed orders/updated for the unpaid state cannot overwrite the paid state that arrived first.
An hourly job asks the GraphQL Admin API for every order updated since the newest updated_at already stored, with a ten-minute overlap, sorted by UPDATED_AT and paged by cursor. The same upsert writes the results, so an order seen by both the webhook and the job is written once and the newer version wins.
By default the Admin API only returns orders from the last 60 days, and an initial backfill of older history needs the read_all_orders scope, which has to be requested for the app.
Encore is a backend framework with built-in infrastructure, so the orders table, the queue between the webhook and the writer, the reconciliation schedule and the Shopify credentials are all declared in the sync service and provisioned in your own AWS or GCP account. On AWS that means RDS and SNS with SQS, and on GCP Cloud SQL and Pub/Sub, as the infrastructure docs describe. Commerce companies such as Groupon, which builds its new development on Encore, and Bookshop.org use it in production.

Run in your terminal to get started locally.
The service below uses a raw endpoint so the HMAC is checked against the exact bytes Shopify signed, a subscription for the idempotent write and a cron job for reconciliation:
// shopify/webhooks.ts
import { api } from "encore.dev/api";
import { secret } from "encore.dev/config";
import { SQLDatabase } from "encore.dev/storage/sqldb";
import { Topic, Subscription } from "encore.dev/pubsub";
import { CronJob } from "encore.dev/cron";
import { createHmac, timingSafeEqual } from "node:crypto";
const db = new SQLDatabase("shopify", { migrations: "./migrations" });
const clientSecret = secret("ShopifyClientSecret");
const adminToken = secret("ShopifyAdminToken");
const shopDomain = secret("ShopifyShopDomain"); // for example "acme.myshopify.com"
interface ShopifyOrder {
id: number;
name: string;
email: string | null;
financial_status: string | null;
fulfillment_status: string | null;
total_price: string;
currency: string;
updated_at: string;
}
interface OrderChanged {
shop: string;
order: ShopifyOrder;
}
const orderChanged = new Topic<OrderChanged>("shopify-order-changed", {
deliveryGuarantee: "at-least-once",
});
function validHmac(body: Buffer, header: string | undefined): boolean {
if (!header) return false;
const expected = createHmac("sha256", clientSecret()).update(body).digest();
const given = Buffer.from(header, "base64");
return given.length === expected.length && timingSafeEqual(given, expected);
}
// Receives orders/create and orders/updated. Shopify fails a delivery that takes
// longer than five seconds, so this only verifies, deduplicates and enqueues.
export const orderWebhook = api.raw(
{ expose: true, method: "POST", path: "/webhooks/shopify/orders" },
async (req, resp) => {
const chunks: Buffer[] = [];
for await (const chunk of req) chunks.push(chunk as Buffer);
const body = Buffer.concat(chunks);
if (!validHmac(body, req.headers["x-shopify-hmac-sha256"] as string | undefined)) {
resp.writeHead(401).end();
return;
}
const webhookId = req.headers["x-shopify-webhook-id"] as string | undefined;
const shop = req.headers["x-shopify-shop-domain"] as string;
// Record the delivery first. A row with published = false can be retried;
// only a completed publish suppresses a later Shopify delivery.
if (webhookId) {
const row = await db.queryRow<{ published: boolean }>`
INSERT INTO received_webhooks (webhook_id, topic, published)
VALUES (${webhookId}, ${req.headers["x-shopify-topic"] as string}, false)
ON CONFLICT (webhook_id) DO UPDATE SET topic = received_webhooks.topic
RETURNING published`;
if (row?.published) {
resp.writeHead(200).end();
return;
}
}
await orderChanged.publish({ shop, order: JSON.parse(body.toString("utf8")) as ShopifyOrder });
if (webhookId) {
await db.exec`
UPDATE received_webhooks SET published = true WHERE webhook_id = ${webhookId}`;
}
resp.writeHead(200).end();
},
);
// Webhooks can arrive out of order, so an older version never overwrites a newer one.
async function upsertOrder(shop: string, o: ShopifyOrder): Promise<void> {
await db.exec`
INSERT INTO orders (shop, shopify_id, name, email, financial_status, fulfillment_status,
total_price, currency, shopify_updated_at)
VALUES (${shop}, ${o.id}, ${o.name}, ${o.email}, ${o.financial_status}, ${o.fulfillment_status},
${o.total_price}::numeric, ${o.currency}, ${o.updated_at}::timestamptz)
ON CONFLICT (shop, shopify_id) DO UPDATE SET
name = EXCLUDED.name,
email = EXCLUDED.email,
financial_status = EXCLUDED.financial_status,
fulfillment_status = EXCLUDED.fulfillment_status,
total_price = EXCLUDED.total_price,
currency = EXCLUDED.currency,
shopify_updated_at = EXCLUDED.shopify_updated_at,
synced_at = now()
WHERE orders.shopify_updated_at < EXCLUDED.shopify_updated_at`;
}
const _ = new Subscription(orderChanged, "store-order", {
handler: async ({ shop, order }) => upsertOrder(shop, order),
retryPolicy: { minBackoff: "5s", maxBackoff: "5m", maxRetries: 10 },
});
// Shopify recommends reconciliation jobs because webhooks are not guaranteed.
// This pulls every order updated since the last run through the GraphQL Admin API.
export const reconcileOrders = api({ expose: false }, async (): Promise<{ synced: number }> => {
const shop = shopDomain();
// Advance a durable scan cursor only after this window is fully processed.
// Do not derive the bound from MAX(shopify_updated_at) in orders, which can
// skip a missed update that sits behind a later stored row.
const windowEnd = new Date();
const scanState = await db.queryRow<{ scanned_until: Date }>`
SELECT scanned_until FROM reconcile_cursors WHERE shop = ${shop}`;
const sinceDate = scanState?.scanned_until
?? new Date(windowEnd.getTime() - 7 * 24 * 60 * 60 * 1000);
// Overlap by ten minutes to cover clock skew between Shopify and this database.
const since = new Date(sinceDate.getTime() - 10 * 60 * 1000).toISOString();
let cursor: string | null = null;
let synced = 0;
do {
const res = await fetch(`https://${shop}/admin/api/2026-10/graphql.json`, {
method: "POST",
headers: { "Content-Type": "application/json", "X-Shopify-Access-Token": adminToken() },
body: JSON.stringify({
query: `query ($q: String!, $after: String) {
orders(first: 100, after: $after, query: $q, sortKey: UPDATED_AT) {
pageInfo { hasNextPage endCursor }
nodes {
legacyResourceId name email updatedAt
displayFinancialStatus displayFulfillmentStatus
totalPriceSet { shopMoney { amount currencyCode } }
}
}
}`,
variables: { q: `updated_at:>'${since}'`, after: cursor },
}),
});
if (!res.ok) throw new Error(`Shopify returned ${res.status}`);
const json = (await res.json()) as any;
if (json.errors) throw new Error(JSON.stringify(json.errors));
const page = json.data.orders;
for (const n of page.nodes) {
await upsertOrder(shop, {
id: Number(n.legacyResourceId),
name: n.name,
email: n.email,
financial_status: n.displayFinancialStatus?.toLowerCase() ?? null,
// Webhook payloads use null for unfulfilled orders, so match that here.
fulfillment_status:
n.displayFulfillmentStatus && n.displayFulfillmentStatus !== "UNFULFILLED"
? n.displayFulfillmentStatus.toLowerCase()
: null,
total_price: n.totalPriceSet.shopMoney.amount,
currency: n.totalPriceSet.shopMoney.currencyCode,
updated_at: n.updatedAt,
});
synced++;
}
cursor = page.pageInfo.hasNextPage ? page.pageInfo.endCursor : null;
} while (cursor);
await db.exec`
INSERT INTO reconcile_cursors (shop, scanned_until)
VALUES (${shop}, ${windowEnd})
ON CONFLICT (shop) DO UPDATE SET scanned_until = EXCLUDED.scanned_until`;
return { synced };
});
const _reconcile = new CronJob("reconcile-shopify-orders", {
title: "Backfill orders that webhooks missed",
every: "1h",
endpoint: reconcileOrders,
});
-- shopify/migrations/1_create_orders.up.sql
CREATE TABLE received_webhooks (
webhook_id TEXT PRIMARY KEY,
topic TEXT NOT NULL,
published BOOLEAN NOT NULL DEFAULT false,
received_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE TABLE orders (
shop TEXT NOT NULL,
shopify_id BIGINT NOT NULL,
name TEXT NOT NULL,
email TEXT,
financial_status TEXT,
fulfillment_status TEXT,
total_price NUMERIC(12, 2) NOT NULL,
currency TEXT NOT NULL,
shopify_updated_at TIMESTAMPTZ NOT NULL,
synced_at TIMESTAMPTZ NOT NULL DEFAULT now(),
PRIMARY KEY (shop, shopify_id)
);
CREATE INDEX orders_by_updated ON orders (shop, shopify_updated_at);
CREATE TABLE reconcile_cursors (
shop TEXT PRIMARY KEY,
scanned_until TIMESTAMPTZ NOT NULL
);
encore run starts Postgres, applies the migration and runs the topic locally, so a signed test payload posted with curl goes through verification, deduplication and the upsert, and the local traces show each step. The cron job does not run locally, so reconcileOrders is tested by calling it directly against a development store, while on a deployed environment Encore runs it hourly with no extra infrastructure, as the cron docs explain. The raw endpoint docs cover reading the request body, and the secrets docs cover setting ShopifyClientSecret and the Admin API token per environment.
To deploy, connect your AWS or GCP account as described in Connect your cloud account, push, and register https://<your-api>/webhooks/shopify/orders for the orders/create and orders/updated topics.
When an AI coding agent adds refunds/create, it writes a second raw endpoint and a migration in the same change and can post a signed payload to it locally, while the client secret stays in Encore's secret storage and never appears in the repository it is working in.
Best fit: Commerce teams that want Shopify orders mirrored into Postgres in their own AWS or GCP account, with the webhook handling, queue and reconciliation in one reviewed service.
Post a payload with a wrong HMAC, the same webhook ID twice, and an orders/updated with an older updated_at than the stored row. Stop the consumer for an hour during a test sale and check that the queue drains and that reconciliation finds anything the webhooks missed, then compare order counts and totals per day with Shopify's own reports.
Compute an HMAC-SHA256 of the raw request body with your app's client secret, base64-encode it, and compare it to the X-Shopify-Hmac-Sha256 header with a constant-time comparison. The body must be the exact bytes Shopify sent, so verify before any JSON parsing middleware touches it.
Shopify treats a delivery as failed if the app does not respond within five seconds, and retries failed deliveries up to eight times over four hours. If failures continue, the subscription is removed, so the endpoint should only verify, record and enqueue the event and leave the processing to a consumer.
No. Shopify does not guarantee ordering within a topic or across topics for the same resource, and the same webhook can arrive more than once after a timeout or retry. Deduplicate on X-Shopify-Webhook-Id and only apply an order update when its updated_at is newer than the stored copy.
With Encore you declare the Postgres database, a Pub/Sub topic between the webhook endpoint and the writer, and an hourly cron job for reconciliation in the service code, with the Shopify credentials stored as secrets. Deploying provisions RDS and SNS with SQS on AWS, or Cloud SQL and Pub/Sub on GCP, in your own account.
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.