
Order Fulfillment State Machine: Design It So Orders Never Get Stuck
An order that sits in "processing" for three weeks is rarely a warehouse problem. Usually it's a modeling problem. The order's status lives in a free-text column, a boolean, or a mix of flags that nobody can reason about, so nothing in the system can tell that an order is stuck. This guide shows how to design an order fulfillment state machine that makes stuck orders impossible to miss: the data model, how to enforce transitions under concurrency, how to take in payment webhooks safely, how to publish events without losing them, and how to find and recover orders that stopped moving.
If you are dealing with a backlog right now, the operational side (sorting by cause, reconciling payments, shipping) is covered in our guide to clearing a backlog of unfulfilled orders. This article is about the system underneath, so the next backlog is smaller and easier to see.
Why orders get stuck: four design flaws
Most stuck orders trace back to one of these:
- Implicit state. Status is derived from a mix of columns (
paid_at IS NOT NULL AND shipped = false AND ...). Every query writes the logic again, slightly differently, and an order can land in a combination no one planned for. - Unrestricted writes. Any code path can set
status = 'shipped'. Nothing stops a cancelled order from being shipped, or a shipped order from going back to "pending". - Dual writes. The code updates the database and then calls a broker, an ERP or a shipping API. If the process dies between the two, one side never hears about the change.
- Missed or repeated webhooks. Payment providers deliver events at least once and not always in order. A handler that assumes exactly-once, in-order delivery will eventually skip a payment or apply it twice.
A state machine fixes the first two directly. The inbox and outbox patterns below fix the other two.
Designing the order fulfillment state machine
Start by separating dimensions that change independently. Payment and fulfillment are different lifecycles: an order can be paid and on hold, or shipped and then partly refunded. Folding them into one status enum causes a combinatorial explosion of states like paid_partially_shipped_refund_pending.
Shopify's API is a useful reference here. Its order-level fulfillment_status field is marked for deprecation in favor of the status on a separate FulfillmentOrder resource, and a FulfillmentOrder has its own statuses, including OPEN, SCHEDULED and ON_HOLD. The lesson for your own system: fulfillment state belongs to the unit that actually ships (a fulfillment order per warehouse or location), not only to the order as a whole.
A workable set of states for most stores:
- Payment:
pending,authorized,captured,failed,refunded,partially_refunded. - Fulfillment:
unfulfilled,allocated,picking,shipped,delivered,on_hold,cancelled.
Then define events (what happened) and guards (conditions that must hold). For example, the allocate event moves fulfillment from unfulfilled to allocated, but only if payment is captured (or authorized, if you capture at shipment). Write the allowed transitions down as data, not as scattered if statements:
const fulfillmentTransitions = {
unfulfilled: { allocate: "allocated", hold: "on_hold", cancel: "cancelled" },
allocated: { start_pick: "picking", hold: "on_hold", cancel: "cancelled" },
picking: { ship: "shipped", hold: "on_hold" },
shipped: { deliver: "delivered" },
on_hold: { release: "unfulfilled", cancel: "cancelled" },
delivered: {},
cancelled: {},
} as const;
const guards = {
allocate: (o) => ["captured", "authorized"].includes(o.payment_state),
ship: (o) => o.payment_state !== "refunded",
};
Keeping the table as data means you can render it as a diagram, test every pair of state and event, and review changes to it in a pull request.
Make on_hold carry a reason
on_hold is where orders go to be forgotten. Require a hold_reason (address problem, fraud review, out of stock, payment mismatch) and an owner every time an order enters it. A hold without a reason is just "stuck" under another name.
Data model: current state plus an append-only history
You need two things: the current state, for fast queries, and the history, for audit and debugging. A practical schema in PostgreSQL:
CREATE TABLE orders (
id uuid PRIMARY KEY,
payment_state text NOT NULL DEFAULT 'pending',
fulfillment_state text NOT NULL DEFAULT 'unfulfilled',
hold_reason text,
version integer NOT NULL DEFAULT 0,
state_entered_at timestamptz NOT NULL DEFAULT now(),
next_check_at timestamptz,
created_at timestamptz NOT NULL DEFAULT now(),
CHECK (fulfillment_state <> 'on_hold' OR hold_reason IS NOT NULL)
);
CREATE TABLE order_transitions (
id bigserial PRIMARY KEY,
order_id uuid NOT NULL REFERENCES orders(id),
dimension text NOT NULL, -- 'payment' | 'fulfillment'
from_state text NOT NULL,
to_state text NOT NULL,
event text NOT NULL,
actor text NOT NULL, -- user id, 'stripe-webhook', 'sweeper'
cause_id text, -- provider event id, request id
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX orders_due_idx ON orders (next_check_at)
WHERE fulfillment_state NOT IN ('delivered', 'cancelled');
Two columns do most of the work later. state_entered_at tells you how long an order has been in its current state. next_check_at is a deadline: when the order enters a state, you set it to "now plus the time this state is allowed to last". The partial index keeps the "what is overdue?" query cheap, because finished orders never appear in it.
Trade-off: full event sourcing or state plus a log? Event sourcing (deriving state only from events) gives you a perfect history, but every read model, report and admin screen gets more complex. For most commerce teams, a current-state row plus an append-only transition log written in the same transaction gives you most of the audit value at a fraction of the cost.
Enforcing transitions under concurrency
Two workers, a webhook and an admin can all touch the same order at the same moment. You have two standard options.
Pessimistic locking. Lock the row, check the transition, write. In PostgreSQL, SELECT ... FOR UPDATE blocks other transactions that try to update or lock the same row until yours ends.
async function apply(db, orderId, event, actor, causeId) {
return db.tx(async (tx) => {
const o = await tx.one(
"SELECT * FROM orders WHERE id = $1 FOR UPDATE", [orderId]);
const to = fulfillmentTransitions[o.fulfillment_state]?.[event];
if (!to) throw new InvalidTransition(o.fulfillment_state, event);
if (guards[event] && !guards[event](o)) throw new GuardFailed(event);
await tx.none(
`UPDATE orders
SET fulfillment_state = $2, state_entered_at = now(),
next_check_at = now() + $3::interval, version = version + 1
WHERE id = $1`,
[orderId, to, slaFor(to)]);
await tx.none(
`INSERT INTO order_transitions
(order_id, dimension, from_state, to_state, event, actor, cause_id)
VALUES ($1, 'fulfillment', $2, $3, $4, $5, $6)`,
[orderId, o.fulfillment_state, to, event, actor, causeId]);
await tx.none(
`INSERT INTO outbox (aggregate_id, type, payload)
VALUES ($1, $2, $3)`,
[orderId, `order.${to}`, { orderId, from: o.fulfillment_state, to }]);
return to;
});
}
Optimistic concurrency. Read without locking, then write with WHERE id = $1 AND version = $2. If zero rows changed, someone else got there first: reload and retry or reject. This avoids holding locks and works well when conflicts are rare. Pessimistic locking is simpler to reason about when conflicts are common, such as a webhook and a worker racing on the same freshly paid order.
Either way, the rule is the same: every state change goes through one function, and that function writes the new state, the history row and the outbound event in one transaction. Never make an HTTP call to a carrier or payment provider while holding the row lock.
Taking payment webhooks in safely: the inbox
Stripe delivers webhooks at least once and does not guarantee their order. One guide summarizes the practical consequences: the same event can arrive twice, and if your endpoint errors, Stripe retries for up to three days. Another points out that Stripe's own best practices recommend logging the event IDs you have processed and skipping ones already logged.
A robust design splits receipt from processing:
- The endpoint verifies the signature against the raw body.
- It inserts the event into an
inboxtable with a unique key on(provider, event_id), usingON CONFLICT DO NOTHING. - It returns 2xx immediately, duplicate or not.
- A worker claims unprocessed inbox rows, fetches the current state of the payment from the provider, and calls
apply()with the provider event id ascause_id.
CREATE TABLE inbox (
provider text NOT NULL,
event_id text NOT NULL,
payload jsonb NOT NULL,
received_at timestamptz NOT NULL DEFAULT now(),
processed_at timestamptz,
PRIMARY KEY (provider, event_id)
);
Step 4 handles ordering: instead of trusting the order events arrived in, the worker asks the provider for the current status and moves the order to match. Re-reading current state is also what Hookdeck's Stripe guide recommends over sorting events by their created timestamp. A unique constraint in the database, not an in-memory set or a cache key with a TTL, is what makes the dedupe hold across restarts and multiple workers.
Publishing events without losing them: the outbox
Your warehouse system, ERP, email service and commission engine need to know when an order changes state. Writing to the database and then publishing to a broker is the dual-write problem. The transactional outbox pattern solves it by writing the message to an outbox table in the same transaction as the business change; a separate relay publishes it afterwards. Microservices.io notes the key guarantee: messages are sent if and only if the database transaction commits.
The relay can be a small worker using FOR UPDATE SKIP LOCKED, which skips rows that another transaction has already locked, so several relay instances can run without picking the same rows:
loop:
BEGIN
rows = SELECT * FROM outbox
WHERE published_at IS NULL
ORDER BY id LIMIT 100
FOR UPDATE SKIP LOCKED
for row in rows:
publish(row) -- broker, webhook, or HTTP call
UPDATE outbox SET published_at = now() WHERE id = row.id
COMMIT
sleep if rows was empty
If the relay crashes after publishing but before committing, the row is published again. That is the intended trade-off: at-least-once delivery. Consumers must therefore be idempotent too, using the outbox row id as their dedupe key, the same way your inbox uses the provider's event id.
Detecting stuck orders: deadlines, not reports
With next_check_at set on every transition, finding stuck orders is one indexed query run by a scheduled sweeper:
SELECT id, payment_state, fulfillment_state, state_entered_at
FROM orders
WHERE next_check_at < now()
AND fulfillment_state NOT IN ('delivered', 'cancelled')
ORDER BY next_check_at
LIMIT 500
FOR UPDATE SKIP LOCKED;
For each overdue order, the sweeper takes one specific action based on the state:
unfulfilledwith paymentpending: ask the payment provider for the real status. A lost webhook shows up here.unfulfilledwith paymentcaptured: allocation never ran. Re-emit the event or alert operations.pickingorallocatedfor too long: move toon_holdwith a reason and an owner.shippedwithout delivery confirmation: query the carrier's tracking.
Every action goes through apply(), with actor = 'sweeper', so the history shows exactly what the automation did. Add a separate daily reconciliation that compares payments the provider reports as captured against orders still marked unpaid, and pulls missed events from the provider's events API after any outage.
Network marketing: commissions depend on the state machine
In network marketing companies, the order state machine also drives money owed to distributors. Commissions, rank qualification and volume should be calculated from state transitions, not from "order created". That means crediting volume on captured (or on delivered, if your plan says so) and generating a reversing entry on refunded, consumed from the outbox with idempotent handlers. If the compensation engine reads order rows directly with its own interpretation of status, sooner or later it will pay on orders that were cancelled. This is one of the reasons we build commissions, store and payments on the same event stream in our network marketing platform, Ariani.
Common mistakes
- Storing one
statusfield for payment, fulfillment and returns together. - Allowing direct
UPDATE orders SET status = ...from admin tools, scripts or migrations, bypassing the transition function. - Deduplicating webhooks with a cache key that expires before the provider stops retrying.
- Calling external APIs inside the database transaction that holds the order lock.
- Using
on_holdwithout a reason, an owner or a deadline. - Writing a sweeper that only reports. It should take an action or escalate to a named person.
- Relying on event arrival order instead of re-reading current state from the source of truth.
Implementation checklist
- Payment and fulfillment modeled as separate state machines.
- Transitions and guards defined as data and covered by tests for every state and event pair.
- A single
apply()function is the only writer of state columns. - State, history row and outbox row written in one transaction.
- Inbox table with a unique key on provider and event id; endpoint returns 2xx fast.
- Workers re-read current state from the provider before transitioning.
- Outbox relay with
FOR UPDATE SKIP LOCKED; idempotent consumers. next_check_atset on every transition, with a partial index and a sweeper.on_holdrequires a reason and an owner (enforced with a CHECK constraint).- Daily reconciliation against the payment provider.
If your current platform can't support this without a rewrite of core order logic, that is usually the point to consider custom software built around your order flow, designed so state, payments and integrations share one source of truth.
Frequently asked questions
Should I use a state machine library or write my own?
A transition table plus one apply() function is a small amount of code and is easy to test. Libraries help when you need nested or parallel states, visualization or long-running timers. Either way, the guarantees come from the database: transactions, row locks and unique constraints.
Do I need a workflow engine for order fulfillment?
Not usually at the start. A state column, an outbox and a sweeper cover most stores. A dedicated workflow engine becomes worth evaluating when one order spans many services with long waits, compensations and human approvals.
How do I migrate existing orders to the new model?
Write a one-off script that maps each existing combination of flags to one payment state and one fulfillment state, logs every mapping as a transition with actor = 'migration', and sends any combination it can't map to on_hold with a reason. Run it in dry-run mode first and review the orders it couldn't map.
Comments
No comments yet. Be the first to share what you think.


