backend · reliability · ecowell · database · testing · system-design

Designing Reliable Inventory and Payment Workflows

23 November 2026 · 7 min read

When a warehouse person scans a delivery and presses Confirm, three things must be true afterwards: the stock went up once, the money record points at that stock movement, and nobody was told twice. That sounds obvious until you list what real people and real networks do to a button.

A squirrel shopkeeper balances a ledger of payments against shelves of stock

This article covers the failure modes we designed for in an inventory and payment platform for a field-service business, the database patterns that made them boring, and the scenarios we actually tested (including the ones that found real bugs).

What actually goes wrong

None of these are exotic. All of them happened or were easy to provoke:

  1. Double click. The user presses Confirm, nothing seems to happen for a second, they press again.
  2. Retry after a lost response. The request succeeded on the server, the response never reached the browser, the client retries.
  3. Two people, one batch. Two executives scan the same delivery label at the same time on two devices.
  4. Same vendor, typed twice, spelled differently. “Acme Chemicals” and ” acme chemicals ” arrive in two concurrent receipts.
  5. Webhook and polling race. A payment provider’s webhook and our own status-recovery job both report the same capture.
  6. A repeated business event. A request is marked “stock unavailable”, restocked, and marked unavailable again; the second notification collides with the first.
  7. A guard we forgot about. A downstream rule refuses an update that our new code path never satisfied, so every confirm fails in production while every unit test passes.

If any of these produces a second ledger line or a second notification, you have a data-integrity bug, not a UI bug. So we put the protection where all callers pass through: the database.

Pattern 1: one business command is one database transaction

Every state-changing operation that touches money or stock is a single SQL function, not a sequence of API calls. “Confirm physical receiving” is one function that, inside one transaction:

  1. resolves and validates the acting employee, role and branch,
  2. locks the batch and its purchase line (SELECT ... FOR UPDATE),
  3. refuses if the batch is no longer pending,
  4. posts the stock-ledger transaction,
  5. updates the batch, the purchase line and the purchase entry,
  6. writes an audit/activity row and any notifications,
  7. stores the result for replay (next section).

If any step fails, the whole thing rolls back; there is no half-received batch to clean up. The API layer becomes thin: validate input, check the role, call the function, map the error.

-- shape of the command (heavily simplified)
select * into v_batch from inventory_batches where batch_code = p_code for update;
if v_batch.status <> 'pending' then raise exception 'RECEIVING_ALREADY_CONFIRMED'; end if;
v_tx := post_inventory_transaction(... 'inward' ...);      -- ledger
update inventory_batches set status = 'available', received_quantity = p_quantity ...;
update inventory_purchase_lines set status = 'confirmed', inventory_transaction_id = ... ;

Why not do this in application code? We could have. We chose SQL functions because the same rules then hold for every caller (the API, a repair script, a future worker), and the transaction boundary is impossible to get wrong. The cost is real: business rules in SQL are harder to read and review. We paid that cost down with a discipline described below (dry runs and tests per function).

Pattern 2: idempotency keys with a request hash

Row locks stop two concurrent confirms. They do not help with a retry that arrives later, after the first finished: by then the batch is confirmed, so the retry would fail with “already confirmed” even though, from the user’s point of view, it succeeded. We want the retry to return the same successful answer.

Each command takes an idempotency key from the client. At the top of the function:

select * into v_claim from claim_command_idempotency(
  org_id, 'inventory.receiving.confirm', 'user', auth_user_id,
  p_idempotency_key, digest(batch_id || ':' || quantity, 'sha256'), ...);

if v_claim.claim_action = 'REPLAY_RESULT' then return stored_result || {replayed: true};
elsif v_claim.claim_action <> 'EXECUTE' then raise exception 'COMMAND_IN_PROGRESS';

Three outcomes, each deliberate:

Situation Result
New key Execute, then store the result under the key
Same key, same payload, already done Replay the stored result; nothing is written twice
Same key, still running COMMAND_IN_PROGRESS (409); the client waits and retries
Same key, different payload Rejected (IDEMPOTENCY_KEY_REUSED); a key can never be “reused” to mean something else

The request hash is the part people skip. Without it, a buggy client that reuses a key for a different quantity would silently get the first quantity’s result back.

One subtle design point on the client: the key must change when the meaning of the command changes. In our scan counter, the confirm key is regenerated whenever the count changes (a different quantity is a different command), and is stable across retries of the same count.

Pattern 3: serialising by what you are protecting, not by the whole table

