The fix was not a better formula. It was fail-closed idempotency, an audit trail wide enough to prove what happened, and a written explanation to the client. The reference design for the corrected model lives in the NetSuite to Shopify inventory sync, and the wider pattern sits inside the multi-brand control-plane architecture.
What a double-decrement looks like in the data
The first symptom is not an error. It is a support ticket saying Shopify shows fewer units than the warehouse, then a second ticket a week later with a bigger gap. Three patterns distinguish a double-decrement from a stale read:
- The drift correlates with order volume, not time. A late sync produces a gap that closes on the next run; a double-decrement produces one that grows with sales and never closes.
- The same order line appears twice in the movement history. With an audit row per effect, one sale produces two rows with the same business key and different timestamps. Without audit rows, the bug is much harder to prove — which is why the audit columns are part of the fix.
- The gap survives a full re-read of the source. Recomputing from the authoritative balance and the pending ledger produces a target lower than Shopify holds, and the difference equals the duplicated effects.
Why “decrement” is the wrong unit of work
A relative write — available = available - 1 — assumes the sender knows the current value and that nobody changes it between the read and the write. In a two-system integration neither holds: Shopify decrements when the sale occurs, and the ERP has its own reservations, adjustments and transfers.
A relative write is also not idempotent. A retry after a timeout, a duplicate webhook, a queue redelivery or an operator pressing “retry” all subtract twice, because the operation has no memory of whether it already ran. HTTP names the missing property: a method is idempotent when repeating it has the same intended effect as a single request (RFC 9110). A -1 operation is not, so no retry policy makes it safe.
The durable alternative is a ledger of business effects: each sale becomes one effect with a stable business key, a payload hash and a state; the balance derives from confirmed source balances plus unsettled effects, and an applied effect is recognised rather than re-applied.
The connection-pool failure mode
The trace ended at the connection layer. A pooled connection is shared state disguised as a local variable, and it creates several ways for a check and a write to disagree even when the code reads as adjacent.
The guard and the write can run on different connections. A service checks “has this order line been processed?” on one connection, then acquires another connection to write. Between the two, a second worker passes the same check. Both write. The bug is invisible in development because there is only one worker and almost no concurrency.
A connection can go back to the pool inside an open transaction. If a code path returns a connection without committing or rolling back — an early return, a swallowed exception, a promise that resolves early — the next request inherits the session state and reads a snapshot older than the data it is about to modify.
A write can be applied twice but acknowledged once. A timeout after the provider committed, followed by a retry, is the classic ambiguous write. It surfaces as a socket error, but the defect is that the retry had no way to ask whether the earlier attempt landed.
These are different bugs with one shape: the unit of work was not atomic with respect to the decision. The fix does not depend on knowing which variant produced the incident. Remove the gap between the check and the write, and let the database enforce the single-effect rule.
Fail-closed idempotency
Fail-closed idempotency means the operation refuses to proceed when it cannot prove it has not already run — the opposite of the retry-friendly default, where an unknown outcome is treated as a failure and retried.
The mechanism is a claim row with a unique constraint on the business key. The insert is the check:
-- One row per business effect. The unique key is the idempotency guarantee.
create table inventory_effect (
id bigserial primary key,
business_key text not null,
payload_hash text not null,
state text not null default 'claimed',
qty_before integer not null,
qty_expected integer not null,
created_at timestamptz not null default now(),
constraint inventory_effect_once unique (business_key)
);
insert into inventory_effect (business_key, payload_hash, qty_before, qty_expected)
values ($1, $2, $3, $4)
on conflict (business_key) do nothing
returning id;
If the insert returns a row, this caller owns the effect and may proceed. If it returns nothing, the effect already exists: compare the stored payload_hash with the incoming one. Same hash means a replay, so return the original outcome. Different hash means a key collision with changed content, so return a conflict and write nothing.
Payment APIs made this shape familiar: Stripe saves the first response under an idempotency key and returns it to retries (Stripe: idempotent requests). The claim row is the same idea applied to an internal ledger.
Four rules make it hold under real failure:
- The claim and the transition share a transaction. Otherwise a claim without a write leaves an effect stuck in
claimed, and a write without a claim removes the guard. - An unknown outcome is reconciled, not retried. A timeout means the provider may have applied the effect; read it back by the stable external ID first.
- The business key comes from the business event, not the HTTP request, queue message or retry attempt.
- The state machine is append-only. Operators repair terminal failures with a new correlated event rather than an edit.
PostgreSQL’s default Read Committed isolation is why the naive version fails: each command takes a new snapshot, so successive statements in one transaction can see different data and a SELECT does not hold the value it read into the UPDATE (PostgreSQL transaction isolation). The unique constraint makes the decision atomic; an application-level if not exists does not.
Audit columns that make the sequence provable
Audit columns are not logging. Logging serves operators reading a stream; audit columns answer, months later, what the system believed and did.
The minimum set that made this incident explainable:
| Column group | Examples | Why it earns its space |
|---|---|---|
| Identity | business key, payload hash, correlation ID, source system | Tells a replay from a new event and links the chain |
| Quantity proof | quantity before, expected, requested, after | Shows whether the write matched the intent |
| Provenance | actor or service, role, request origin, attempt number | Distinguishes a retry from a second actor |
| Time | created, applied, settled, read back, all in UTC | Orders the sequence across services and time zones |
| Vendor evidence | external ID, provider status, raw response reference | Lets a human prove the effect landed |
Two details separate an audit table from a useful one. Store the expected value before the write, not only the value after it, or a wrong write and a correct write look identical. And store the readback separately from the request: the provider’s acknowledgment and the provider’s state are different facts. An incident review that has to reconstruct intent from application logs will end in “probably a retry”.
Comparison: three ways to make a decrement once-only
| Technique | What it guarantees | Cost | Failure mode it does not cover |
|---|---|---|---|
Optimistic check (if not processed) |
Nothing under concurrency | Cheap to write | Two workers both pass the check |
Row lock (SELECT … FOR UPDATE) |
Serialised access to that row while the transaction holds the lock | Lock contention; must be in the same transaction as the write | A retry after commit still re-applies a relative write |
| Unique claim plus ledger | One business effect, even across retries and workers | Schema change, state machine, recovery path | A wrong business key collapses two real events into one |
Which should you choose? Use the unique claim as the base, because it is the only one that survives a retry after commit. Add a row lock through SELECT … FOR UPDATE when the operation is a read-modify-write on a balance several transactions touch (PostgreSQL SELECT). Use an optimistic version column for user-facing edits where a conflict should be shown to a person. The three are layers, not alternatives.
How it was explained to the client
A written explanation is part of the remediation, not a courtesy. The client’s finance and operations teams need three things in plain language: what happened, what was and was not affected, and what changed.
The structure that works:
- The symptom in their terms. “Some orders reduced stock twice, so the store showed fewer units than the warehouse.” No jargon in the first paragraph.
- The scope, stated precisely. Which period, channel and direction. If it cannot be bounded yet, say so and give the date it will be.
- The mechanism, in one paragraph. Enough to be credible, not a lecture: the guard that made the operation run once and the write that changed the balance could run on different connections.
- The remediation, as verified changes. A unique business key, a claim-and-settle state machine, audit columns recording expected and actual quantity, and a reconciliation run.
- The proof and the owner. The post-fix reconciliation, the test that reproduces the race and now fails safely, and who owns the remaining manual step.
What broke and what we changed
The incident produced four changes.
A guard outside the write. A check followed by a separate write is the shape that fails: two workers can both pass the check, or a retry can pass it after the first write already landed. The fix puts the claim and the transition in one transaction with a unique constraint, so concurrency produces one winner and one replay.
Timeouts treated as failures. A timeout after a successful provider write is an unknown outcome, and retrying it is how one sale becomes two effects. The corrected flow reads the provider state by the stable external ID and writes again only when the read proves the first attempt did not land.
Audit rows that record outcomes but not intent. A row that shows only the new quantity cannot distinguish a duplicate from a legitimate adjustment. The record now stores before, expected, requested and after values, plus the attempt number and policy version.
Reconciliation that only reports. A drift report without a repair gate is not a control, because nothing stops an unreviewed bulk correction. The process separates dry run from repair, requires an approver, and treats an unexplained difference as an incident rather than a number to overwrite.
Related
Frequently asked questions
What causes an inventory double-decrement?
The usual cause is a non-idempotent relative write that is retried, or a check-then-write sequence where the check and the write are not atomic. Duplicate webhook delivery, a queue redelivery, a timeout after a successful write, or two workers passing the same guard all produce the same outcome: one sale, two reductions.
How can a connection pool cause it?
A pool hands out shared connections, so a check and a write can run on different connections, or a connection can return to the pool with an open transaction and stale session state; the next request then reads a snapshot older than the data it is about to change. The pool is not the bug; the missing transaction boundary is.
Is a unique constraint enough to prevent double-decrement?
A unique constraint on the business key prevents a second effect for the same key, but not if the key comes from the retry attempt rather than the business event, and not if a genuinely new event reuses the key. It is necessary but only correct with a stable key and an append-only state machine.
Why reconcile before retry instead of retrying?
Because a timeout does not tell you whether the write landed. Retrying an unknown outcome risks a duplicate effect; reconciling reads the provider's state and turns the unknown into a fact. The read costs one request and prevents a class of bug that is expensive to unwind.
What audit columns should an inventory integration keep?
At minimum: a stable business key, a payload hash, quantity before and expected, the requested and actual value after, the actor and role, the attempt number, the correlation ID, UTC timestamps per transition, and the provider's external ID and readback. Those fields prove what the system believed at each step.
