Skip to content
James Ross
articlePublished Updated 9 min read

NetSuite Shopify integration: inventory sync with drift reconciliation

By James Ross

A NetSuite Shopify integration for inventory projects NetSuite's authoritative available quantity into Shopify while accounting for orders Shopify has taken but NetSuite has not yet confirmed. The projection is an absolute target, not a delta, and it is written with a compare-and-set so a stale compute cannot overwrite newer stock. Drift reconciliation then proves the two systems converge.

A warehouse stock tower projecting quantities to a storefront shelf with a reconciliation lens, depicting a NetSuite Shopify integration.

That NetSuite Shopify integration was built for an industrial and facility supplies distributor, and it sits in the same integration family as a multi-brand commerce control plane. The interesting parts are the pending-demand ledger, the certificate-based machine-to-machine credential, and the refusal to write a relative adjustment.

Why Shopify gets a projection, not a second master

Shopify decrements its own available quantity when a sale occurs, while NetSuite may not reflect the reservation until the order has travelled through its connector, validation and posting route. Reapplying the sale as a negative delta to Shopify decrements the unit twice: once by Shopify, once by the integration.

Ignoring the gap fails the other way. Between the sale and the NetSuite posting, NetSuite still reports the unit as available, so a projection that simply mirrors NetSuite puts it back on sale. The resolution is a calculated projection: confirmed NetSuite availability minus demand Shopify has taken but NetSuite has not settled. The target can legitimately be lower than both raw values, and the system can explain why.

The target quantity formula

For each tenant, NetSuite item and mapped location, the projection computes one target:

target = max(
  policy_floor,                    -- usually 0; a backorder policy may allow negative
  confirmed_netsuite_available     -- authoritative, read with a revision
    - unsettled_shopify_sale_qty   -- positive pending demand
    - safety_stock                 -- configured per item/location
    - approved_temporary_holds     -- explicitly approved, time-bounded
)

Four properties keep this from becoming a formula that nobody trusts.

The floor is policy, not a clamp. For most items the floor is zero. A backorder policy can allow a negative target, but that decision is recorded in configuration with an owner, not hidden in a Math.max(0, …) call.

Every input has a timestamp and a revision. A target computed from a snapshot older than the last successful read is a guess. The implementation records the source snapshot and requires a later monotonic availability revision before settlement.

Quantities are safe integers. No floats and no unit conversion inside the projection; conversion belongs to an approved mapping, and an anomaly is an exception rather than a rounding decision.

Every state transition is validated and append-only. A terminal event cannot silently resume. Operators repair terminal failures by creating a new correlated event, not by rewriting history.

Pending-demand accounting: deltas that settle once

A pending delta records demand that Shopify has recognised and NetSuite has not yet confirmed. It is not a negative stock adjustment: the lifecycle is what prevents both double-decrement and permanent under-counting.

received -> validated -> mapped -> pending_netsuite -> netsuite_applied
         -> netsuite_confirmed -> shopify_applied -> reconciled

Any active state may move to retryable, blocked_mapping, quarantined or dead_letter when the state-machine contract permits it. retryable resumes only to the recorded resume state, so a retry does not restart the business effect from the beginning.

The settlement rule is the core invariant: a delta settles only after an authoritative NetSuite read shows its business effect, identified by the order connector acknowledgment or external transaction key. Settlement removes the delta; it does not add an inverse. An inverse would leave a permanent pair of compensating errors under a partial failure.

The other invariants are equally load-bearing: one pending delta per business key, settlement at most once with no return to unsettled, the same inputs producing the same projection, and no second decrement issued because of a Shopify order receipt.

The compensating events — cancellation, refund, restock — enter the ledger as immutable negative deltas. They are new facts, not edits to the original sale.

OAuth 2.0 machine-to-machine with a certificate

NetSuite’s client credentials flow authenticates the integration as an entity and role, using a signed JWT assertion instead of a client secret. The setup is a mapping between the integration record, the entity, the role and the public half of a certificate:

  1. Generate a dedicated RSA key pair in the secrets environment. Keep the unencrypted private PEM out of NetSuite, Git, tickets and chat.
  2. Upload the public certificate in OAuth 2.0 Client Credentials (M2M) Setup, and map it to the integration record, entity and role.
  3. Store the account ID, client ID, certificate ID and PKCS8 private PEM as encrypted credentials; the adapter reads them at runtime.
  4. Sign a short-lived assertion with PS256 for the token endpoint, request the rest_webservices scope, and use the access token for REST and SuiteQL calls (NetSuite REST web services).

The JWT must carry iss, sub, aud and exp, and the authorization server must reject a token whose audience is not itself (RFC 7523). A 401 usually means an assertion problem — wrong audience, key or certificate, or clock skew — while a 403 usually means the role cannot see the subsidiary, location or record.

Two operational details are easy to miss. The five-certificate limit means rotation needs a free slot, and a sandbox refresh clears the client credentials setup, so the mapping has to be recreated (Oracle). Rotation is a sequence: create the new key and mapping, test a read-only call under the same role, deploy with writes paused, confirm token and readback, then revoke the old certificate.

Absolute writes and compare-and-set

The write that reaches Shopify sets an absolute available quantity; it never sends “subtract one”. A relative write is only safe if the sender knows the current value, and it turns a retry into a second decrement.

Shopify’s inventorySetQuantities mutation supports a compareQuantity on each quantity, and it returns COMPARE_QUANTITY_REQUIRED when the compare value is missing without ignoreCompareQuantity, or COMPARE_QUANTITY_STALE when the compare value no longer matches the persisted value (Shopify inventory error codes). That is exactly the primitive a projection needs: write the target only if the current value is still the one the computation was based on.

