Technical
Shopify Stock Sync: Race Conditions, Missed Webhooks and Fixes
Why stock numbers drift between Shopify and an ERP or warehouse system, and the three design fixes that keep them right: one owner of stock, idempotent updates and reconciliation jobs.
Kalvyai Engineering · · 7 min read

On this page
The usual symptoms are an oversold product, or a listing that shows 0 while the warehouse has 40 on the shelf. When we trace these cases, there is rarely one bug. There are a few small design gaps that add up: two systems writing the same number, webhooks that arrive twice or not at all, bundles nobody modelled, and locations that were mapped once and then forgotten.
This post walks through each cause and then the three fixes that solve most of them: one owner of stock, idempotent updates, and reconciliation jobs.
The four ways stock drifts
1. Race conditions between two writers
A classic lost update looks like this:
- The ERP reads Shopify's available quantity for a SKU: 10.
- A warehouse pick of 2 units is confirmed in the ERP. The ERP computes 10 - 2 = 8.
- Meanwhile, Shopify sells 3 units. Shopify now shows 7.
- The ERP writes 8 to Shopify.
Shopify now shows 8, the real figure is 5, and the 3-unit sale has been erased from the stock count. Nothing errored. Every system did what it was told.
The root problem is that two systems both believe they can compute the stock number, and each writes based on a value that was already stale.
Deltas have the opposite failure. If the integration sends "subtract 2" and the request is retried after a timeout, you may subtract 4.
2. Missed, duplicated and out-of-order webhooks
Shopify's documentation is clear that webhook delivery is not guaranteed to be exactly once or in order. In practice you will see:
- Duplicates. Your endpoint is slow, Shopify times out waiting and retries, and you process the same
orders/createtwice. - Out-of-order delivery. An
orders/updatedcan arrive before theorders/createit refers to. - Lost events. If your endpoint is down longer than the retry window, the event is gone. Repeated failures can also lead to the subscription being removed.
An integration that treats webhooks as the only source of truth will drift slowly, and nobody will notice until a customer does.
3. Bundles and kits
Shopify sells "Gift Box", but the warehouse stocks a mug, a candle and a card. The bundle's real availability is:
bundle_available = min(component_available / qty_per_bundle) over all componentsStock goes wrong when:
- The bundle SKU is tracked as its own stock item in Shopify, so selling a bundle does not reduce the mug count, and selling a loose mug does not reduce the bundle count.
- Components are shared across several bundles, and only one bundle gets recalculated when a component moves.
- The ERP explodes the bundle into components on import, but Shopify also deducts from a separate bundle quantity, so the deduction happens twice or in the wrong place.
4. Several locations
Shopify holds inventory per inventory item per location. Your ERP or WMS has warehouses, sub-locations and bins. Common mistakes:
- Pushing the total across all warehouses into a single Shopify location.
- A new Shopify location (a pop-up store, a 3PL) that is not mapped, so it keeps whatever number it was given on day one.
- An order assigned to one location in Shopify but fulfilled from another warehouse in the ERP, so each side deducts from a different place.
Fix 1: Pick one owner of stock
Decide which system owns the stock number. For almost every business we work with, that is the ERP or WMS, because that is where receipts, transfers, picks, returns and adjustments happen. Shopify is a sales channel that reports demand and displays what the owner tells it.
The flow then becomes one-directional for quantities:
Shopify order -> ERP creates sales order / reservation
ERP stock move -> ERP recomputes available per SKU per location
ERP -> pushes absolute available quantity to ShopifyRules that follow from this:
- Shopify's inventory number never flows back into the ERP's on-hand. Orders, cancellations and refunds flow back as events, and the ERP adjusts its own records.
- Only one integration writes inventory to Shopify. If an old app, a spreadsheet import and a new connector all write stock, you have three owners.
- Staff do not edit stock in Shopify admin. Restrict this with staff permissions where you can.
- Define exactly what "available" means before you push it. A typical definition:
push_qty = on_hand
- reserved_for_open_orders
- quarantined_or_damaged
- safety_bufferThe safety buffer is a business decision, not a technical one. A small buffer on fast sellers absorbs the seconds between a sale and the next push.
Fix 2: Make every update idempotent
Idempotent means processing the same message twice gives the same result as processing it once. You need this on both directions.
Incoming webhooks
Use this order of operations:
- Verify the HMAC signature.
- Record the webhook ID in a table with a unique constraint.
- If the ID already exists, return 200 and stop.
- Put the payload on a queue and return 200 quickly.
- Process from the queue, and make the processing itself idempotent (for example, "create sales order if no order exists for this Shopify order ID").
CREATE TABLE shopify_webhook_log (
webhook_id text PRIMARY KEY,
topic text NOT NULL,
received_at timestamptz NOT NULL DEFAULT now(),
processed_at timestamptz,
payload jsonb NOT NULL
);import base64, hashlib, hmac
from flask import Flask, request, abort
app = Flask(__name__)
SECRET = b"your-app-client-secret"
def valid_hmac(body: bytes, header: str) -> bool:
digest = hmac.new(SECRET, body, hashlib.sha256).digest()
return hmac.compare_digest(base64.b64encode(digest).decode(), header or "")
@app.post("/webhooks/shopify")
def shopify_webhook():
body = request.get_data()
if not valid_hmac(body, request.headers.get("X-Shopify-Hmac-Sha256")):
abort(401)
webhook_id = request.headers.get("X-Shopify-Webhook-Id")
topic = request.headers.get("X-Shopify-Topic")
# INSERT ... ON CONFLICT DO NOTHING; returns False if already seen
is_new = db.insert_webhook_if_new(webhook_id, topic, body)
if is_new:
queue.enqueue("process_shopify_event", webhook_id)
return "", 200 # fast, even for duplicatesThe webhook ID dedupes retries of the same delivery. It does not protect you from two different events about the same order arriving out of order, which is why step 5 matters: always look up the current state by Shopify order ID and apply changes based on that, not on the assumption that events arrive in sequence. When in doubt, fetch the order from the API before acting.
Outgoing stock pushes
Push absolute values, not deltas. "Set available to 37 at location X" can be retried safely. "Subtract 2" cannot.
To guard against the lost-update race, use a compare-and-set: tell Shopify what you expect the current value to be, and let the write fail if it changed. The GraphQL Admin API's inventorySetQuantities mutation supports this.
const mutation = `
mutation SetStock($input: InventorySetQuantitiesInput!) {
inventorySetQuantities(input: $input) {
inventoryAdjustmentGroup { id }
userErrors { field message code }
}
}`;
const variables = {
input: {
name: "available",
reason: "correction",
referenceDocumentUri: "erp://stock-push/2024-06-01T10:15:00Z/SKU-123",
quantities: [
{
inventoryItemId: "gid://shopify/InventoryItem/1111",
locationId: "gid://shopify/Location/2222",
quantity: 37,
// Expected current value. Write fails if Shopify's value differs.
// Check the compare-and-set field name for your API version.
compareQuantity: 40
}
]
}
};If the compare fails, do not blindly retry with the new value. Re-read Shopify, let the ERP recompute available (a sale may have just happened and needs to be imported first), then push again.
On the ERP side, keep a version or timestamp per SKU and location. A push job that was queued with older data should be dropped if a newer value has already been sent.
Fix 3: Run reconciliation jobs
Webhooks are the fast path. Reconciliation is what makes the system correct over time. Assume some events will be lost and design a job that finds and repairs the gap.
Order reconciliation
- Store a watermark: the last
updated_atyou fully processed. - Every run, fetch orders updated since the watermark minus an overlap window (for example 30 minutes), so late or clock-skewed events are caught.
- For each order, run the same idempotent import used by the webhook processor.
- Advance the watermark only after the batch succeeds.
The overlap means you re-check some orders every run. That is fine, because the import is idempotent.
Stock reconciliation
- For every mapped SKU and location, read Shopify's available quantity. For large catalogs, use a bulk query rather than paging item by item.
- Compute the ERP's push quantity for the same pairs.
- Compare, log every difference, and re-push the ERP value.
- Alert a person when the difference is large or keeps reappearing on the same SKU, because that points to a second writer or a mapping problem.
SELECT s.sku,
s.location_code,
e.push_qty AS erp_qty,
s.available AS shopify_qty,
s.available - e.push_qty AS drift
FROM shopify_stock_snapshot s
JOIN erp_push_quantities e USING (sku, location_code)
WHERE s.available <> e.push_qty
ORDER BY abs(s.available - e.push_qty) DESC;How often to run these depends on order volume. As a starting point, many stores run order reconciliation every few minutes and a full stock comparison at least daily, then tighten based on what the drift report shows.
Handling bundles properly
Choose one model and stick to it:
- ERP computes bundle stock. The bundle is a kit in the ERP. Whenever any component moves, the ERP recalculates every bundle that uses that component and pushes both component and bundle quantities. Orders for the bundle are exploded into components when they reach the ERP.
- Shopify deducts components. If the bundles app you use deducts component inventory itself, push only component quantities and make sure the bundle SKU is not tracked as separate stock.
The failure case is mixing the two, where both systems think they are responsible for the bundle number.
Multi-location checklist
- Keep an explicit mapping table: ERP warehouse or location to Shopify location ID. No mapping, no push.
- Push per location. Never push totals into one location.
- For Shopify locations with no ERP equivalent, decide deliberately: set them to 0, or stop stocking items there.
- Read the fulfillment order's assigned location when importing an order, and reserve stock in the matching ERP warehouse.
- When fulfillment moves to a different warehouse, update both the ERP reservation and the Shopify fulfillment location.
- Include location in the reconciliation report so drift at one location is visible.
When stock is already wrong: a quick diagnosis
- Pick one SKU that is wrong and list every write to it in Shopify's inventory history for the last few days.
- Identify every source of those writes: your connector, other apps, staff, imports.
- Compare orders in Shopify and in the ERP for the same period. Missing orders mean lost webhooks; duplicate orders mean non-idempotent processing.
- Check the location mapping for that SKU.
- If it is a bundle or a bundle component, check which system is deducting what.
This usually points straight at one of the four causes above.
How Kalvyai can help
We build and repair Shopify integrations with Odoo, ERPNext and warehouse systems, including stock ownership design, idempotent webhook processing, location mapping and reconciliation jobs. You can read more about our Shopify work. If you run Odoo, our Shopify Odoo Connector connects Shopify and Odoo so the two stay in sync, and our other apps are at store.kalvyai.com.
If your stock numbers are drifting and you want a second pair of eyes on the design, get in touch.
- Shopify
- Inventory
- ERP Integration
- Webhooks
- 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