WooCommerce

WooCommerce Inventory Sync Without Oversells

WooCommerce inventory sync is the process of keeping stock quantities consistent between WooCommerce and an external system such as an ERP, warehouse or point-of-sale. Done badly it oversells; done well it uses atomic stock updates, signed webhooks, idempotent writes and a reservation step at checkout. I build these integrations in PHP with a single source of truth, a reconciliation pass and measurable sync lag.

By Saif Al Jahanwebdev-saif.com

What WooCommerce inventory sync actually guarantees

An inventory sync has one job: the number a customer can buy must never exceed the number you can ship. In WooCommerce that number lives in several places at once — the post meta keys _stock and _manage_stock, the wp_wc_product_meta_lookup table used for fast queries, the object cache, and whatever external system you treat as authoritative. A sync is correct only if all of those agree after every write. Oversells are not usually caused by a broken API; they are caused by two writers using stale reads, by backorders left enabled, or by stock being reduced too early or too late relative to payment. Before choosing a transport, write down the invariants.

  • No negative stock on any published product or variation
  • One authoritative quantity per SKU, not two competing owners
  • Every change applied exactly once, even after webhook retries
  • A bounded, measured delay between the source of truth and the store

The stock APIs and hooks I actually use

For writes inside WordPress I call wc_update_product_stock( $product_id, $quantity, "set" ) or the WC_Product methods set_manage_stock(), set_stock_quantity(), set_backorders() and set_stock_status() followed by save(). For remote systems the WooCommerce REST API v3 exposes GET and PUT on /wp-json/wc/v3/products/<id> with stock_quantity, manage_stock, stock_status and backorders; authentication is a consumer key and secret over HTTPS. Read only the fields you need. On the event side, hook into woocommerce_product_set_stock, woocommerce_reduce_order_stock and woocommerce_order_status_changed instead of polling for changes. Each variation carries its own stock, and wc_update_product_lookup_tables() rebuilds the lookup table when it drifts.

  • PUT /wp-json/wc/v3/products/<id> for absolute quantity writes
  • wc_update_product_stock() for in-process adjustments
  • woocommerce_product_set_stock and woocommerce_reduce_order_stock for events
  • wp_wc_product_meta_lookup for fast stock-aware queries
  • Variation IDs hold their own stock, separate from the parent product

Webhooks without retry storms

WooCommerce webhooks are configured under WooCommerce > Settings > Advanced > Webhooks with topics such as product.updated, order.created and order.updated. Each delivery carries X-WC-Webhook-ID, X-WC-Webhook-Topic and X-WC-Webhook-Signature. Verify the signature with hash_equals() against base64_encode( hash_hmac( "sha256", $raw_body, $secret, true ) ) before trusting the payload. The handler should return HTTP 200 fast, then hand the payload to Action Scheduler with as_enqueue_async_action(). Record the delivery ID as the idempotency key so a retry cannot apply the same change twice. Repeated non-2xx responses trigger exponential retries and can eventually disable a webhook, so never make slow ERP calls inside the webhook request.

  • Subscribe to product.updated and order.created, not every topic available
  • Verify the HMAC signature against the raw body before parsing JSON
  • Acknowledge with 200 immediately and process the job asynchronously
  • Store X-WC-Webhook-Delivery-ID to make redelivery harmless
  • Keep outbound HTTP out of the request so retries stay quiet

Where race conditions come from

The classic lost update looks like this: an external sync reads stock 5, a checkout reads stock 5, the sync writes 5, the checkout writes 4 — the sale disappears. The same pattern reverses into an oversell when two checkouts each subtract from the same stale value. The WooCommerce product data store wraps stock writes in a database transaction with a row lock, which protects reductions made through its own API. Integrations that read through REST and write a calculated value later lose that protection. If you must adjust stock directly, use an atomic statement such as UPDATE ... SET stock = stock - 1 WHERE stock >= 1, or SELECT ... FOR UPDATE inside a transaction, and check the affected row count. For channel sync, serialise writes per SKU with an Action Scheduler group or an advisory lock rather than trusting timestamps alone.

  • Read-modify-write across two systems is the root cause
  • Atomic decrement wins over a calculated absolute value under load
  • Lock or queue per SKU so two writers cannot interleave
  • Check affected rows and retries instead of assuming the write landed

Preventing oversells at checkout