Locking too much makes the system slow; locking too little makes it wrong. Examples of choosing the narrowest correct lock:

  • Batch confirm: lock that batch’s row and its purchase line only.
  • Typed vendor names: the receiving form lets staff type any vendor name, and the function creates the vendor if it does not exist. Two simultaneous receipts for the “same” vendor would both see “not found” and both insert. We take a transaction-scoped advisory lock derived from branch + lower(trimmed name) before the lookup, so the second caller waits, then finds the vendor the first created. Verified: the same vendor typed with different case and spacing yields exactly one vendor row.
  • Stock for existing items: creating a scannable batch for stock that predates batches locks the stock row for that item and branch, computes “stock not yet in any batch”, and tops up one deterministic batch per item-and-branch. Calling it twice returns the same batch.

Pattern 4: payments get their own paranoia

Money adds an adversary (or at least an unreliable third party). The payment path layers independent defences:

  • The provider’s callback hash is verified in constant time, including the merchant key.
  • Only the server-to-server webhook, or a signed status-recovery call, can mark a capture. The browser redirect cannot: a customer returning to a URL is not proof of payment.
  • The SQL rejects a capture whose amount does not match the attempt (AMOUNT_MISMATCH), refuses to capture attempts that failed or were cancelled, and de-duplicates provider events.
  • Overpayment and balance checks run in the same transaction as the capture.
  • When the dashboard webhook is not configured, a recovery job polls the provider with a signed request and applies the same capture function; the webhook and the poller race safely because capture is idempotent.

How we tested it (and what the tests missed)

We used four layers, each catching something the others could not:

  1. Unit tests with a fake database client for service-layer rules: who may call what, what is forwarded, that the idempotency key is required. (Fast; catches wiring and role mistakes.)
  2. Rolled-back SQL dry runs against the real database. Every migration, and every new function, was first run inside BEGIN ... ROLLBACK against the hosted database with real actors: approve twice, reject without a note, assign an executive from another branch, confirm as an executive, mark unavailable twice. Nothing persists, but the real triggers, constraints and grants all execute. This is the technique we would recommend most strongly.
  3. Scripted browser scenarios for the scan workflow: 50 scans at 3 to 4 ms per key, with and without gaps; slow human typing must not count; scanning with no Enter suffix; undo, clear, and over-scan. Exactly one confirm request must be sent.
  4. End-to-end runs on the live system with real logins in every role.

What layer 4 found that layers 1 to 3 did not: after all tests passed, the very first real “confirm receiving” returned an internal server error. A downstream guard on the purchase table requires a posted purchase to carry the ledger transaction id; our function posted the purchase without linking it. The unit tests used a fake database and so never met the guard; the dry run had not exercised that exact path. The fix was one line (set the transaction id in the same UPDATE) and a new migration, but it would have been a production outage on the first day. Lesson: an integration test through the real database is not optional for money and stock.

A second finding came from review rather than testing: when a request was marked unavailable, restocked, and marked unavailable again, the notification’s de-duplication key was identical and the second call failed with a unique violation, which would have returned a 500 and lost the new expected-back date. Fixed by making each marking its own notification key.

Trade-offs, honestly

  • SQL functions vs application code. Strong guarantees and one place for rules, but less readable and a smaller pool of people who can review them. Mitigation: dry runs, tests, and naming functions after the command they implement.
  • Idempotency table growth. Every command leaves a row. Fine at our volume (it was the largest table at under 600 KB), but it needs an expiry job at scale.
  • Local counting. The scan counter counts in the browser and sends one confirm. Cheap and idempotent, but a browser crash mid-count loses the count. We accepted that because nothing is booked until the confirm.
  • Immutable ledgers. Stock and payment records cannot be deleted by design (triggers enforce it), so test data is hidden with soft deletes and excluded from totals rather than removed.

Checklist you can reuse

  1. Make each money or stock operation one transactional command.
  2. Lock the narrowest thing that makes the command correct.
  3. Require an idempotency key and store a hash of the request with it.
  4. Replay the stored result for repeats; return “in progress” for concurrent duplicates.
  5. Never treat a browser redirect as proof of payment; verify provider signatures in constant time and compare amounts.
  6. Dry-run every migration in a rolled-back transaction with real actors.
  7. Always run one real end-to-end flow before you call it done.

AI use: Written with AI assistance from my own notes and project facts, then reviewed by me. Images are AI-generated. How I use AI

Loading reactions…

Working on something similar? Let's talk.

Same problem, a question about this article, a collaboration, or an open-source project you would like me to contribute to. Pick whichever door you like: