Development guide

Inventory Sync for AI Commerce: Webhooks, Retries & Reconciliation

By Michael E.Updated Sources checked 14 min

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.

Example source-of-truth rules. Adjust to your systems.
FieldTypical source of truthCopiesConflict rule
On-hand stock per locationWMS or ERPCommerce platform, feed, agent tools, search indexSource wins; copies never write back
Sellable quantityOMS (on-hand minus reservations and safety stock)Feed, agent toolsComputed in one place only; channels read it
List priceERP or PIMPlatform, feedSource wins; channel-specific prices are separate fields
Sale price and datesPricing or promotions enginePlatform, feedExpired promotions are removed by the source, not by a channel
Customer-specific price (B2B)ERP price listsLive lookup onlyNever cached in a shared feed
Availability date (backorder, preorder)ERP or OMSFeed, agent toolsSource 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.

Synthetic example event.
{
  "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"
}
FieldWhy it is there
event_idDeduplication key. The same event delivered twice has the same ID.
available (absolute)Applying it twice gives the same result, so duplicates are harmless.
versionPer-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_atFor lag metrics and audits. Do not use wall-clock time for ordering across systems; use the version.
sourceLets 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.

Illustrative sketch, not production code: webhook receiver that verifies, logs, acknowledges, then processes.
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 });
}
Illustrative sketch: apply with a version guard. Older or repeated versions change nothing.
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.

Illustrative sketch: re-process a time window after fixing a bug. The version guard keeps this safe to run more than once.
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.

Illustrative sketch: tiered reconciliation job. Low-stock and recently sold SKUs are checked more often.
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.

Drill parameters (synthetic simulation, run 2026-11-29)
ParameterValue
SKUs200 invented SKUs, starting stock 0–5 units
Duration6 simulated hours at 1-second resolution, 5 random seeds
Change rate2 stock changes per SKU per hour (70% sales of 1 unit, 30% restocks of 1–4); about 2,350 events per run
Dropped by sender3% of events never sent
Duplicated5% of events delivered twice
DelayRandom 0–120 seconds per delivery, which also reorders events
Consumer outage20 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
Results: averages over 5 seeds unless noted. Synthetic simulation output, not measured on a real system.
MetricA: naive overwrite, no retriesB: idempotent + version guard + retriesC: B + 15-min reconciliation
Share of SKU-time with wrong stock9.38%6.58%3.54%
Share of SKU-time wrong for more than 5 consecutive minutes6.22%3.46%0.52%
Share of SKU-time showing stock when true stock was 00.88%0.66%0.34%
Longest single stale stretch (max over seeds)209.8 min178.4 min15.0 min
Out-of-order events that rolled stock back25 per run00
Duplicate deliveries ignored0 (applied again)110 per run110 per run
Corrections made by reconciliationn/an/a263 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.

Core of the simulated consumer (from the dependency-free Node script we ran).
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. 1

    Pick a test SKU set

    Synthetic or staging SKUs with low stock, where errors are most expensive.

  2. 2

    Record the baseline

    Measure the time from a source change to the channel copy matching, per SKU.

  3. 3

    Inject one fault at a time

    Drop, duplicate, delay, reorder, take the consumer down, disable the subscription.

  4. 4

    Measure the same metrics

    Wrong SKU-time, longest stale stretch, rollbacks, phantom stock, reconciliation fixes.

  5. 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?

MetricWhat it tells youExample alert
Source-to-channel lag (p50, p95)Normal delivery healthp95 above your agreed window for 15 minutes
Reconciliation fixes per passEvents being lost upstreamFixes above a baseline you set after the first week
Dead-letter queue sizeRetries exhaustedAny entry older than one hour
Webhook subscription statusSender stopped sendingSubscription disabled or no events in an expected window
Stale-version events ignoredReordering or replay activitySudden spike (often a replay or a sender bug)
Checkout out-of-stock rejectionsChannel copy is ahead of truthRate 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.

Sources

  1. Agent Commerce Optimization: synthetic inventory-sync failure simulation (run 2026-11-29) — First-party synthetic simulation; parameters and results are on this page.
  2. Google: UCP latest updates (order webhook acknowledgment and retry rules)
  3. Shopify: Storefront Catalog MCP (availability signals)
  4. 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.