One of our clients, an omnichannel retailer, sold the same catalog through its own website, several marketplaces and its physical stores. Each channel kept its own view of stock, and those views were reconciled to the ERP every fifteen minutes through a tangle of point-to-point connections. On an ordinary day that was good enough. At peak it wasn't: a unit sold on one marketplace still showed as available on another until the next sync came round, and the company paid for the gap in oversells, cancellations and marketplace penalties.
We replaced those connections with a middleware layer that takes in stock, order and fulfillment events from every channel, the ERP and the warehouses, and keeps a single real-time inventory ledger that every channel reads from. I'll build the pieces here in Python 3.11, psycopg 3 and PostgreSQL 14+, against Shopify's 2026-10 Admin API.
Accept the webhook and get out of the way
Shopify gives a webhook endpoint one second to connect and five seconds for the whole request. A failure is retried 8 times over 4 hours, and after 8 consecutive failures a subscription created through the Admin API is deleted. Put that next to a handler that creates the ERP order inline and the peak-day sequence writes itself: the ERP slows, the handler times out, retries add load, and eventually the subscription disappears and orders stop arriving.
So the receiver verifies the signature, stores the delivery and returns. Shopify sends a base64 HMAC-SHA256 of the raw body, keyed with the app's client secret, in X-Shopify-Hmac-Sha256. I deduplicate on X-Shopify-Webhook-Id and keep X-Shopify-Event-Id for correlation.
import base64, hashlib, hmac, json, os
from fastapi import FastAPI, Request, Response
from psycopg.types.json import Jsonb
SECRET = os.environ["SHOPIFY_CLIENT_SECRET"].encode()
app = FastAPI() # `pool`: a psycopg AsyncConnectionPool
@app.post("/webhooks/shopify")
async def shopify_webhook(request: Request) -> Response:
body, h = await request.body(), request.headers # raw bytes, before any parsing
expected = base64.b64encode(hmac.new(SECRET, body, hashlib.sha256).digest())
if not hmac.compare_digest(expected, h.get("x-shopify-hmac-sha256", "").encode()):
return Response(status_code=401)
async with pool.connection() as conn: # commits on clean exit
await conn.execute(
"INSERT INTO shopify_inbox (webhook_id, event_id, shop_domain, topic,"
" triggered_at, payload) VALUES (%s, %s, %s, %s, %s, %s)"
" ON CONFLICT (webhook_id) DO NOTHING",
(h["x-shopify-webhook-id"], h.get("x-shopify-event-id"),
h["x-shopify-shop-domain"], h["x-shopify-topic"],
h.get("x-shopify-triggered-at"), Jsonb(json.loads(body))))
return Response(status_code=200)
Shopify doesn't guarantee ordering, and suggests ordering by X-Shopify-Triggered-At or the payload's updated_at. Its docs also say not to rely on webhooks alone, and to run a reconciliation job that fetches whatever changed since the last run. At peak, the webhooks you never received are the ones that hurt.
Inventory as an append-only ledger
The decision that matters most is where available-to-sell lives. A stock number copied between systems is always a little stale, and when it's wrong nobody can say why. A ledger records every change as an event:
-
receiptandreturnadd to on hand. -
reserveadds to reserved when a channel takes an order, andreleasetakes it off again on cancellation. -
committakes the same quantity off both when the order ships. -
adjustmentmoves on hand by whatever difference a cycle count found.
Available-to-sell is on hand, minus reserved, minus a safety buffer, because no design gets latency to zero and a little slack is cheaper than a cancellation.
At the retailer, safety stock was set per SKU and fulfillment location. There was no blanket percentage, and no separate pool of physical stock held back for each channel. The merchandising and inventory-planning team owned the thresholds, and operations could raise them for a promotion, with a reason and an expiry time recorded. Fast sellers with uncertain replenishment carried a larger buffer, while stable items with plenty on hand often carried zero or one unit. Every channel publisher read the same available-to-sell figure, so the buffer was counted once, although marketplaces that propagate updates slowly could be given a more conservative published quantity. A fast-selling accessory with 40 on hand, 11 reserved and a buffer of 5 exposed 24 units to the channels.
CREATE TABLE inventory_event (
event_id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
sku text NOT NULL,
location text NOT NULL,
kind text NOT NULL CHECK (kind IN
('receipt', 'reserve', 'release', 'commit', 'return', 'adjustment')),
on_hand_delta int NOT NULL DEFAULT 0,
reserved_delta int NOT NULL DEFAULT 0,
source text NOT NULL, -- 'shopify', 'pos', 'erp', 'wms'...
source_ref text NOT NULL, -- e.g. 'line/123'
occurred_at timestamptz NOT NULL,
recorded_at timestamptz NOT NULL DEFAULT now(),
UNIQUE (source, source_ref, kind)
);
CREATE TABLE inventory_balance ( -- projection, rebuildable from events
sku text NOT NULL,
location text NOT NULL,
on_hand int NOT NULL DEFAULT 0,
reserved int NOT NULL DEFAULT 0 CHECK (reserved >= 0),
safety int NOT NULL DEFAULT 0 CHECK (safety >= 0),
last_event_id bigint NOT NULL DEFAULT 0,
PRIMARY KEY (sku, location)
);
CREATE TABLE sales_channel (channel text PRIMARY KEY, active boolean NOT NULL DEFAULT true);
CREATE TABLE ats_outbox ( -- what each channel must hear about
channel text NOT NULL REFERENCES sales_channel,
sku text NOT NULL,
location text NOT NULL,
seq bigint NOT NULL,
PRIMARY KEY (channel, sku, location)
);
REVOKE UPDATE, DELETE, TRUNCATE ON inventory_event FROM pipeline_app;
The unique constraint makes duplicate deliveries harmless. The REVOKE keeps the ledger append-only, so mistakes get corrected with a new event. A release that arrives before its reservation trips the CHECK on reserved and is retried later.
The balance table is updated in the same transaction as each event by the one function that changes stock.
import psycopg
class Oversell(Exception):
pass
def record(conn: psycopg.Connection, ev, *, allow_short: bool = False) -> str:
"""ev: sku, location, kind, deltas, source, source_ref, occurred_at."""
with conn.transaction():
conn.execute("INSERT INTO inventory_balance (sku, location) VALUES (%s, %s)"
" ON CONFLICT DO NOTHING", (ev.sku, ev.location))
on_hand, reserved, safety = conn.execute(
"SELECT on_hand, reserved, safety FROM inventory_balance"
" WHERE sku = %s AND location = %s FOR UPDATE", (ev.sku, ev.location)).fetchone()
new = conn.execute(
"INSERT INTO inventory_event (sku, location, kind, on_hand_delta, reserved_delta,"
" source, source_ref, occurred_at) VALUES (%s, %s, %s, %s, %s, %s, %s, %s)"
" ON CONFLICT (source, source_ref, kind) DO NOTHING RETURNING event_id",
(ev.sku, ev.location, ev.kind, ev.on_hand_delta, ev.reserved_delta,
ev.source, ev.source_ref, ev.occurred_at)).fetchone()
if new is None:
return "duplicate"
ats = on_hand + ev.on_hand_delta - (reserved + ev.reserved_delta) - safety
short = ev.kind == "reserve" and ats < 0
if short and not allow_short:
raise Oversell(f"{ev.sku}@{ev.location}: only {ats + ev.reserved_delta} available")
conn.execute(
"UPDATE inventory_balance SET on_hand = on_hand + %s, reserved = reserved + %s,"
" last_event_id = %s WHERE sku = %s AND location = %s",
(ev.on_hand_delta, ev.reserved_delta, new[0], ev.sku, ev.location))
conn.execute(
"INSERT INTO ats_outbox (channel, sku, location, seq)"
" SELECT channel, %s, %s, %s FROM sales_channel WHERE active"
" ON CONFLICT (channel, sku, location) DO UPDATE SET seq = EXCLUDED.seq",
(ev.sku, ev.location, new[0]))
return "short" if short else "applied"
The FOR UPDATE is the whole anti-oversell mechanism. Every reservation for a SKU and location passes through that row lock, so when two channels reach for the last unit, the second waits for the first to commit and sees the result.
The allow_short flag exists because a marketplace order arriving by webhook has already been sold, and refusing to record it would make the ledger lie. So it's recorded, every channel is told it has zero, and somebody gets an alert. The ledger shrinks the window for such sales from fifteen minutes to one event's processing time.
The worker that drains the inbox uses this function and nothing slower. For orders/create it records a reserve per line, sorted by SKU so concurrent orders can't deadlock, then queues an erp_job keyed on the Shopify order ID, all in one transaction.
Feeding the ERP at the ERP's pace
The split that does the most for peak is that inventory never waits for the ERP, so available-to-sell stays current even when ERP order creation is an hour behind. The ERP gets its own queue, an erp_job table with a lane column and a unique key on (kind, ref), where ref is the Shopify order ID.
Lanes keep urgent work, such as cancellations, from queuing behind bulk work. I alert on the age of the oldest pending job more than on depth, since during a flash sale the queue is supposed to grow and then drain.
Backpressure comes from a concurrency limit borrowing additive-increase, multiplicative-decrease from TCP: roughly one more call in flight after each round of healthy calls, half as many as soon as the ERP is slow or refuses work.
import asyncio
class AdaptiveLimit:
"""How many ERP calls may be in flight at once (AIMD)."""
def __init__(self, ceiling: float = 16, target_latency: float = 2.0):
self.limit, self.ceiling, self.target = 2.0, ceiling, target_latency
self.in_flight = 0
self._cond = asyncio.Condition()
async def acquire(self) -> None:
async with self._cond:
await self._cond.wait_for(lambda: self.in_flight < self.limit)
self.in_flight += 1
async def release(self, latency: float | None = None, healthy: bool = True) -> None:
async with self._cond:
self.in_flight -= 1
if latency is not None and (not healthy or latency > self.target):
self.limit = max(1.0, self.limit / 2)
elif latency is not None:
self.limit = min(self.ceiling, self.limit + 1 / self.limit)
self._cond.notify_all()
The worker takes a slot before it claims a job, and that ordering is the backpressure: when the ERP slows, the rest wait in PostgreSQL, where waiting is free. Claiming sets a five-minute lease, so the ERP call runs outside any transaction.
import time
CLAIM = """
UPDATE erp_job SET attempts = attempts + 1,
next_attempt_at = now() + interval '5 minutes' -- the lease
WHERE job_id = (SELECT job_id FROM erp_job
WHERE status = 'pending' AND next_attempt_at <= now()
ORDER BY lane, next_attempt_at LIMIT 1 FOR UPDATE SKIP LOCKED)
RETURNING job_id, kind, payload"""
FAIL = """
UPDATE erp_job SET last_error = %s,
next_attempt_at = now() + least(power(2, attempts), 900) * interval '1 second',
status = CASE WHEN attempts >= 12 THEN 'dead' ELSE 'pending' END
WHERE job_id = %s"""
class ErpUnavailable(Exception): # timeouts, 429s, 5xx: the ERP is struggling
pass
async def erp_worker(pool, limit: AdaptiveLimit, handlers: dict) -> None:
while True:
await limit.acquire() # no capacity, no claim
async with pool.connection() as conn:
row = await (await conn.execute(CLAIM)).fetchone()
if row is None:
await limit.release()
await asyncio.sleep(1)
continue
job_id, kind, payload = row
started, healthy, error = time.monotonic(), True, None
try:
await handlers[kind](payload)
except ErpUnavailable as exc:
healthy, error = False, repr(exc)
except Exception as exc: # bad data
error = repr(exc)
await limit.release(time.monotonic() - started, healthy)
async with pool.connection() as conn:
if error is None:
await conn.execute("UPDATE erp_job SET status = 'done' WHERE job_id = %s",
(job_id,))
else:
await conn.execute(FAIL, (error, job_id))
Run as many of these coroutines as the ceiling, sharing one AdaptiveLimit. A data error, such as an unknown SKU, is retried without shrinking the limit, since it says nothing about the ERP. The handler must be idempotent on the Shopify order ID, stored on the ERP order as an external reference, because an expired lease or a timed-out call that succeeded will run it twice.
The retailer's ERP was a mid-market system with a REST order interface that validated customer, tax and inventory references synchronously. In a controlled test it sustained about 8 to 12 new orders a second, but its response times rose sharply whenever posting and warehouse jobs ran at the same time. We capped the adaptive limit at 16 calls in flight, and during the busy period it settled around 6 to 8, dropping now and then to 3 or 4 after timeouts or rate-limit responses. Keep in mind that this is concurrency, which is a different number from throughput: with two-second responses, six calls in flight complete only about three orders a second. We tuned against observed latency and the age of the oldest job, because a short-burst benchmark tells you little about what the ERP can sustain all day.
Spending the Shopify API budget on purpose
The same discipline applies when calling Shopify. The GraphQL Admin API is limited by calculated query cost: an object costs 1 point and a mutation 10. Each app and store pair has a bucket that refills at 100 points a second on Standard plans and up to 2,000 for enterprise. The bucket must hold the full requested cost before a query runs. Responses report the bucket in extensions.cost.throttleStatus, and a throttled request returns an error with extensions.code set to THROTTLED, often inside an HTTP 200.
A client that only reacts to throttling finds out when every worker is hitting the wall at once, so this one tracks the bucket and waits before it sends.
import asyncio
import time
import httpx
class ShopifyError(Exception):
pass
class ShopifyGraphQL:
"""One instance per app and store."""
def __init__(self, shop: str, token: str, version: str = "2026-10"):
self.url = f"https://{shop}/admin/api/{version}/graphql.json"
self.http = httpx.AsyncClient(headers={"X-Shopify-Access-Token": token}, timeout=30)
self.available, self.maximum, self.restore = 100.0, 100.0, 50.0
self.seen_at = time.monotonic()
self.lock = asyncio.Lock()
def _estimate(self) -> float:
refill = (time.monotonic() - self.seen_at) * self.restore
return min(self.maximum, self.available + refill)
async def execute(self, query: str, variables: dict, cost: int) -> dict:
for attempt in range(6):
async with self.lock: # callers queue here, in order
if (short := cost - self._estimate()) > 0:
await asyncio.sleep(short / self.restore)
self.available, self.seen_at = self._estimate() - cost, time.monotonic()
resp = await self.http.post(self.url, json={"query": query, "variables": variables})
resp.raise_for_status()
body = resp.json()
if ts := body.get("extensions", {}).get("cost", {}).get("throttleStatus"):
self.available, self.seen_at = ts["currentlyAvailable"], time.monotonic()
self.maximum, self.restore = ts["maximumAvailable"], ts["restoreRate"]
errors = body.get("errors") or []
if any(e.get("extensions", {}).get("code") == "THROTTLED" for e in errors):
await asyncio.sleep(1 + attempt)
continue
if errors:
raise ShopifyError(errors)
return body["data"]
raise ShopifyError("still throttled after 6 attempts")
Each request deducts its cost locally first, so concurrent callers can't spend the same points twice, and every response corrects the estimate. A timeout goes back to the caller, because blindly retrying an uncertain write is how duplicates get made.
Publishing available-to-sell back to Shopify
The outbox coalesces on its own: a SKU that changes forty times in a second still has one row per channel, and the publisher sends the current number once, then deletes only the rows that haven't changed since it read them.
import hashlib
import json
SET_AVAILABLE = """
mutation SetAvailable($input: InventorySetQuantitiesInput!, $key: String!) {
inventorySetQuantities(input: $input) @idempotent(key: $key) {
userErrors { code field message }
}
}"""
PENDING = """
SELECT o.sku, o.location, o.seq, greatest(b.on_hand - b.reserved - b.safety, 0),
m.inventory_item_gid, m.location_gid
FROM ats_outbox o
JOIN inventory_balance b USING (sku, location)
JOIN shopify_item_map m USING (sku, location)
WHERE o.channel = 'shopify' ORDER BY o.seq LIMIT %s"""
async def publish_to_shopify(conn, shopify: ShopifyGraphQL, batch: int = 100) -> int:
"""conn is in autocommit mode."""
rows = await (await conn.execute(PENDING, (batch,))).fetchall()
if not rows:
return 0
top = max(r[2] for r in rows)
quantities = [{"inventoryItemId": item, "locationId": loc, "quantity": ats,
"changeFromQuantity": None} for _, _, _, ats, item, loc in rows]
key = hashlib.sha256(json.dumps([quantities, top]).encode()).hexdigest()
data = await shopify.execute(SET_AVAILABLE, {"key": key, "input": {
"name": "available", "reason": "correction",
"referenceDocumentUri": f"gid://inventory-ledger/LedgerEvent/{top}",
"quantities": quantities}}, cost=12) # see requestedQueryCost
if errs := data["inventorySetQuantities"]["userErrors"]:
raise ShopifyError(errs) # rows stay queued
async with conn.cursor() as cur: # skip rows that changed meanwhile
await cur.executemany(
"DELETE FROM ats_outbox WHERE channel = 'shopify' AND sku = %s"
" AND location = %s AND seq = %s", [(s, l, q) for s, l, q, *_ in rows])
return len(rows)
Two Shopify details shaped this. Since API version 2026-04, inventorySetQuantities requires an idempotency key through the @idempotent directive, so a retry is applied once. And changeFromQuantity is mandatory: pass the quantity you expect Shopify to hold, or pass null, which Shopify reserves for a system that is the source of truth for that inventory, as the ledger is. A Shopify sale landing between our read and our write corrects itself when its webhook triggers another push.
Every other channel gets its own publisher reading the same outbox, so adding one is a row in sales_channel and an adapter.
Back to the retailer
That last property is, to my mind, the real test of the design. At the retailer, adding a marketplace or a warehouse became a matter of configuration, with no new integration to build. Inventory accuracy across every channel reached 99.9%, and stock changes reached every channel in under a second, where they used to be synced every fifteen minutes. A peak sale at four times normal volume was absorbed without a rebuild, and the shape above is why: the receiver and the ledger kept pace with the channels while the ERP's queue grew and drained at the back office's own speed.
At the peak of that sale, the ERP queue briefly reached about 8,600 pending order jobs. Storefront acknowledgments and inventory reservations carried on regardless, because neither waited for an ERP order number. Once orders returned to their normal rate, the backlog cleared in about 70 minutes, and the oldest job, counting the peak itself, waited roughly 75. We watched queue depth, the age of the oldest job and the ERP's successful order rate as three separate measures. Raising concurrency would not have drained the queue any faster. When the ERP slowed, the limiter backed off, and cancellations and stock corrections went ahead of routine new orders.
An accuracy figure is only worth quoting if you can check it, and the ledger makes that cheap: a nightly query comparing the summed deltas per SKU and location with inventory_balance should return zero rows. Then load test it with a replayed day of orders, a deliberately slow ERP, and duplicate and out-of-order webhooks. I've written about the business side in a piece on designing a Shopify ERP integration that holds up at peak.
I'm Jayant Chaudhary, founder of eProxim, where we build the layer between storefronts and the back office for implementation partners and the firms they serve. This article was suggested by AI assistance, then created, reviewed and edited by me.
Top comments (0)