Reservation timing is the decision that matters most. WooCommerce reduces stock when an order is paid, but unpaid orders can hold stock for a configurable window through the woocommerce_hold_stock_minutes option; a practical value I use is 30 to 60 minutes, paired with the unpaid-order cancellation that releases expired holds. For gateways that settle asynchronously, re-check availability on woocommerce_payment_complete and fail gracefully if the reservation expired. Keep manage_stock enabled and backorders set to no for physical products — one product with backorders enabled breaks an otherwise sound sync. For high-demand SKUs, add a reservation endpoint with a short time-to-live that returns HTTP 409 when stock is exhausted, and treat the Store API checkout like any other channel.

  • woocommerce_hold_stock_minutes set to 30-60 for pending payment orders
  • manage_stock enabled and backorders disabled on physical products
  • Revalidate on woocommerce_payment_complete for delayed gateways
  • A reservation endpoint with a short TTL and a 409 on exhaustion
  • Release expired holds automatically rather than by manual cleanup

A practical sync architecture I build

I am Saif Al Jahan, a freelance WordPress and PHP developer based in Mymensingh, Bangladesh (GMT+6), and this is the pattern I use on WooCommerce builds documented at webdev-saif.com. One system owns the quantity — usually the ERP or warehouse, never two. Outbound changes leave WooCommerce as signed webhooks; inbound stock arrives as absolute snapshots carrying a version or updated_at timestamp, not bare deltas, so a duplicated message cannot double-apply. Every inbound message is idempotent by delivery ID and version. Writes are queued per SKU through Action Scheduler, which gives ordered retries and a visible failed-action list. A reconciliation job every five minutes compares WooCommerce quantities with the source and logs drift through wc_get_logger().

  • One owner of truth, with WooCommerce mirroring rather than negotiating
  • Absolute versioned snapshots instead of unversioned delta increments
  • Idempotency keyed on delivery ID plus source version
  • Per-SKU Action Scheduler queues for ordering and safe retries
  • Five-minute reconciliation that corrects and records drift

Testing and the numbers worth watching

Sync bugs are concurrency bugs, so a single happy-path test proves little. I fire two simultaneous checkouts at the last unit of a SKU on a staging clone and assert that exactly one order succeeds and stock never goes negative. I also replay the same webhook delivery twice and confirm the quantity changed once. Practical targets I use: webhook handlers respond under 2 seconds, p95 stock lag stays under 60 seconds, and drift is zero units after each reconciliation pass. Alert on negative stock, on a webhook disabled after repeated failures, and on a queue depth that keeps growing. Keep logs in wp-content/uploads/wc-logs/ and review them weekly rather than after a customer complains.

  • Two concurrent checkouts against the final unit of one SKU
  • Replay one delivery twice and assert a single stock change
  • p95 sync lag under 60 seconds; webhook response under 2 seconds
  • Alerts for negative stock, disabled webhooks and growing queues

Frequently asked questions

What causes overselling in WooCommerce?

Overselling happens when the promised quantity exceeds physical stock. The usual causes are stale reads during simultaneous checkouts, an external ERP writing an older quantity after a newer sale, backorders left enabled, and expired unpaid orders releasing stock later than expected. Fix the write path with atomic stock updates and one authoritative source before tuning settings.

Should I use webhooks or polling for inventory sync?

Use webhooks for change detection and a scheduled reconciliation for correctness. Webhooks push product.updated and order.created events immediately, but they can be duplicated or delayed, so they are not a guarantee. A five-minute reconciliation job comparing quantities with the source catches missed deliveries. Polling alone wastes requests and still leaves a lag window.

Does WooCommerce protect stock updates from race conditions?

Partly. Its product data store uses a database transaction around stock changes made through WooCommerce itself, which serialises concurrent reductions. That protection disappears when an external system reads stock through REST and writes a calculated value later. Keep adjustments atomic, queue writes per SKU, and never store a quantity computed from a stale read.

Which REST endpoint updates WooCommerce stock?

Use PUT on /wp-json/wc/v3/products/<id> with a body containing stock_quantity, manage_stock, stock_status and optionally backorders, authenticated with a consumer key and secret over HTTPS. Target the variation ID for variations. For writes inside WordPress, wc_update_product_stock() is simpler and respects the locking in the WooCommerce data store.

How do I verify a WooCommerce webhook is genuine?

Recompute the signature from the raw request body using hash_hmac( "sha256", $body, $secret, true ), base64-encode it, and compare it with the X-WC-Webhook-Signature header using hash_equals(). Reject mismatches before parsing JSON. Also store X-WC-Webhook-Delivery-ID so a redelivered event cannot be applied twice.

Written by Saif Al Jahan, webdev-saif.com · Mymensingh, Bangladesh. Last updated .