Inventory Sync for AI Commerce: Webhooks, Retries & Reconciliation
Short answer
Webhooks alone cannot keep inventory correct, because deliveries get dropped, duplicated, delayed, and reordered. Keep stock correct for AI shopping channels with four parts: one source of truth per field, events that carry absolute quantities with a version number, an idempotent consumer that ignores duplicates and older versions, and a scheduled reconciliation job that repairs whatever the webhooks missed.
Key takeaways
- Name one system of record for each field (stock, price, availability date) and never let a channel copy overwrite it.
- Send absolute quantities with a monotonically increasing version, not deltas, so duplicates and reordering are harmless.
- Persist every webhook to a replay log before processing it, and acknowledge fast.
- Reconciliation is not optional: in our synthetic drill, lost webhooks stayed wrong for hours until a 15-minute reconciliation pass existed.
- Recheck stock live at cart and checkout, because any copy of inventory lags the source.
How do we prevent stale stock after a failed webhook?
Assume webhooks will fail and design so that a failure is repaired automatically. Make the consumer idempotent and version-aware so retries are safe, have the sender retry with backoff, and run a reconciliation job against the source of truth so anything still wrong is corrected within a known window.
Stale stock matters more in AI shopping than on a website. An assistant or agent reads availability from a feed, catalog channel, or tool call, states it to the buyer as fact, and may build a cart on it. If the channel copy says 3 units while the warehouse has 0, the agent recommends something you cannot ship. For how often feeds themselves should refresh, see product feed refresh and inventory freshness.
- Source of truth
- The single system whose value wins when copies disagree, for example the WMS for on-hand stock or the ERP for list price.
- Webhook
- An HTTP request a system sends to notify another system that something changed. Delivery is usually at-least-once, not exactly-once.
- Idempotent update
- An update that has the same effect whether it is applied once or many times.
- Reconciliation
- A scheduled comparison between a copy and its source of truth that corrects any differences.
- Replay log
- An append-only record of every event received, kept so events can be re-processed after a bug or outage.
What should be the source of truth for inventory and price?
The system that physically or contractually controls the value. Every other system, including your product feed, AI catalog channel, search index, and assistant cache, is a copy that can be wrong and must be repairable.
| Field | Typical source of truth | Copies | Conflict rule |
|---|---|---|---|
| On-hand stock per location | WMS or ERP | Commerce platform, feed, agent tools, search index | Source wins; copies never write back |
| Sellable quantity | OMS (on-hand minus reservations and safety stock) | Feed, agent tools | Computed in one place only; channels read it |
| List price | ERP or PIM | Platform, feed | Source wins; channel-specific prices are separate fields |
| Sale price and dates | Pricing or promotions engine | Platform, feed | Expired promotions are removed by the source, not by a channel |
| Customer-specific price (B2B) | ERP price lists | Live lookup only | Never cached in a shared feed |
| Availability date (backorder, preorder) | ERP or OMS | Feed, agent tools | Source wins; channel shows the date, not a guess |
What should an inventory event contain?
An absolute quantity, a version that only increases, a unique event ID, and the time the change happened at the source. Deltas such as "minus 1" are fragile: a duplicate subtracts twice, and a lost event leaves a permanent error.
{
"event_id": "inv_01J9Z6S3W0SYN",
"type": "inventory.level_changed",
"sku": "SYN-JKT-BLU-M",
"location_id": "WH-EAST",
"available": 0,
"version": 48213,
"occurred_at": "2026-11-29T14:02:11Z",
"source": "wms"
}| Field | Why it is there |
|---|---|
event_id | Deduplication key. The same event delivered twice has the same ID. |
available (absolute) | Applying it twice gives the same result, so duplicates are harmless. |
version | Per-SKU-and-location counter from the source. The consumer ignores any event with a version at or below what it already holds, so late deliveries cannot roll stock back. |
occurred_at | For lag metrics and audits. Do not use wall-clock time for ordering across systems; use the version. |
source | Lets you reject events from a system that is not the owner of that field. |
If the source cannot produce a version, a database sequence or a change-data-capture log position can serve as one. If it can only send deltas, convert them to absolute values at the edge of your system by reading the source after each notification.
How do we make inventory updates idempotent?
Do two checks before writing: skip the event if its ID is already in the replay log, and only apply it if its version is newer than the stored version. Do both in one conditional write so concurrent deliveries cannot race.
export async function POST(req: Request) {
const raw = await req.text();
if (!verifySignature(req.headers, raw, process.env.WMS_WEBHOOK_SECRET!)) {
return new Response('bad signature', { status: 401 });
}
const ev = JSON.parse(raw) as InventoryEvent;
// 1. Persist first. ON CONFLICT makes duplicate deliveries a no-op.
const inserted = await db.query(
`INSERT INTO inventory_event_log (event_id, sku, location_id, available, version, occurred_at, payload)
VALUES ($1,$2,$3,$4,$5,$6,$7) ON CONFLICT (event_id) DO NOTHING RETURNING event_id`,
[ev.event_id, ev.sku, ev.location_id, ev.available, ev.version, ev.occurred_at, raw]);
// 2. Acknowledge quickly so the sender does not time out and retry.
if (inserted.rowCount) queue.enqueue('apply-inventory', { eventId: ev.event_id });
return new Response(null, { status: 200 });
}INSERT INTO channel_inventory (sku, location_id, available, version, updated_at)
VALUES ($1, $2, $3, $4, now())
ON CONFLICT (sku, location_id) DO UPDATE
SET available = EXCLUDED.available,
version = EXCLUDED.version,
updated_at = now()
WHERE channel_inventory.version < EXCLUDED.version;The same pattern applies to outbound calls. When your middleware pushes stock to a platform API or a feed endpoint and the call times out, retry with the same idempotency key or the same absolute payload, so a retry that already succeeded does no harm. Our inventory and pricing API integration service builds these adapters for ERP, WMS, and OMS sources.
How should webhook retries be handled?
On the sending side, retry on timeouts and 5xx responses with increasing delays and a cap, and stop retrying permanent 4xx errors. On the receiving side, return 2xx only after the event is durably logged, and make duplicates harmless rather than trying to prevent them.
- Use exponential backoff with jitter, and a retry window long enough to cover a realistic outage of your consumer.
- Send retries to a dead-letter queue when they are exhausted, and alert on its size. A non-empty dead-letter queue is a list of SKUs that may be wrong.
- Distinguish errors: a 400 for a malformed event should not be retried forever; a 503 during a deploy should.
- Many platforms disable a webhook subscription after repeated failures. Monitor subscription health, not just delivery errors.
- Never rely on retries alone. Some events are lost before the first attempt (the sender crashed, the subscription was disabled), and no retry schedule recovers those. That is the job of reconciliation.
What is a replay log and why keep one?
A replay log is the append-only table every incoming event is written to before processing. It turns incidents into routine work: after a bug in the apply step, you fix the code and re-process the affected time range instead of guessing what was missed.
SELECT event_id, sku, location_id, available, version
FROM inventory_event_log
WHERE received_at BETWEEN $1 AND $2
ORDER BY sku, location_id, version;
-- feed each row back through the same apply step used for live events- Keep raw payloads, receive time, processing status, and error text.
- Set a retention period that covers your longest likely incident plus audit needs.
- Index by event ID (dedup), by SKU (investigation), and by receive time (replay).
How often should inventory reconcile?
Often enough that the longest time a SKU can stay wrong is acceptable to the business, which is usually minutes for fast-moving or low-stock items and hours for slow-moving ones. The reconciliation interval sets the upper bound on how long a lost webhook can leave stock wrong.
async function reconcile(tier: 'hot' | 'full') {
const skus = tier === 'hot'
? await db.lowStockOrRecentlySold({ threshold: 5, sinceMinutes: 60 })
: await db.allActiveSkus();
for (const batch of chunk(skus, 200)) {
const truth = await wms.getLevels(batch); // source of truth, paged
for (const t of truth) {
const fixed = await applyIfNewer(t.sku, t.locationId, t.available, t.version);
if (fixed) metrics.increment('inventory.reconcile.fixed', { tier });
}
}
}
// schedule: hot tier every 15 min, full pass nightly (example values, not a recommendation)The number of corrections each pass makes is the most useful health metric you have. If it is near zero, the webhooks are working. If it climbs, something upstream is dropping events, and the reconciliation job is quietly covering for it.
How do we design an inventory sync failure drill?
Inject the faults real webhook delivery produces, run the same change stream through each consumer design, and measure how long copies stay wrong. We ran this as a small synthetic simulation to show the effect of each design choice.
| Parameter | Value |
|---|---|
| SKUs | 200 invented SKUs, starting stock 0–5 units |
| Duration | 6 simulated hours at 1-second resolution, 5 random seeds |
| Change rate | 2 stock changes per SKU per hour (70% sales of 1 unit, 30% restocks of 1–4); about 2,350 events per run |
| Dropped by sender | 3% of events never sent |
| Duplicated | 5% of events delivered twice |
| Delay | Random 0–120 seconds per delivery, which also reorders events |
| Consumer outage | 20 minutes of 5xx responses, starting at hour 2 |
| Sender retries (designs B and C) | After 60 s, 300 s, and 1,800 s |
| Reconciliation (design C) | Full comparison with the source every 15 minutes |
| Metric | A: naive overwrite, no retries | B: idempotent + version guard + retries | C: B + 15-min reconciliation |
|---|---|---|---|
| Share of SKU-time with wrong stock | 9.38% | 6.58% | 3.54% |
| Share of SKU-time wrong for more than 5 consecutive minutes | 6.22% | 3.46% | 0.52% |
| Share of SKU-time showing stock when true stock was 0 | 0.88% | 0.66% | 0.34% |
| Longest single stale stretch (max over seeds) | 209.8 min | 178.4 min | 15.0 min |
| Out-of-order events that rolled stock back | 25 per run | 0 | 0 |
| Duplicate deliveries ignored | 0 (applied again) | 110 per run | 110 per run |
| Corrections made by reconciliation | n/a | n/a | 263 per run |
How to read it. Design B removes rollbacks and recovers the outage through retries, but the 3% of events the sender never sent stay wrong until the next change to that SKU, which is why its longest stale stretch is still about three hours. Design C caps that at the reconciliation interval. The remaining 3.54% of wrong SKU-time in design C is mostly the 0–120 second delivery delay we injected, which no consumer design can remove: only a live check at cart and checkout covers that window.
if (design === 'A') {
// naive: overwrite with payload, no dedup, no version guard
chan[ev.sku] = ev.qty; chanVer[ev.sku] = ev.version;
} else {
if (seen.has(ev.eventId)) continue; // duplicate
seen.add(ev.eventId);
if (ev.version <= chanVer[ev.sku]) continue; // older than what we hold
chan[ev.sku] = ev.qty; chanVer[ev.sku] = ev.version;
}
// design C, every 900 simulated seconds:
// for each SKU, if chan != truth, set chan = truth and count a fix- 1
Pick a test SKU set
Synthetic or staging SKUs with low stock, where errors are most expensive.
- 2
Record the baseline
Measure the time from a source change to the channel copy matching, per SKU.
- 3
Inject one fault at a time
Drop, duplicate, delay, reorder, take the consumer down, disable the subscription.
- 4
Measure the same metrics
Wrong SKU-time, longest stale stretch, rollbacks, phantom stock, reconciliation fixes.
- 5
Fix and re-run
Add the version guard, retries, replay log, or reconciliation tier, and run the same drill again.
Do we still need live stock checks at checkout?
Yes. Every copy of inventory lags the source by at least the delivery time, so the final check before a cart is confirmed or an order is placed must read the sellable quantity live from the system of record.
Feeds and catalog channels are for discovery; tool calls and checkout are for decisions. That split is the basis of the Next.js agentic commerce architecture, and the stock-race scenario (CT-061) in the agentic checkout test plan tests it directly. Headless teams can see how this fits their stack on the headless commerce page.
What should we monitor in an inventory sync?
| Metric | What it tells you | Example alert |
|---|---|---|
| Source-to-channel lag (p50, p95) | Normal delivery health | p95 above your agreed window for 15 minutes |
| Reconciliation fixes per pass | Events being lost upstream | Fixes above a baseline you set after the first week |
| Dead-letter queue size | Retries exhausted | Any entry older than one hour |
| Webhook subscription status | Sender stopped sending | Subscription disabled or no events in an expected window |
| Stale-version events ignored | Reordering or replay activity | Sudden spike (often a replay or a sender bug) |
| Checkout out-of-stock rejections | Channel copy is ahead of truth | Rate rising week over week |
Frequently asked questions
Should inventory sync use webhooks or polling?
Both. Webhooks give low latency for most changes, and polling or reconciliation catches what webhooks miss. Using only polling makes every change wait for the next cycle, and using only webhooks leaves lost events uncorrected.
Why send absolute quantities instead of deltas?
Absolute values make duplicates harmless and let a later event fully correct an earlier error. A delta applied twice or lost once leaves a permanent drift that only reconciliation can find.
What if the source system has no version number?
Use a sequence the source can provide, such as a change-data-capture log position or a database row version. If none exists, read the current value from the source when a notification arrives and use the read time plus a sequence you assign as the version.
Does reconciliation overload the ERP or WMS?
It can, which is why reconciliation is usually tiered: frequent passes for low-stock and recently sold SKUs, and a full pass off-peak. Batch the reads and respect the source's API rate limits.
How fast must inventory be for AI shopping channels?
Each channel publishes its own refresh guidance for feeds, and those differ. The business question is how long a wrong value can be shown before it causes harm, which is shortest for low-stock items.
Are the drill numbers on this page typical?
No. They come from a synthetic simulation with fault rates we chose to make effects visible. They show the direction and size of each design change under those assumptions, not what any real store will see.
Should prices use the same pattern?
Yes. Price events need the same event ID, version, and reconciliation, with one difference: customer-specific B2B prices should be looked up live rather than synced into a shared feed.
Stock or prices drifting between systems?
Tell us your source systems, platform, channels, and SKU count. We map the sources of truth and scope the sync and reconciliation work.
Related
- Inventory & Pricing API IntegrationWe build the adapters, event handling, and reconciliation.
- Inventory-to-Feed Integration DemoA failure and recovery demonstration with synthetic data.
- How Often Should Product Feeds Update?Feed refresh and freshness.
- How to Test Agentic Checkout Before LaunchIncludes the stock-race test.
- Next.js Agentic Commerce ArchitectureWhere live stock checks sit in the stack.
Sources
- Agent Commerce Optimization: synthetic inventory-sync failure simulation (run 2026-11-29) — First-party synthetic simulation; parameters and results are on this page.
- Google: UCP latest updates (order webhook acknowledgment and retry rules)
- Shopify: Storefront Catalog MCP (availability signals)
- OpenAI: Submit product feeds
Platform capabilities, eligibility, and specifications change. Sources were checked on 2026-11-29; confirm the current primary documentation before scoping an implementation. See our editorial policy and methodology.