A compare conflict is not an error to retry blindly. Another writer changed the quantity between the read and the write, so the response is to re-read the level, recompute from the current snapshot and ledger, and try again with the new compare value. Bypassing the comparison is not normal behaviour.

The same applies inside the database. At PostgreSQL’s default Read Committed isolation, each command takes a new snapshot, so two successive statements in one transaction can see different data (PostgreSQL transaction isolation). A “check, then insert” sequence needs a unique constraint or a row lock. The compare value is the provider-side version of that constraint.

A second idempotency layer sits above the compare value: a deterministic document URI identifies the business intent, and each write attempt carries a durable key. Shopify separates IDEMPOTENCY_KEY_PARAMETER_MISMATCH (key reused with different parameters) from IDEMPOTENCY_PREVIOUS_ATTEMPT_FAILED (a new key is required). A connector that treats a stale compare and both idempotency errors as “retry” will loop or double-write.

Drift detection and reconciliation runs

Drift is the difference between the projected target and what Shopify actually holds, after accounting for the pending ledger. A reconciliation run reads both sides, recomputes the target, and classifies the difference: explainable by a pending delta, explainable by a stale snapshot, or unexplained.

Unexplained drift is the only interesting category, and it should be rare. Common causes are a direct edit in Shopify, an out-of-band NetSuite adjustment, a mapping change that moved an item to a different location, or a write that succeeded at the provider and failed locally before acknowledgment.

A dry run computes and reports; a repair run writes. Repair requires an approver or admin and a certified Shopify write scope, which keeps a routine reconciliation from becoming an unreviewed bulk update. Full reconciliation runs in generations with completeness checks and atomic promotion, so a partially completed generation cannot be mistaken for a clean one.

Rollout is part of the design: read-only discovery first, then shadow mode through at least one complete business cycle with vendor writes disabled, then a canary of 10–25 low-risk variants at one location for 24–72 hours, then expansion one dimension at a time with a full reconciliation at each step. The stop conditions are written before the first write: an unmapped item, an event that would create a duplicate order, an unexplained target, drift or lag beyond threshold, or a missing audit or pause control.

Comparison: three ways to keep two systems in step

Model Write style Handles Shopify’s own decrement? Failure mode When to use it
Shopify is master Push Shopify quantity to the ERP Yes, by ignoring the ERP’s availability The ERP is wrong for accounting and planning A store with no ERP inventory truth
NetSuite master, relative deltas Send -1 per sale No: Shopify already decremented Double decrement, or oversell if skipped Almost never for stock
NetSuite master, projected absolute target Compare-and-set the computed target Yes, through pending demand A stale snapshot writes an old target unless compared When the ERP is the stock authority

Which should you choose? Use the projected absolute target whenever the ERP is the authority and the store takes orders faster than the ERP confirms them — most wholesale and distributor stores. Use Shopify as master only when there is no separate inventory system of record. Relative deltas are not a third option; they are a bug waiting for a retry.

What broke and what we changed

Settlement could look up a business key across tenants. The commercial review found that the settle path resolved a business key globally before applying tenant logic, and that several effect queries omitted a tenant predicate. In a single-tenant deployment the bug is invisible; in a multi-tenant one it is a cross-tenant write. The fix made effects tenant-scoped and moved the tenant predicate into the effect queries, and the review records it as a launch blocker that was closed.

Settlement initially settled too much. The first implementation settled all deltas once an observation looked plausible. The remediation moved to per-effect settlement: persist the baseline, expected quantity, receipt and confirmation, and settle only an effect whose expected quantity equals a later observation and whose revision advanced. That is the difference between “the number matches” and “this transaction caused the number”.

The worker could report ready without an adapter. Readiness was green in a configuration where no NetSuite or Shopify adapter existed, which is the worst kind of monitoring failure: the dashboard says healthy while nothing can sync. The fix made startup require active tenants, resolve the adapters, run both vendor connection tests, and only then mark the worker ready — fail-closed readiness instead of a liveness check.

The dashboard offered quantity writes it could not honour. Rendered QA found controls that changed only React state. The fix removed unsupported quantity-write controls from the production GUI and made the API return 501 FEATURE_NOT_SUPPORTED for adjustment, transfer, count and hold workflows. A blocked button is honest; a fake one is not.

The repository is an engineering candidate for credentialed staging. None of the above is vendor certification, and no live vendor write is claimed here.

Frequently asked questions

Why not just push NetSuite's available quantity to Shopify?

Because Shopify has already subtracted its own sales, and NetSuite may not have posted the corresponding reservation yet. Pushing the raw NetSuite number would put sold units back on sale. The projection subtracts unsettled Shopify demand and safety stock, then writes the result as an absolute target with a compare-and-set.

What is a pending delta in an inventory sync?

A pending delta is a record of demand that Shopify has recognised but NetSuite has not yet confirmed. It reduces the projected target until an authoritative NetSuite read shows the transaction's effect, at which point the delta settles and is removed. Settlement happens once; the delta never returns to unsettled.

How does certificate authentication work for NetSuite?

The integration record is mapped to an entity, a role and the public half of a certificate. The adapter signs a short-lived JWT assertion with the private key, sends it to the token endpoint for the rest_webservices scope, and uses the access token for REST and SuiteQL. There is no client secret to rotate; the certificate is the credential.

What does a Shopify compare-and-set conflict mean?

It means the quantity changed between the read and the write, so the computed target was based on a value that no longer exists. The connector re-reads the level, recomputes the target and retries with the new compare value. Forcing the stale quantity is how a sync quietly overwrites a sale.

Can this run for more than one store or tenant?

The production boundary in this build is exactly one active tenant. Effects carry tenant identifiers and the review closed the cross-tenant gaps, but multi-tenant SaaS operation, public Shopify App Store installation and per-tenant credentials are intentionally unsupported, and live installation still requires a development store.