Technical
Shopify to ERP Sync Architecture: Webhooks, Bulk Ops, Inventory
How to design a Shopify to ERP sync that stays correct under load: webhooks plus reconciliation polling, GraphQL bulk operations for backfills, inventory rules that prevent overselling, and idempotency at every step.
Kalvyai Engineering · · Updated · 8 min read

On this page
Most Shopify to ERP integrations work fine in a demo. They fail later: during a flash sale, after a deploy that dropped webhooks for ten minutes, or when two systems both decide they own the stock number. This post covers the architecture we use to make a Shopify sync with Odoo or ERPNext correct, not just fast.
The short version:
- Use webhooks for speed and polling for correctness. You need both.
- Use GraphQL Admin API bulk operations for backfills and large reconciliation runs.
- Treat inventory as its own problem with its own rules.
- Make every write idempotent, and decide up front which system owns each field.
The components
A reliable sync has more parts than "receive webhook, create sales order". Here is the layout we start from:
Shopify
| webhooks (HTTPS) ^ GraphQL Admin API (mutations)
v |
Ingress endpoint --> Inbox table --> Queue --> Workers --> ERP (Odoo / ERPNext)
^ |
Reconciliation poller -----------------+ v
Bulk backfill jobs --------------------+ Outbox table --> Shopify writer
Shared: mapping table, dead-letter list, sync log, alertsEach part has one job:
- Ingress endpoint: verify the request, store it, return 200. Nothing else.
- Inbox table: a durable record of every event received, deduplicated.
- Workers: turn events into ERP documents, with retries and backoff.
- Reconciliation poller: periodically asks Shopify what changed and fills gaps.
- Bulk jobs: initial import and large catch-up runs.
- Outbox: changes the ERP needs to push to Shopify (stock, prices, fulfillments), written in the same transaction as the ERP change.
- Mapping table: links Shopify IDs to ERP record IDs.
Webhooks vs polling: use both
Why webhooks alone are not enough
Webhooks give you low latency, but Shopify's own guidance is that apps should not rely only on webhooks and should run reconciliation jobs. In practice:
- Deliveries can arrive more than once.
- Deliveries can arrive out of order. An
orders/updatedcan land before theorders/createfor the same order. - Deliveries can be missed entirely if your endpoint is down longer than Shopify's retry window, and repeated failures can lead to the subscription being removed.
- Shopify expects a fast response. If your handler does ERP work inline, slow ERP responses turn into timeouts and retries.
Why polling alone is not enough
Polling every few minutes is simple and catches everything, but it adds latency, costs API rate limit budget, and still needs careful cursor handling. Customers notice when an order takes ten minutes to reach the warehouse.
The pattern
- Webhooks drive near real-time processing.
- A poller runs on a schedule and queries for records updated since its last checkpoint, minus a safety overlap (for example, five minutes) to cover clock skew and in-flight writes.
- Both paths feed the same queue and the same idempotent workers. The poller does not need to know whether a webhook already handled a record; the worker decides.
A polling query for orders filters on updated_at:
POLL_ORDERS = """
query($cursor: String, $q: String!) {
orders(first: 100, after: $cursor, query: $q, sortKey: UPDATED_AT) {
pageInfo { hasNextPage endCursor }
edges { node { id name updatedAt } }
}
}
"""
variables = {"cursor": None, "q": "updated_at:>='2025-01-10T09:55:00Z'"}The poller only fetches IDs and timestamps. Workers fetch full details when they process each record, which keeps the poll cheap.
The ingress endpoint
The ingress endpoint should do three things and return:
- Verify the HMAC signature in the
X-Shopify-Hmac-Sha256header against the raw request body. - Insert the event into the inbox, keyed on the webhook ID header (
X-Shopify-Webhook-Id). - Return 200.
import base64
import hashlib
import hmac
def verify_shopify_hmac(raw_body: bytes, header_hmac: str, client_secret: str) -> bool:
digest = hmac.new(client_secret.encode("utf-8"), raw_body, hashlib.sha256).digest()
expected = base64.b64encode(digest).decode("utf-8")
return hmac.compare_digest(expected, header_hmac or "")Verify against the raw bytes. If your framework parses JSON first and you re-serialize it, the signature will not match.
The inbox table uses a primary key on the webhook ID so duplicates are dropped at the database level:
CREATE TABLE shopify_inbox (
webhook_id text PRIMARY KEY,
shop_domain text NOT NULL,
topic text NOT NULL,
received_at timestamptz NOT NULL DEFAULT now(),
payload jsonb NOT NULL,
status text NOT NULL DEFAULT 'pending',
attempts int NOT NULL DEFAULT 0,
last_error text
);
INSERT INTO shopify_inbox (webhook_id, shop_domain, topic, payload)
VALUES ($1, $2, $3, $4)
ON CONFLICT (webhook_id) DO NOTHING;Keeping the raw payload also gives you an audit trail and lets you replay events after a bug fix.
GraphQL bulk operations for backfills
The first sync of a store with years of orders, or a catch-up after a long outage, should not page through the regular API. Bulk operations let Shopify run the query asynchronously and hand you a JSONL file.
The flow:
- Start the job with
bulkOperationRunQuery. - Wait for completion, either by polling the operation status or by subscribing to the
bulk_operations/finishwebhook. - Download the JSONL file from the returned URL.
- Stream it line by line into your queue.
START_BULK = """
mutation($q: String!) {
bulkOperationRunQuery(query: $q) {
bulkOperation { id status }
userErrors { field message }
}
}
"""
INNER_QUERY = """
{
orders(query: "updated_at:>='2024-01-01'") {
edges { node {
id name updatedAt displayFinancialStatus
lineItems { edges { node { id sku quantity } } }
} }
}
}
"""Things that catch people out:
- Nested connections are flattened. Line items come out as separate JSONL lines with a
__parentIdfield pointing at the order. Group them before building ERP documents, and do not assume the parent line is directly before its children unless the docs for your API version guarantee it. - Concurrency is limited per shop. Older API versions allow only one bulk query at a time per shop and app. Queue bulk jobs on your side rather than firing them in parallel.
- The download URL expires. Download promptly and store the file if you need to reprocess it.
- Status lookups vary by version. Newer API versions let you look up a job with
bulkOperation(id:), while older ones usecurrentBulkOperation. Use the one your API version documents.
For large writes to Shopify (for example, pushing thousands of price updates), bulkOperationRunMutation works the same way in reverse, using a JSONL file uploaded via staged uploads.
Rate limits
The GraphQL Admin API uses a cost-based leaky bucket. Each response includes cost and throttle status in the extensions field. Your Shopify client should read that and slow down before it hits the limit, instead of reacting to throttling errors. Limits differ by plan. Run reconciliation and outbox writers through the same rate-limited client so they do not compete.
Inventory: the hardest part
Orders flow mostly one way. Inventory changes in both systems at the same time, and mistakes cost money: oversells, cancelled orders, or stock that shows as zero when the shelf is full.
How Shopify models stock
Shopify tracks quantities per inventory item per location, with named quantity states such as available, on_hand, committed and incoming. When an order is placed, Shopify moves units out of available immediately. Your ERP has its own model, for example on-hand, reserved and forecast quantities per warehouse in Odoo, or actual and reserved quantities per warehouse in ERPNext.
First decision: map each Shopify location to one or more ERP warehouses, and decide which ERP number you push. Usually that is "free to sell" stock (on hand minus reserved minus a safety buffer), not raw on-hand.
The classic race condition
- The ERP reads 10 units free for SKU A.
- A customer buys 1 on Shopify. Shopify
availabledrops to 9. - The order webhook has not been processed yet, so the ERP still thinks 10.
- The ERP pushes "available = 10" to Shopify.
- Shopify now shows 10 units that really are 9. Repeat during a sale and you oversell.
Rules that prevent it
Rule 1: the ERP owns physical stock, Shopify owns its own order commitments. The ERP is the source of truth for what is in the warehouse. Shopify is the source of truth for orders it has accepted but the ERP has not yet seen.
Rule 2: account for unsynced orders before pushing. When computing the number to push, subtract Shopify orders that are in your inbox but not yet converted into ERP reservations. Process orders before stock pushes for the same SKU.
Rule 3: use compare-and-set or deltas, not blind absolute writes. inventorySetQuantities accepts a compare quantity: the write only succeeds if Shopify's current value matches what you expected. If it fails, re-read and recompute. Alternatively, push deltas with inventoryAdjustQuantities when the ERP records a stock movement (a receipt adds 20, a scrap removes 2), which cannot overwrite a Shopify-side decrement.
SET_AVAILABLE = """
mutation($input: InventorySetQuantitiesInput!) {
inventorySetQuantities(input: $input) {
inventoryAdjustmentGroup { id }
userErrors { field message code }
}
}
"""
variables = {
"input": {
"name": "available",
"reason": "correction",
"quantities": [{
"inventoryItemId": "gid://shopify/InventoryItem/123",
"locationId": "gid://shopify/Location/456",
"quantity": 42,
"compareQuantity": 40
}]
}
}Rule 4: debounce per SKU. If ten stock moves hit one SKU in a minute, push once with the final number. Key the outbox on (inventory item, location) and collapse pending rows.
Rule 5: run a full stock reconciliation daily. Use a bulk query to pull all inventory levels, compare with the ERP, and log differences above a threshold for review rather than silently overwriting.
Idempotency everywhere
Every step can run twice: webhook retries, poller overlap, worker crashes after the ERP write but before marking the event done. Design for it.
Inbound (Shopify to ERP)
Use a mapping table with a unique constraint on the Shopify ID:
CREATE TABLE shopify_map (
shop_domain text NOT NULL,
resource text NOT NULL, -- 'order', 'product', 'customer'
shopify_gid text NOT NULL,
erp_id text NOT NULL,
shopify_updated_at timestamptz NOT NULL,
UNIQUE (shop_domain, resource, shopify_gid)
);The worker logic for an order:
- Look up the mapping. If none exists, create the ERP order and the mapping in one transaction.
- If a mapping exists and the incoming
updatedAtis older than or equal toshopify_updated_at, skip. This handles out-of-order delivery. - Otherwise apply the update and store the new timestamp.
Also store the Shopify order ID on the ERP document itself (a custom field in Odoo or ERPNext) with a unique constraint, as a second guard against duplicates if the mapping table and ERP ever drift.
Better still, have the worker fetch the current state of the order from the API instead of trusting the webhook payload. Then it does not matter which event arrived first; the worker always applies the latest state.
Outbound (ERP to Shopify)
- Write outbox rows in the same database transaction as the ERP change, so a crash cannot lose them.
- Give each outbox row a stable key, and record the Shopify result against it.
- For creates (for example, a fulfillment), check whether the record already exists in Shopify before retrying a create that may have succeeded.
Conflict rules: decide ownership per field
Most sync bugs are really ownership bugs. Write down who owns what before writing code. A typical starting table:
Data | Owner | Direction |
|---|---|---|
Orders, line items, discounts, taxes charged | Shopify | Shopify to ERP |
Payment status | Shopify | Shopify to ERP |
Physical stock | ERP | ERP to Shopify |
Fulfillment and tracking | ERP (warehouse) | ERP to Shopify |
Product master, SKU, cost | ERP | ERP to Shopify |
Online title, description, images, SEO | Shopify | Not synced or Shopify to ERP |
Price | Pick one | One direction only |
Rules that follow from it:
- A field has exactly one owner. Never sync the same field both ways.
- If the non-owner changes an owned field, the next sync overwrites it, and you log that it happened.
- Edits to orders after they reach the ERP (address changes, line edits, cancellations) need explicit handling. Decide which states allow automatic updates and which create a task for a person.
- SKUs are the join key for products. Duplicate or blank SKUs should stop the sync for that item and raise an alert, not guess.
Operating it
A sync you cannot see is a sync you cannot trust. At minimum:
- A dead-letter list for events that failed after N retries, with the error and a replay button.
- Alerts on inbox backlog age, not just count.
- A daily report of reconciliation differences for orders and stock.
- Logs that link each ERP document back to the Shopify event that created or changed it.
How Kalvyai can help
We design and build Shopify integrations with Odoo and ERPNext, including webhook ingress, reconciliation, bulk backfills and inventory rules like the ones above. See our Shopify work at https://kalvyai.com/shopify.
If you run Odoo, our Shopify Odoo Connector connects Shopify and Odoo so the two stay in sync. Our other Odoo and ERPNext apps are at https://store.kalvyai.com.
If your current sync oversells, duplicates orders, or needs constant manual fixes, contact us and we will review the architecture with you.
Last updated 28 Nov 2026
- Shopify
- ERP integration
- GraphQL Admin API
- Webhooks
- Inventory sync
- Idempotency
- Odoo
- ERPNext
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