Technical
Shopify Webhooks in Production: HMAC, Retries, Duplicates, Ordering
A practical guide to running Shopify webhooks in production: verify the HMAC on the raw body, deduplicate retries, handle out-of-order events, and recover cleanly after your endpoint has been down.
Kalvyai Engineering · · Updated · 7 min read

On this page
A Shopify webhook handler that works in development often fails in production. The usual causes are signature checks that break after a framework upgrade, the same order processed twice, an older update overwriting a newer one, and a missing day of data after an outage.
This post covers each of those problems and shows the patterns we use when we connect Shopify to Odoo, ERPNext and other back-office systems.
What Shopify guarantees and what it does not
Plan around these facts before you write any code:
- Delivery is at least once. You will sometimes receive the same webhook more than once.
- Order is not guaranteed. An
orders/updatedevent can arrive before theorders/createfor the same order. - Delivery is not guaranteed forever. If your endpoint keeps failing, Shopify stops retrying. Depending on how the subscription was created, it may also remove the subscription.
- Shopify expects a fast response. A slow endpoint is treated as a failed one.
Check the current retry policy and timeout in Shopify's documentation for your API version. These values have changed over the years, so do not hardcode assumptions about them.
The rest of this post follows from those four points.
Step 1: Verify the HMAC on the raw body
Every Shopify webhook includes an X-Shopify-Hmac-Sha256 header. It holds a base64-encoded HMAC-SHA256 digest of the request body, signed with your app's secret.
Which secret to use:
- For apps (custom or public), use the app's client secret.
- For webhooks created in the Shopify admin, use the signing secret shown on that settings page.
The mistake almost everyone makes once
You must compute the HMAC over the exact raw bytes Shopify sent. Many frameworks parse JSON before your handler runs. If you re-serialize the parsed object, key order, whitespace or unicode escaping can change, and the signature will never match.
Read the raw body first. Verify it. Parse it only after that.
import base64
import hashlib
import hmac
from flask import Flask, abort, request
app = Flask(__name__)
SHOPIFY_SECRET = b"load-this-from-your-secret-store"
def verify_shopify_hmac(raw_body: bytes, header_value: str) -> bool:
if not header_value:
return False
digest = hmac.new(SHOPIFY_SECRET, raw_body, hashlib.sha256).digest()
expected = base64.b64encode(digest)
# Constant-time comparison to avoid timing attacks
return hmac.compare_digest(expected, header_value.encode())
@app.post("/webhooks/shopify")
def shopify_webhook():
raw = request.get_data() # raw bytes, before any JSON parsing
if not verify_shopify_hmac(raw, request.headers.get("X-Shopify-Hmac-Sha256", "")):
abort(401)
# ... enqueue and return quickly (see Step 2)
return "", 200A few details that matter:
- Use a constant-time comparison (
hmac.compare_digestin Python,crypto.timingSafeEqualin Node.js). Never use==. - In Express, mount
express.raw({ type: 'application/json' })on the webhook route only, so the rest of your app can still use the JSON parser. - Also check
X-Shopify-Shop-Domainagainst the shops you actually serve. A valid signature for a shop you do not know about should be logged and rejected. - When you rotate the secret, accept both the old and the new secret for a short overlap period.
Step 2: Acknowledge fast, process later
Do not call your ERP, an AI model or any slow external API inside the webhook request. If your ERP takes several seconds to post a sales order, Shopify will see a timeout, mark the delivery as failed, and retry it. You will then process the same order twice.
Use an inbox pattern:
- Verify the HMAC.
- Write the raw payload and headers to a durable table or queue.
- Return 200.
- A separate worker reads the inbox and does the real work.
Here is a minimal inbox table in PostgreSQL:
CREATE TABLE shopify_webhook_inbox (
webhook_id text PRIMARY KEY,
shop_domain text NOT NULL,
topic text NOT NULL,
api_version text,
triggered_at timestamptz,
payload jsonb NOT NULL,
received_at timestamptz NOT NULL DEFAULT now(),
processed_at timestamptz,
attempts integer NOT NULL DEFAULT 0,
last_error text
);
CREATE INDEX ON shopify_webhook_inbox (processed_at) WHERE processed_at IS NULL;The handler then does one insert:
headers = request.headers
db.execute(
"""
INSERT INTO shopify_webhook_inbox
(webhook_id, shop_domain, topic, api_version, triggered_at, payload)
VALUES (%s, %s, %s, %s, %s, %s)
ON CONFLICT (webhook_id) DO NOTHING
""",
(
headers["X-Shopify-Webhook-Id"],
headers["X-Shopify-Shop-Domain"],
headers["X-Shopify-Topic"],
headers.get("X-Shopify-API-Version"),
headers.get("X-Shopify-Triggered-At"),
raw.decode("utf-8"),
),
)If the insert fails because your database is down, return a 5xx. Shopify will retry, which is what you want. Never return 200 for something you did not store.
Step 3: Handle retries and duplicates
Duplicates come from several places:
- Shopify retries after a timeout, even if your code actually finished.
- Network issues between Shopify and your load balancer.
- Two subscriptions that overlap. For example,
orders/createandorders/updatedboth fire when an order is created. - Your own replays during recovery.
Layer 1: deduplicate on the delivery
The ON CONFLICT (webhook_id) DO NOTHING above drops exact redeliveries. Shopify sends a webhook ID header that stays the same across retries of a delivery. Newer API versions also send an event ID header.
Layer 2: make the business action idempotent
Delivery-level dedup does not cover the overlapping-topics case, or a replay you trigger yourself. The safer rule is that creating something in the ERP must be keyed on the Shopify resource ID, not on the webhook.
In practice:
- Store the Shopify order ID (or the GraphQL GID) on the ERP sales order, with a unique constraint.
- Use "find by Shopify ID, then create or update". Never use a blind create.
- For side effects like sending an email or posting a payment, record that the action was done, and check that record first.
If you do this, processing the same payload twice gives the same result as processing it once. That is the property you need.
Step 4: Handle out-of-order events
Suppose a customer edits their shipping address twice in quick succession. You may receive the second update first and the first update second. If you apply them in arrival order, the old address wins.
The fix is to compare timestamps. Most Shopify resources carry an updated_at field in the payload. Store it on your side, and only apply an update if it is newer than what you already have:
INSERT INTO shopify_order_mirror (shopify_order_id, updated_at, data)
VALUES ($1, $2, $3)
ON CONFLICT (shopify_order_id) DO UPDATE
SET updated_at = EXCLUDED.updated_at,
data = EXCLUDED.data
WHERE shopify_order_mirror.updated_at < EXCLUDED.updated_at;If the incoming event is older, the WHERE clause skips it. Nothing is overwritten.
Some cases need extra care.
Updates that arrive before the create
If orders/updated arrives first, you have two options. You can treat it as a create, since the payload contains the full order. Or you can put it back on the queue with a short delay. The first option is simpler and works well when your handler is already "create or update".
Deletes
Delete payloads usually contain little more than the ID. Record a tombstone (the ID plus the deletion time) instead of just removing the row. Otherwise a late updated event can bring the record back.
Treating the webhook as a notification only
For resources where correctness matters more than API usage, such as inventory levels, treat the webhook as a signal that something changed. Then fetch the current state from the Admin API before you write to the ERP. This avoids ordering problems entirely. The cost is extra API calls, which count against your rate limits. We usually use this approach for a few critical topics, not for every webhook.
Step 5: Recover after your endpoint was down
At some point your endpoint will be down longer than Shopify's retry window. Common causes are a failed deploy, an expired TLS certificate or a firewall change. When that happens, assume some events are lost for good. Recovery has two parts: restore the subscription, then backfill the data.
Runbook
- Fix the endpoint and confirm it works. Send a test webhook and check that the HMAC passes and the inbox row is written.
- Check whether your subscriptions still exist. Query them through the Admin API, or check the app's delivery metrics in the Partner Dashboard or Dev Dashboard. If a subscription was removed, re-register it. Subscriptions declared in your app configuration and subscriptions created through the API behave differently, so confirm which kind you use.
- Find the gap. Take the
triggered_atof the last inbox row you received before the outage. Subtract a safety margin, such as an hour. - Backfill from the API. Query each affected resource for records updated since that time, and push them through the same processing path as webhooks.
- Let idempotency do its job. Because of Steps 3 and 4, records you already have are skipped or applied as no-ops.
- Write down what happened. Note the time window, the resources affected and how many records were backfilled.
A backfill using the GraphQL Admin API looks like this:
QUERY = """
query ($cursor: String, $q: String!) {
orders(first: 100, after: $cursor, query: $q, sortKey: UPDATED_AT) {
pageInfo { hasNextPage endCursor }
nodes { id updatedAt }
}
}
"""
def backfill_orders(client, since_iso: str):
cursor = None
while True:
data = client.graphql(QUERY, {"cursor": cursor, "q": f"updated_at:>='{since_iso}'"})
page = data["orders"]
for node in page["nodes"]:
enqueue_resync("orders", node["id"], node["updatedAt"])
if not page["pageInfo"]["hasNextPage"]:
break
cursor = page["pageInfo"]["endCursor"]Check which API scopes and access windows apply to historical orders in your setup.
Do not wait for an outage
Run the same backfill on a schedule as a reconciliation job, for example every few hours over a recent window. Webhooks give you speed, and reconciliation gives you completeness. Many "mystery" sync gaps turn out to be single dropped events that a scheduled reconciliation would have caught quietly.
Step 6: Monitor the right things
Alert on signals that show real problems:
- HMAC failure rate. A sudden spike usually means a rotated secret or a body-parsing change after a deploy.
- Inbox age. Alert when the oldest unprocessed row is older than a few minutes. This catches a stuck worker even while Shopify still sees 200s.
- Rows with high
attempts. These are poison messages. Move them to a dead-letter state with the error, so they do not block the queue. - Silence. If a busy store sends no
orders/createfor an unusually long time, something upstream is wrong. - Reconciliation diffs. If the scheduled backfill keeps finding records that webhooks missed, look into it.
A short checklist
- HMAC verified on raw bytes, with constant-time comparison
- Shop domain checked against known shops
- Payload stored durably before returning 200
- Dedup on the webhook ID, plus idempotent writes keyed on the Shopify resource ID
updated_atcomparison before overwriting- Tombstones for deletes
- Scheduled reconciliation through the Admin API
- Written runbook for re-registering subscriptions and backfilling
- Alerts on HMAC failures, inbox age, dead letters and silence
How Kalvyai can help
We build and maintain Shopify integrations with Odoo and ERPNext, including the webhook handling, idempotent sync and reconciliation described above. You can read more about that work at kalvyai.com/shopify.
If you run Odoo, our Shopify Odoo Connector connects your Shopify store to Odoo and keeps the two in sync. Our other apps are at store.kalvyai.com.
If your current integration is dropping orders, creating duplicates or needs a review before peak season, get in touch.
Last updated 28 Nov 2026
- Shopify
- Webhooks
- Integrations
- HMAC
- Reliability
- ERP Sync
Kalvyai Engineering · Engineering team
The engineers who build, connect and fix business systems at Kalvyai: Odoo, ERPNext, Shopify and AI agents that work inside them with approvals, budgets and an audit trail.



Comments
No comments yet. Questions and corrections are welcome.
Rate this post or leave a comment